wesmiler 2 yıl önce
ebeveyn
işleme
2fe1a70c1b

+ 32 - 0
app/Http/Controllers/Api/v1/LiveController.php

@@ -4,6 +4,7 @@ namespace App\Http\Controllers\Api\v1;
 use App\Http\Controllers\Api\webApp;
 use App\Http\Validator\LiveValidator;
 use App\Services\LiveService;
+use App\Services\RedisService;
 
 /**
  * 在线直播
@@ -13,6 +14,37 @@ class LiveController extends webApp
 {
 
     /**
+     * 列表
+     * @return array
+     */
+    public function index()
+    {
+       try {
+        $params = request()->post();
+        $pageSize = request()->post('pageSize', 0);
+        $datas = LiveService::make()->getDataList($params, $pageSize,'', $this->userId);
+        return message(1010, true, $datas);
+       } catch (\Exception $exception){
+           RedisService::set("caches:request:error_live_index", ['error'=>$exception->getMessage(),'trace'=>$exception->getTrace()], 7200);
+           return message(1018, false, ['error'=>env('APP_DEBUG')? $exception->getMessage() : '']);
+       }
+    }
+
+    /**
+     * 播放与浏览
+     * @return array
+     */
+    public function updatePlay()
+    {
+        $id = request()->post('id',0);
+        if(!$result = LiveService::make()->updatePlay($this->userId, $id)){
+            return message(LiveService::make()->getError(), false);
+        }else{
+            return message(LiveService::make()->getError(), true, $result);
+        }
+    }
+
+    /**
      * 获取流地址
      * @return array
      */

+ 74 - 58
app/Services/Api/VideoCollectService.php

@@ -169,15 +169,15 @@ class VideoCollectService extends BaseService
      * @param $type
      * @return array|mixed
      */
