DownloadRepository.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. $token = JWTAuth::decode(JWTAuth::getToken());
  46. if(!$token || $token['type'] != 1){
  47. return Response::create([
  48. 'message' => '获取登陆信息失败',
  49. 'status_code' => 500
  50. ]);
  51. }
  52. $uid = $token['user']->id;
  53. $username = $token['user']->username;
  54. //下载中
  55. if($this->download->where('uid', $uid)->where('download_status', 0)->where('download_type', $request['download_type'])->exists()){
  56. return Response::create([
  57. 'message' => '当前有任务未完成,请等待',
  58. 'status_code' => 500
  59. ]);
  60. }
  61. $data = [
  62. 'uid' => $uid,
  63. 'username' => $username,
  64. 'download_type' => $request['download_type'],
  65. 'download_status' => 0,
  66. 'params' => json_encode($request),
  67. 'url' => ''
  68. ];
  69. DB::beginTransaction();
  70. try{
  71. $this->download->create($data);
  72. DB::commit();
  73. return Response::create();
  74. }catch (QueryException $exception){
  75. DB::rollBack();
  76. Log::debug('生成下载内容:'.$exception->getMessage());
  77. return Response::create([
  78. 'message' => '操作失败,请重试',
  79. 'error' => $exception->getMessage(),
  80. 'status_code' => 500
  81. ]);
  82. }
  83. }
  84. }