VideoViewedJob.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace App\Jobs;
  3. use App\Model\Mongo\VideoHistoryModel;
  4. use App\Model\VideoModel;
  5. use App\Repositories\UserRepository;
  6. use Carbon\Carbon;
  7. use Hyperf\AsyncQueue\Job;
  8. use Modules\Api\Services\VideoService;
  9. class VideoViewedJob extends Job
  10. {
  11. public $params;
  12. public function __construct($params)
  13. {
  14. // 这里最好是普通数据,不要使用携带 IO 的对象,比如 PDO 对象
  15. $this->params = $params;
  16. }
  17. public function handle()
  18. {
  19. $arrUserCodes = [];
  20. $nowDate = Carbon::now()->toDateString();
  21. $videoService = make(VideoService::class);
  22. if (!empty($this->params)) {
  23. foreach ($this->params as $item) {
  24. $data = [
  25. 'date' => $item['date'],
  26. 'user_id' => $item['user_id'],
  27. 'video_id' => $item['video_id'],
  28. ];
  29. $key = $data['date'] . '_'. $data['user_id']. '_'. $data['video_id'];
  30. $_id = substr(md5($key), 8, 16);
  31. $data['_id'] = $_id;
  32. $count = make(VideoHistoryModel::class)->db()->countDocuments(
  33. ['_id' => $_id]
  34. );
  35. if ($count) {
  36. continue;
  37. }
  38. // 自动增加观看次数.
  39. $videoObj = VideoModel::where(['id' => $item['video_id']])->first(['id', 'watch', 'real_watch']);
  40. if (!empty($videoObj)) {
  41. $videoObj->watch++;
  42. $videoObj->real_watch++;
  43. $videoObj->save();
  44. }
  45. // $userDayCount = make(VideoHistoryModel::class)->db()->countDocuments(
  46. // ['uid' => $item['user_id'],'date' => $data['date']]
  47. // );
  48. // 不管是不是会员,超过每日观影次数没有,都记录.
  49. $videoService->addHistory($data);
  50. if (!isset($arrUserCodes[$item['user_code']])) {
  51. $arrUserCodes[$item['user_code']] = $item['user_code'];
  52. }
  53. }
  54. }
  55. if (!empty($arrUserCodes)) {
  56. $userRepo = make(UserRepository::class);
  57. foreach ($arrUserCodes as $k => $userCode) {
  58. // 清理用户缓存.
  59. $userRepo->delUserCache($userCode);
  60. }
  61. }
  62. }
  63. }