DownloadRepository.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Administrator
  5. * Date: 2019/6/11
  6. * Time: 10:45
  7. */
  8. namespace App\Repositories;
  9. use App\Models\Download;
  10. use Illuminate\Database\QueryException;
  11. use Dingo\Api\Http\Response;
  12. use Illuminate\Support\Facades\DB;
  13. use Illuminate\Support\Facades\Log;
  14. use Symfony\Component\HttpKernel\Exception\HttpException;
  15. use Tymon\JWTAuth\Facades\JWTAuth;
  16. class DownloadRepository
  17. {
  18. public function __construct(Download $download)
  19. {
  20. $this->download = $download;
  21. }
  22. /**
  23. * 下载列表
  24. */
  25. public function lists($request)
  26. {
  27. $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
  28. $where = [];
  29. if(isset($request['content'])){
  30. $where[] = ['content', 'like', "%{$request['content']}%"];
  31. }
  32. if(isset($request['download_type'])){
  33. $where[] = ['download_type', $request['download_type']];
  34. }
  35. return $this->download
  36. ->where($where)
  37. ->orderBy('id','desc')
  38. ->paginate($perPage);
  39. }
  40. /**
  41. * 添加下载
  42. */
  43. public function create($request)
  44. {
  45. Log::debug('添加下载数据:'.json_encode($request));
  46. $token = JWTAuth::decode(JWTAuth::getToken());
  47. if(!$token || $token['type'] != 1){
  48. return Response::create([
  49. 'message' => '获取登陆信息失败',
  50. 'status_code' => 500
  51. ]);
  52. }
  53. $uid = $token['user']->id;
  54. $username = $token['user']->username;
  55. //下载中
  56. if($this->download->where('uid', $uid)->where('download_status', 0)->where('download_type', $request['download_type'])->exists()){
  57. return Response::create([
  58. 'message' => '当前有任务未完成,请等待',
  59. 'status_code' => 500
  60. ]);
  61. }
  62. $data = [
  63. 'uid' => $uid,
  64. 'username' => $username,
  65. 'download_type' => $request['download_type'],
  66. 'download_status' => 0,
  67. 'params' => json_encode($request),
  68. 'url' => ''
  69. ];
  70. DB::beginTransaction();
  71. try{
  72. $this->download->create($data);
  73. DB::commit();
  74. return Response::create();
  75. }catch (QueryException $exception){
  76. DB::rollBack();
  77. Log::debug('生成下载内容:'.$exception->getMessage());
  78. return Response::create([
  79. 'message' => '操作失败,请重试',
  80. 'error' => $exception->getMessage(),
  81. 'status_code' => 500
  82. ]);
  83. }
  84. }
  85. }