-    public function getCollectCacheInfo($userId, $collectId, $type)
+    public function getCollectCacheInfo($userId, $collectId, $type, $sourceType=1)
     {
-        $cacheKey = "caches:videos:collect:temp_{$userId}_{$collectId}_{$type}";
+        $cacheKey = "caches:videos:collect:temp_{$userId}_{$collectId}_{$type}_{$sourceType}";
         $info = RedisService::get($cacheKey);
         if($info || RedisService::exists($cacheKey)){
             return $info;
         }
 
-        $info = $this->model->where(['user_id'=> $userId,'collect_id'=> $collectId,'type'=> $type])->select(['id','user_id','status'])->first();
+        $info = $this->model->where(['user_id'=> $userId,'collect_id'=> $collectId,'source_type'=>$sourceType,'type'=> $type])->select(['id','user_id','status'])->first();
         $info = $info? $info->toArray() : [];
         if($info){
             RedisService::set($cacheKey, $info, rand(10,30));
@@ -186,18 +186,23 @@ class VideoCollectService extends BaseService
         return $info;
     }
 
-    public function getRecommendData($userId)
+    /**
+     * 推荐数据
+     * @param $userId 用户
+     * @return array|mixed
+     */
+    public function getRecommendData($userId, $type=1)
     {
-        $cacheKey = "caches:videos:recommend:{$userId}";
+        $cacheKey = "caches:videos:recommend:{$userId}_{$type}";
         $data = RedisService::get($cacheKey);
         if($data || RedisService::exists($cacheKey)){
             return $data? $data : [];
         }
 
-        $arr = ['uids'=>[$userId],'tags'=>[]];
-        $datas = $this->model->where(['user_id'=> $userId,'status'=>1,'mark'=>1])
+        $arr = ['uids'=>[$userId],'tags'=>[],'category'=>[]];
+        $datas = $this->model->where(['user_id'=> $userId,'source_type'=> $type,'status'=>1,'mark'=>1])
             ->where('collect_uid','>', 0)
-            ->select(['collect_uid','tags'])
+            ->select(['collect_uid','tags','category_id'])
             ->orderRaw('rand()')
             ->limit(rand(3,5))
             ->get();
@@ -206,11 +211,16 @@ class VideoCollectService extends BaseService
             foreach ($datas as $item)
             {
                 $uid = isset($item['collect_uid'])? $item['collect_uid'] : 0;
+                $categoryId = isset($item['category_id'])? $item['category_id'] : 0;
                 $tags = isset($item['tags'])? explode(',', $item['tags']) : [];
                 if($uid){
                     $arr['uids'][] = $uid;
                 }
 
+                if($categoryId){
+                    $arr['category'][] = $categoryId;
+                }
+
                 if($tags){
                     $tags = array_filter($tags);
                     $arr['tags'] = array_merge($arr['tags'], $tags);
@@ -234,67 +244,73 @@ class VideoCollectService extends BaseService
      */
     public function collect($userId, $params)
     {
-        $collectId = isset($params['id'])? intval($params['id']) : 0;
-        $type = isset($params['type'])? intval($params['type']) : 2;
-        $status = isset($params['status'])? intval($params['status']) : 1;
-        if($collectId<=0 || !in_array($type, [2,3]) || !in_array($status, [1,2])){
-            $this->error = 2014;
-            return false;
-        }
+        try {
+            $collectId = isset($params['id']) ? intval($params['id']) : 0;
+            $type = isset($params['type']) ? intval($params['type']) : 2;
+            $status = isset($params['status']) ? intval($params['status']) : 1;
+            if ($collectId <= 0 || !in_array($type, [2, 3]) || !in_array($status, [1, 2])) {
+                $this->error = 2014;
+                return false;
+            }
 
-        $collectInfo = $this->getCollectCacheInfo($userId, $collectId, $type);
-        $id = isset($collectInfo['id'])? $collectInfo['id'] : 0;
+            $collectInfo = $this->getCollectCacheInfo($userId, $collectId, $type);
+            $id = isset($collectInfo['id']) ? $collectInfo['id'] : 0;
 
-        // 信息
-        $info = VideoModel::where(['id'=> $collectId,'mark'=>1])->select(['id','user_id','tags'])->first();
-        $collectUid = isset($info['user_id'])? $info['user_id'] : 0;
-        if(empty($info)){
-            $this->error = 1039;
-            return false;
-        }
+            // 信息
+            $info = VideoModel::where(['id' => $collectId, 'mark' => 1])->select(['id', 'user_id', 'tags'])->first();
+            $collectUid = isset($info['user_id']) ? $info['user_id'] : 0;
+            if (empty($info)) {
+                $this->error = 1039;
+                return false;
+            }
 
-        $data = [
-            'user_id'=> $userId,
-            'type'=> $type,
-            'collect_id'=> $collectId,
-            'collect_uid'=> $collectUid,
-            'tags'=> isset($info['tags'])? $info['tags'] : '',
-            'update_time'=> time(),
-            'status'=> $status,
-            'mark'=> 1,
-        ];
+            $data = [
+                'user_id' => $userId,
+                'type' => $type,
+                'source_type' => 1,
+                'collect_id' => $collectId,
+                'collect_uid' => $collectUid,
+                'tags' => isset($info['tags']) ? $info['tags'] : '',
+                'update_time' => time(),
+                'status' => $status,
+                'mark' => 1,
+            ];
+
+            DB::beginTransaction();
+            if (!$id) {
+                $data['create_time'] = time();
+                if (!$this->model->insertGetId($data)) {
+                    DB::rollBack();
+                    return false;
+                }
+            } else {
+                if (!$this->model->where('id', $id)->update($data)) {
+                    DB::rollBack();
+                    return false;
+                }
+            }
 
-        DB::beginTransaction();
-        if(!$id){
-            $data['create_time'] = time();
-            if(!$this->model->insertGetId($data)){
-                DB::rollBack();
-                return false;
+            $updateData = ['update_time' => time()];
+            if ($type == 2) {
+                $updateData['collect_num'] = DB::raw('collect_num ' . ($status == 1 ? '+ 1' : '-1'));
+            } else if ($type == 3) {
+                $updateData['like_num'] = DB::raw('like_num ' . ($status == 1 ? '+ 1' : '-1'));
             }
-        }else{
-            if(!$this->model->where('id', $id)->update($data)){
+            if (!VideoModel::where(['id' => $collectId, 'mark' => 1])->update($updateData)) {
                 DB::rollBack();
                 return false;
             }
-        }
 
-        $updateData = ['update_time'=>time()];
-        if($type == 2){
-            $updateData['collect_num'] = DB::raw('collect_num '.($status==1?'+ 1':'-1'));
-        }else if ($type == 3){
-            $updateData['like_num'] = DB::raw('like_num '.($status==1?'+ 1':'-1'));
-        }
-        if(!VideoModel::where(['id'=> $collectId,'mark'=>1])->update($updateData)){
-            DB::rollBack();
+            $this->error = 1002;
+            DB::commit();
+            RedisService::clear("caches:videos:collect:u{$userId}_c{$collectId}_{$type}");
+            RedisService::clear("caches:videos:collect:temp_{$userId}_{$collectId}_{$type}_1");
+            RedisService::clear("caches:videos:recommend:{$userId}_1");
+            return true;
+        }catch (\Exception $exception){
+            $this->error = $exception-> getMessage();
             return false;
         }
-
-        $this->error = 1002;
-        DB::commit();
-        RedisService::clear("caches:videos:collect:u{$userId}_c{$collectId}_{$type}");
-        RedisService::clear("caches:videos:collect:temp_{$userId}_{$collectId}_{$type}");
-        RedisService::clear("caches:videos:recommend:{$userId}");
-        return true;
     }
 
     /**

+ 4 - 5
app/Services/Api/VideoService.php

@@ -302,8 +302,8 @@ class VideoService extends BaseService
                     'status'=> 1,
                 ];
                 VideoCollectModel::insert($data);
-                RedisService::set("caches:videos:collect:temp_{$userId}_{$id}_1", $data, rand(10,30));
-                RedisService::clear("caches:videos:recommend:{$userId}");
+                RedisService::set("caches:videos:collect:temp_{$userId}_{$id}_1_1", $data, rand(10,30));
+                RedisService::clear("caches:videos:recommend:{$userId}_1");
             }
 
             // 浏览量
@@ -311,7 +311,6 @@ class VideoService extends BaseService
         }
 
         return $info;
-
     }
 
     /**
@@ -343,8 +342,8 @@ class VideoService extends BaseService
                 'status'=> 1,
             ];
             VideoCollectModel::insert($data);
-            RedisService::set("caches:videos:collect:temp_{$userId}_{$id}_1", $data, rand(10,30));
-            RedisService::clear("caches:videos:recommend:{$userId}");
+            RedisService::set("caches:videos:collect:temp_{$userId}_{$id}_1_1", $data, rand(10,30));
+            RedisService::clear("caches:videos:recommend:{$userId}_1");
         }
 
         // 浏览量

+ 159 - 0
app/Services/LiveService.php

@@ -15,7 +15,9 @@ use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
 use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
 use App\Models\LiveModel;
 use App\Models\MemberModel;
+use App\Models\VideoCollectModel;
 use App\Services\Api\MemberCollectService;
+use App\Services\Api\VideoCollectService;
 use Darabonba\OpenApi\Models\Config;
 use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
 use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
@@ -57,6 +59,102 @@ class LiveService extends BaseService
         return self::$instance;
     }
 
+    /**
+     * 列表数据
+     * @param $params
+     * @param int $pageSize
+     * @return array
+     */
+    public function getDataList($params, $pageSize = 18, $field = '', $userId=0)
+    {
+        $where = ['a.mark' => 1,'a.status'=>2,'b.mark'=>1];
+        $field = $field? $field : 'lev_a.*';
+        $order = 'rand()';
+        $model = $this->model->with(['member'])->from('videos as a')
+            ->leftJoin('member as b', 'b.id', '=', 'a.user_id')
+            ->where($where)
+            ->where(function ($query) use ($params) {
+                $type = isset($params['type']) ? $params['type'] : 0;
+                if ($type > 0) {
+                    $query->where('a.type', $type);
+                }
+
+                $uid = isset($params['user_id']) ? $params['user_id'] : 0;
+                if ($uid > 0) {
+                    $query->where('a.user_id', $uid);
+                }else{
+                    $query->where('a.status', 2);
+                }
+            })
+            ->where(function ($query) use ($params) {
+                $keyword = isset($params['kw']) ? $params['kw'] : '';
+                if ($keyword) {
+                    $query->where('a.title', 'like', "%{$keyword}%")
+                        ->orWhere('a.tags', 'like', "%{$keyword}%")
+                        ->orWhere('a.description', 'like', "%{$keyword}%")
+                        ->orWhere('b.nickname', 'like', "%{$keyword}%");
+                }
+            });
+
+        // 推荐的数据
+        $countModel = clone $model;
+        $total = $countModel->where(function($query) use($params, $userId){
+            // 推荐视频数据
+            $isRecommend = isset($params['is_recommend']) ? $params['is_recommend'] : 0;
+            if ($isRecommend > 0) {
+                $recommendData = VideoCollectService::make()->getRecommendData($userId);
+                $uids = isset($recommendData['uids'])? $recommendData['uids'] : []; // 按用户推荐
+                $tags = isset($recommendData['tags'])? $recommendData['tags'] : [];  // 按标签推荐
+                if($uids){
+                    $query->orWhere(function($query) use($uids){
+                        $query->whereIn('a.user_id', $uids);
+                    });
+                }
+
+                if($tags){
+                    $query->orWhere(function($query) use($tags){
+                        foreach($tags as $tag){
+                            $query->where('a.tags', 'like',"%{$tag}%")
+                                ->orWhere('a.description','like',"%{$tag}%");
+                        }
+                    });
+                }
+            }
+        })->count('a.id');
+
+        if($total > 0){
+            // 关联推荐数据
+            $list = $countModel->selectRaw($field)
+                ->orderByRaw($order)
+                ->paginate($pageSize > 0 ? $pageSize : 9999999);
+        }else{
+            // 默认推荐数据
+            $list = $model->selectRaw($field)
+                ->orderByRaw($order)
+                ->paginate($pageSize > 0 ? $pageSize : 9999999);
+        }
+
+        $list = $list ? $list->toArray() : [];
+        if ($list && $list['data']) {
+            foreach ($list['data'] as &$item) {
+                $item['time_text'] = isset($item['create_time']) ? dateFormat($item['create_time'], 'Y-m-d H:i') : '';
+                $member = isset($item['member'])? $item['member'] : [];
+                if($member){
+                    $member['avatar'] = isset($member['avatar']) && $member['avatar']? get_image_url($member['avatar']) : get_image_url('/images/member/logo.png');
+                }
+                $item['like_num'] = isset($item['like_num']) && $item['like_num']? intval($item['like_num']) : 0;
+                $item['views'] = isset($item['views']) && $item['views']? intval($item['views']) : 0;
+                $item['member'] = $member;
+            }
+        }
+
+        return [
+            'pageSize' => $pageSize,
+            'total'    => isset($list['total']) ? $list['total'] : 0,
+            'list'     => isset($list['data']) ? $list['data'] : []
+        ];
+    }
+
     public function getInfo($id, $userId)
     {
         $info = $this->model->with(['member'])->where(['id'=> $id,'mark'=>1])->first();
@@ -76,18 +174,79 @@ class LiveService extends BaseService
             // 观看权限
             $info['view_limit'] = 0;
 
+            // 浏览历史
+            if(!VideoCollectService::make()->getCollectCacheInfo($userId, $id, 1)){
+                $data = [
+                    'user_id'=> $userId,
+                    'type'=> 1,
+                    'collect_id'=> $id,
+                    'collect_uid'=> isset($info['user_id'])? $info['user_id'] : 0,
+                    'tags'=> isset($info['tags'])? $info['tags'] : '',
+                    'create_time'=> time(),
+                    'status'=> 1,
+                ];
+                VideoCollectModel::insert($data);
+                RedisService::clear("caches:videos:recommend:{$userId}_2");
+            }
+
             // 更新播放量
             if(!RedisService::get("caches:live:player:{$userId}_{$id}")){
                 $this->model->where(['id'=> $id])->update(['views'=>DB::raw('views + 1'),'update_time'=>time()]);
                 RedisService::set("caches:live:player:{$userId}_{$id}", ['user_id'=> $userId,'id'=>$id], rand(600, 1800));
                 $info['views'] += 1;
             }
+
+
         }
 
         return $info;
     }
 
     /**
+     * 更新播放浏览历史
+     * @param $userId 用户ID
+     * @param $id 视频ID
+     * @return false
+     */
+    public function updatePlay($userId, $id)
+    {
+        // 浏览历史
+        if(!VideoCollectService::make()->getCollectCacheInfo($userId, $id, 1,2)){
+            $info = $this->model->from('live as a')
+                ->where(['a.id'=> $id,'a.mark'=>1])
+                ->select(['a.id','a.category_id','a.user_id'])
+                ->first();
+
+            if(empty($info)){
+                return false;
+            }
+
+            $data = [
+                'user_id'=> $userId,
+                'type'=> 1,
+                'source_type'=> 2,
+                'collect_id'=> $id,
+                'category_id'=> isset($info['category_id'])? $info['category_id'] : 0,
+                'collect_uid'=> isset($info['user_id'])? $info['user_id'] : 0,
+                'create_time'=> time(),
+                'status'=> 1,
+            ];
+            VideoCollectModel::insert($data);
+            RedisService::set("caches:videos:collect:temp_{$userId}_{$id}_1_2", $data, rand(10,30));
+            RedisService::clear("caches:videos:recommend:{$userId}_1_2");
+        }
+
+        // 更新播放量
+        if(!RedisService::get("caches:live:player:{$userId}_{$id}")){
+            $this->model->where(['id'=> $id])->update(['views'=>DB::raw('views + 1'),'update_time'=>time()]);
+            RedisService::set("caches:live:player:{$userId}_{$id}", ['user_id'=> $userId,'id'=>$id], rand(600, 1800));
+            $info['views'] += 1;
+        }
+        $this->error = 1010;
+        return true;
+    }
+
+    /**
      * 获取直播推流/拉流地址
      * @param $streamName
      * @param string $appName

+ 2 - 0
routes/api.php

@@ -47,9 +47,11 @@ Route::prefix('v1')->group(function(){
     Route::post('/index/video', [\App\Http\Controllers\Api\v1\IndexController::class, 'videoList']);
 
     // 直播
+    Route::get('/live/index', [\App\Http\Controllers\Api\v1\LiveController::class, 'index']);
     Route::get('/live/url', [\App\Http\Controllers\Api\v1\LiveController::class, 'getUrl']);
     Route::post('/live/create', [\App\Http\Controllers\Api\v1\LiveController::class, 'create']);
     Route::post('/live/info', [\App\Http\Controllers\Api\v1\LiveController::class, 'getInfo']);
+    Route::post('/live/play', [\App\Http\Controllers\Api\v1\LiveController::class, 'updatePlay']);
     Route::post('/live/category/search', [\App\Http\Controllers\Api\v1\LiveCategoryController::class, 'search']);
     Route::post('/live/category/options', [\App\Http\Controllers\Api\v1\LiveCategoryController::class, 'options']);