LiveService.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2017~2021 LARAVEL研发中心
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://www.laravel.cn
  8. // +----------------------------------------------------------------------
  9. // | Author: laravel开发员 <laravel.qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace App\Services;
  12. use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
  13. use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
  14. use App\Models\LiveModel;
  15. use App\Models\MemberModel;
  16. use App\Models\VideoCollectModel;
  17. use App\Services\Api\MemberCollectService;
  18. use App\Services\Api\VideoCollectService;
  19. use Darabonba\OpenApi\Models\Config;
  20. use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
  21. use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
  22. use Illuminate\Support\Facades\DB;
  23. /**
  24. * 在线直播服务管理-服务类
  25. * @author laravel开发员
  26. * @since 2020/11/11
  27. * Class LiveService
  28. * @package App\Services
  29. */
  30. class LiveService extends BaseService
  31. {
  32. // 静态对象
  33. protected static $instance = null;
  34. /**
  35. * 构造函数
  36. * @author laravel开发员
  37. * @since 2020/11/11
  38. * ConfigService constructor.
  39. */
  40. public function __construct()
  41. {
  42. $this->model = new LiveModel();
  43. }
  44. /**
  45. * 静态入口
  46. * @return SmsService|static|null
  47. */
  48. public static function make()
  49. {
  50. if (!self::$instance) {
  51. self::$instance = new static();
  52. }
  53. return self::$instance;
  54. }
  55. /**
  56. * 列表数据
  57. * @param $params
  58. * @param int $pageSize
  59. * @return array
  60. */
  61. public function getDataList($params, $pageSize = 18, $field = '', $userId=0)
  62. {
  63. $where = ['a.mark' => 1,'a.status'=>1,'b.mark'=>1];
  64. $field = $field? $field : 'lev_a.*';
  65. $order = 'rand()';
  66. $model = $this->model->with(['member'])->from('live as a')
  67. ->leftJoin('member as b', 'b.id', '=', 'a.user_id')
  68. ->where($where)
  69. ->where(function ($query) use ($params) {
  70. $type = isset($params['type']) ? $params['type'] : 0;
  71. if ($type > 0) {
  72. $query->where('a.type', $type);
  73. }
  74. $categoryId = isset($params['category_id']) ? $params['category_id'] : 0;
  75. if ($categoryId > 0) {
  76. $query->where('a.category_id', $categoryId);
  77. }
  78. $uid = isset($params['user_id']) ? $params['user_id'] : 0;
  79. if ($uid > 0) {
  80. $query->where('a.user_id', $uid);
  81. }
  82. })
  83. ->where(function ($query) use ($params) {
  84. $keyword = isset($params['kw']) ? $params['kw'] : '';
  85. if ($keyword) {
  86. $query->where('a.title', 'like', "%{$keyword}%")
  87. ->orWhere('a.description', 'like', "%{$keyword}%")
  88. ->orWhere('b.nickname', 'like', "%{$keyword}%");
  89. }
  90. })->where(function ($query) use ($userId) {
  91. if ($userId) {
  92. $query->where('a.visible_users', '=', '')
  93. ->orWhere('a.visible_users', 'like',"%{$userId},%")
  94. ->orWhere('a.manage_users', 'like',"%{$userId},%");
  95. }
  96. });
  97. // 推荐的数据
  98. $countModel = clone $model;
  99. $total = $countModel->where(function($query) use($params, $userId){
  100. // 推荐视频数据
  101. $isRecommend = isset($params['is_recommend']) ? $params['is_recommend'] : 0;
  102. if ($isRecommend > 0) {
  103. $recommendData = VideoCollectService::make()->getRecommendData($userId);
  104. $uids = isset($recommendData['uids'])? $recommendData['uids'] : []; // 按用户推荐
  105. $category = isset($recommendData['category'])? $recommendData['category'] : []; // 按标签推荐
  106. if($uids){
  107. $query->orWhere(function($query) use($uids){
  108. $query->whereIn('a.user_id', $uids);
  109. });
  110. }
  111. if($category){
  112. $query->orWhere(function($query) use($category){
  113. $query->whereIn('a.category_id', $category);
  114. });
  115. }
  116. }
  117. })->count('a.id');
  118. if($total > 0){
  119. // 关联推荐数据
  120. $list = $countModel->selectRaw($field)
  121. ->orderByRaw($order)
  122. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  123. }else{
  124. // 默认推荐数据
  125. $list = $model->selectRaw($field)
  126. ->orderByRaw($order)
  127. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  128. }
  129. $list = $list ? $list->toArray() : [];
  130. if ($list && $list['data']) {
  131. foreach ($list['data'] as &$item) {
  132. $item['time_text'] = isset($item['create_time']) ? dateFormat($item['create_time'], 'Y-m-d H:i') : '';
  133. $member = isset($item['member'])? $item['member'] : [];
  134. if($member){
  135. $member['avatar'] = isset($member['avatar']) && $member['avatar']? get_image_url($member['avatar']) : get_image_url('/images/member/logo.png');
  136. }
  137. $item['like_num'] = isset($item['like_num']) && $item['like_num']? intval($item['like_num']) : 0;
  138. $item['views'] = isset($item['views']) && $item['views']? intval($item['views']) : 0;
  139. $item['member'] = $member;
  140. }
  141. }
  142. return [
  143. 'pageSize' => $pageSize,
  144. 'total' => isset($list['total']) ? $list['total'] : 0,
  145. 'list' => isset($list['data']) ? $list['data'] : []
  146. ];
  147. }
  148. /**
  149. * 详情
  150. * @param $id
  151. * @param $userId
  152. * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
  153. */
  154. public function getInfo($id, $userId)
  155. {
  156. $info = $this->model->with(['member'])->where(['id'=> $id,'mark'=>1])->first();
  157. if($info && isset($info['member'])){
  158. if(isset($info['member']['avatar'])){
  159. $info['member']['avatar'] = $info['member']['avatar']? $info['member']['avatar'] : '/images/member/logo.png';
  160. $info['member']['avatar'] = get_image_url($info['member']['avatar']);
  161. }
  162. if($info['user_id'] == $userId){
  163. $info['is_follow'] = 1;
  164. }else{
  165. $checkFollow = MemberCollectService::make()->checkCollect($userId, $info['user_id'], 1);
  166. $info['is_follow'] = $checkFollow? 1 : 0;
  167. }
  168. // 观看权限
  169. $info['view_limit'] = 0;
  170. // 浏览历史
  171. if(!VideoCollectService::make()->getCollectCacheInfo($userId, $id, 1)){
  172. $data = [
  173. 'user_id'=> $userId,
  174. 'type'=> 1,
  175. 'collect_id'=> $id,
  176. 'collect_uid'=> isset($info['user_id'])? $info['user_id'] : 0,
  177. 'tags'=> isset($info['tags'])? $info['tags'] : '',
  178. 'create_time'=> time(),
  179. 'status'=> 1,
  180. ];
  181. VideoCollectModel::insert($data);
  182. RedisService::clear("caches:videos:recommend:{$userId}_2");
  183. RedisService::clear("caches:member:fans:{$userId}_{$id}_2");
  184. }
  185. // 更新播放量
  186. if(!RedisService::get("caches:live:player:{$userId}_{$id}")){
  187. $this->model->where(['id'=> $id])->update(['views'=>DB::raw('views + 1'),'update_time'=>time()]);
  188. RedisService::set("caches:live:player:{$userId}_{$id}", ['user_id'=> $userId,'id'=>$id], rand(600, 1800));
  189. $info['views'] += 1;
  190. }
  191. // 结束直播
  192. /*if($info['create_time'] <= time() - 2 * 86400 && $info['status'] == 1){
  193. $this->model->where(['id'=> $id])->update(['status'=>2,'update_time'=>time()]);
  194. $info['status'] = 2;
  195. }*/
  196. }
  197. return $info;
  198. }
  199. public function getUserList($params, $pageSize, $userId=0)
  200. {
  201. }
  202. /**
  203. * 更新播放浏览历史
  204. * @param $userId 用户ID
  205. * @param $id 视频ID
  206. * @return false
  207. */
  208. public function updatePlay($userId, $id)
  209. {
  210. // 浏览历史
  211. if(!VideoCollectService::make()->getCollectCacheInfo($userId, $id, 1,2)){
  212. $info = $this->model->from('live as a')
  213. ->where(['a.id'=> $id,'a.mark'=>1])
  214. ->select(['a.id','a.category','a.user_id'])
  215. ->first();
  216. if(empty($info)){
  217. return false;
  218. }
  219. $data = [
  220. 'user_id'=> $userId,
  221. 'type'=> 1,
  222. 'source_type'=> 2,
  223. 'collect_id'=> $id,
  224. 'category_id'=> isset($info['category'])? $info['category'] : 0,
  225. 'collect_uid'=> isset($info['user_id'])? $info['user_id'] : 0,
  226. 'create_time'=> time(),
  227. 'status'=> 1,
  228. ];
  229. VideoCollectModel::insert($data);
  230. RedisService::set("caches:videos:collect:temp_{$userId}_{$id}_1_2", $data, rand(10,30));
  231. RedisService::clear("caches:videos:recommend:{$userId}_1_2");
  232. RedisService::clear("caches:member:fans:{$userId}_{$id}_2");
  233. }
  234. // 更新播放量
  235. if(!RedisService::get("caches:player:live:{$userId}_{$id}")){
  236. $this->model->where(['id'=> $id])->update(['views'=>DB::raw('views + 1'),'update_time'=>time()]);
  237. RedisService::set("caches:player:live:{$userId}_{$id}", ['user_id'=> $userId,'id'=>$id], rand(6*3600, 86400));
  238. }
  239. $this->error = 1010;
  240. return true;
  241. }
  242. /**
  243. * 缓存数据
  244. * @param $id
  245. * @param int $status
  246. * @return array|mixed
  247. */
  248. public function getCacheInfo($id, $status=0)
  249. {
  250. $cacheKey = "caches:live:info:{$id}_{$status}";
  251. $info = RedisService::get($cacheKey);
  252. if($info){
  253. return $info;
  254. }
  255. $where = ['id' => $id, 'mark' => 1];
  256. if($status){
  257. $where['status'] = $status;
  258. }
  259. $info = $this->model->where($where)
  260. ->select(['id','user_id','create_time','end_time','views','reward_num','reward_total','like_num'])
  261. ->first();
  262. $info = $info? $info->toArray() : [];
  263. if($info){
  264. RedisService::set($cacheKey, $info, rand(3, 5));
  265. }
  266. return $info;
  267. }
  268. /**
  269. * 状态设置
  270. * @return bool
  271. */
  272. public function status()
  273. {
  274. $id = request()->post('id', 0);
  275. $status = request()->post('status', 2);
  276. if ($id && !$info = $this->getCacheInfo($id)) {
  277. $this->error = 2981;
  278. return false;
  279. }
  280. $updateData = ['status'=>$status, 'update_time'=> time()];
  281. if($status == 2){
  282. $updateData['end_time'] = time();
  283. }
  284. if($this->model->where(['id'=> $id,'mark'=>1])->update($updateData)){
  285. $this->error = 1002;
  286. $time = $info['end_time']? intval($info['end_time'] - $info['create_time']) : intval(time() - $info['create_time']);
  287. $info['status'] = $status;
  288. $info['live_hour'] = $time > 3600 ? intval($time/3600) : 0;
  289. $info['live_minute'] = $time%3600? intval($time%3600/60) : 0;
  290. $info['time_text'] = date('H:i', $info['create_time']);
  291. $info['end_time_text'] = date('H:i', $info['end_time']? $info['end_time'] : time());
  292. $info['fans_num'] = MemberCollectService::make()->getViewFansCountByType($info['user_id'], $id, 2);
  293. $info['new_fans'] = MemberCollectService::make()->getNewFansCount($info['user_id'], $id,2, $info['create_time']);
  294. return $info;
  295. }
  296. $this->error = 1003;
  297. return true;
  298. }
  299. /**
  300. * 获取直播推流/拉流地址
  301. * @param $streamName
  302. * @param string $appName
  303. * @param string $playType
  304. * @param int $expireTime
  305. * @return array
  306. */
  307. public function getLiveUrl($streamName, $appName = 'xlapp', $playType = 'rtmp', $expireTime = 1440)
  308. {
  309. $cachekey = "caches:live:urls:{$streamName}_{$appName}_{$playType}";
  310. $datas = RedisService::get($cachekey);
  311. if($datas){
  312. return $datas;
  313. }
  314. $playUrls = [];
  315. //未开启鉴权Key的情况下
  316. $pushDomain = ConfigService::make()->getConfigByCode('live_push_url');
  317. $playDomain = ConfigService::make()->getConfigByCode('live_play_url');
  318. $pushKey = ConfigService::make()->getConfigByCode('push_url_key');
  319. $playKey = ConfigService::make()->getConfigByCode('play_url_key');
  320. $timeStamp = time() + $expireTime * 60;
  321. if ($pushKey == '') {
  322. $pushUrl = 'rtmp://' . $pushDomain . '/' . $appName . '/' . $streamName;
  323. } else {
  324. $sstring = '/' . $appName . '/' . $streamName . '-' . $timeStamp . '-0-0-' . $pushKey;
  325. $md5hash = md5($sstring);
  326. $pushUrl = 'rtmp://' . $pushDomain . '/' . $appName . '/' . $streamName . '?auth_key=' . $timeStamp . '-0-0-' . $md5hash;
  327. }
  328. if ($playKey == '') {
  329. $playUrls['rtmp'] = 'rtmp://' . $playDomain . '/' . $appName . '/' . $streamName;
  330. $playUrls['flv'] = 'http://' . $playDomain . '/' . $appName . '/' . $streamName . '.flv';
  331. $playUrls['hls'] = 'http://' . $playDomain . '/' . $appName . '/' . $streamName . '.m3u8';
  332. } else {
  333. $rtmpSstring = '/' . $appName . '/' . $streamName . '-' . $timeStamp . '-0-0-' . $playKey;
  334. $rtmpMd5hash = md5($rtmpSstring);
  335. $playUrls['rtmp'] = 'rtmp://' . $playDomain . '/' . $appName . '/' . $streamName . '?auth_key=' . $timeStamp . '-0-0-' . $rtmpMd5hash;
  336. $flvSstring = '/' . $appName . '/' . $streamName . '.flv-' . $timeStamp . '-0-0-' . $playKey;
  337. $flvMd5hash = md5($flvSstring);
  338. $playUrls['flv'] = 'http://' . $playDomain . '/' . $appName . '/' . $streamName . '.flv?auth_key=' . $timeStamp . '-0-0-' . $flvMd5hash;
  339. $hlsSstring = '/' . $appName . '/' . $streamName . '.m3u8-' . $timeStamp . '-0-0-' . $playKey;
  340. $hlsMd5hash = md5($hlsSstring);
  341. $playUrls['hls'] = 'http://' . $playDomain . '/' . $appName . '/' . $streamName . '.m3u8?auth_key=' . $timeStamp . '-0-0-' . $hlsMd5hash;
  342. }
  343. $datas = [
  344. 'push_url' => $pushUrl,
  345. 'play_url' => isset($playUrls[$playType]) ? $playUrls[$playType] : '',
  346. 'play_urls' => $playUrls,
  347. ];
  348. RedisService::set($cachekey, $datas, 1800);
  349. return $datas;
  350. }
  351. /**
  352. * 创建直播间
  353. * @param $userId 直逼用户
  354. * @param $params
  355. * @return array|false
  356. */
  357. public function create($userId, $params)
  358. {
  359. $liveLevel = ConfigService::make()->getConfigByCode('live_open_level');
  360. $liveLevel = $liveLevel > 0 ? $liveLevel : 0;
  361. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])->select(['id', 'nickname', 'member_level', 'status'])->first();
  362. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  363. $nickname = isset($userInfo['nickname']) ? $userInfo['nickname'] : '';
  364. $memberLevel = isset($userInfo['member_level']) ? $userInfo['member_level'] : 0;
  365. if (empty($userInfo) || $status != 1) {
  366. $this->error = 2024;
  367. return false;
  368. }
  369. if($memberLevel < $liveLevel){
  370. $this->error = 2040;
  371. return false;
  372. }
  373. // 验证是否有开播中断播的继续播
  374. $data = [
  375. 'type' => isset($params['type']) ? intval($params['type']) : 1,
  376. 'user_id' => $userId,
  377. 'title' => isset($params['title']) && $params['title'] ? trim($params['title']) : $nickname.'正在直播',
  378. 'description' => isset($params['description']) && $params['description'] ? trim($params['description']) : lang('我正在直播,快来看看吧'),
  379. 'category' => isset($params['category']) ? intval($params['category']) : 0,
  380. 'visible_type' => isset($params['visible_type']) ? intval($params['visible_type']) : 0,
  381. 'visible_users' => isset($params['visible_users']) ? trim($params['visible_users']) : '',
  382. 'chat_type' => isset($params['chat_type']) ? intval($params['chat_type']) : 0,
  383. 'chat_status' => isset($params['chat_status']) ? intval($params['chat_status']) : 1,
  384. 'pay_status' => isset($params['pay_status']) ? intval($params['pay_status']) : 1,
  385. 'open_area' => isset($params['open_area']) ? intval($params['open_area']) : 1,
  386. 'view_allow' => isset($params['view_allow']) ? intval($params['view_allow']) : 1,
  387. 'push_url' => isset($params['push_url']) ? trim($params['push_url']) : '',
  388. 'play_url' => isset($params['play_url']) ? trim($params['play_url']) : '',
  389. 'update_time'=> time(),
  390. 'status' =>1,
  391. 'mark'=>1,
  392. ];
  393. if($liveId = $this->model->where(['user_id'=> $userId,'status'=>1,'mark'=>1])->orderBy('create_time','desc')->value('id')){
  394. if(!$this->model->where(['user_id'=> $userId,'status'=>1,'mark'=>1])->update($data)){
  395. $this->error = 2042;
  396. return false;
  397. }
  398. }else{
  399. $data['create_time'] = time();
  400. $this->model->where(['user_id'=> $userId,'mark'=>1])->update(['status'=>2,'update_time'=>time()]);
  401. if(!$liveId = $this->model->insertGetId($data)){
  402. $this->error = 2042;
  403. return false;
  404. }
  405. }
  406. $data['id'] = $liveId;
  407. $data['member'] = MemberModel::where(['id'=> $userId])->select(['id','nickname','avatar','status'])->first();
  408. $data['member'] = $data['member']? $data['member'] : [];
  409. $data['member']['is_follow'] = 1;
  410. if(isset($data['member']['avatar'])){
  411. $data['member']['avatar'] = $data['member']['avatar']? $data['member']['avatar'] : '/images/member/logo.png';
  412. $data['member']['avatar'] = get_image_url($data['member']['avatar']);
  413. }
  414. $this->error = 2041;
  415. return $data;
  416. }
  417. }