LiveService.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. /**
  200. * 更新播放浏览历史
  201. * @param $userId 用户ID
  202. * @param $id 视频ID
  203. * @return false
  204. */
  205. public function updatePlay($userId, $id)
  206. {
  207. // 浏览历史
  208. if(!VideoCollectService::make()->getCollectCacheInfo($userId, $id, 1,2)){
  209. $info = $this->model->from('live as a')
  210. ->where(['a.id'=> $id,'a.mark'=>1])
  211. ->select(['a.id','a.category','a.user_id'])
  212. ->first();
  213. if(empty($info)){
  214. return false;
  215. }
  216. $data = [
  217. 'user_id'=> $userId,
  218. 'type'=> 1,
  219. 'source_type'=> 2,
  220. 'collect_id'=> $id,
  221. 'category_id'=> isset($info['category'])? $info['category'] : 0,
  222. 'collect_uid'=> isset($info['user_id'])? $info['user_id'] : 0,
  223. 'create_time'=> time(),
  224. 'status'=> 1,
  225. ];
  226. VideoCollectModel::insert($data);
  227. RedisService::set("caches:videos:collect:temp_{$userId}_{$id}_1_2", $data, rand(10,30));
  228. RedisService::clear("caches:videos:recommend:{$userId}_1_2");
  229. RedisService::clear("caches:member:fans:{$userId}_{$id}_2");
  230. }
  231. // 更新播放量
  232. if(!RedisService::get("caches:player:live:{$userId}_{$id}")){
  233. $this->model->where(['id'=> $id])->update(['views'=>DB::raw('views + 1'),'update_time'=>time()]);
  234. RedisService::set("caches:player:live:{$userId}_{$id}", ['user_id'=> $userId,'id'=>$id], rand(6*3600, 86400));
  235. }
  236. $this->error = 1010;
  237. return true;
  238. }
  239. /**
  240. * 缓存数据
  241. * @param $id
  242. * @param int $status
  243. * @return array|mixed
  244. */
  245. public function getCacheInfo($id, $status=0)
  246. {
  247. $cacheKey = "caches:live:info:{$id}_{$status}";
  248. $info = RedisService::get($cacheKey);
  249. if($info){
  250. return $info;
  251. }
  252. $where = ['id' => $id, 'mark' => 1];
  253. if($status){
  254. $where['status'] = $status;
  255. }
  256. $info = $this->model->where($where)
  257. ->select(['id','user_id','create_time','end_time','views','reward_num','reward_total','like_num'])
  258. ->first();
  259. $info = $info? $info->toArray() : [];
  260. if($info){
  261. RedisService::set($cacheKey, $info, rand(3, 5));
  262. }
  263. return $info;
  264. }
  265. /**
  266. * 状态设置
  267. * @return bool
  268. */
  269. public function status()
  270. {
  271. $id = request()->post('id', 0);
  272. $status = request()->post('status', 2);
  273. if ($id && !$info = $this->getCacheInfo($id)) {
  274. $this->error = 2981;
  275. return false;
  276. }
  277. $updateData = ['status'=>$status, 'update_time'=> time()];
  278. if($status == 2){
  279. $updateData['end_time'] = time();
  280. }
  281. if($this->model->where(['id'=> $id,'mark'=>1])->update($updateData)){
  282. $this->error = 1002;
  283. $time = $info['end_time']? intval($info['end_time'] - $info['create_time']) : intval(time() - $info['create_time']);
  284. $info['status'] = $status;
  285. $info['live_hour'] = $time > 3600 ? intval($time/3600) : 0;
  286. $info['live_minute'] = $time%3600? intval($time%3600/60) : 0;
  287. $info['time_text'] = date('H:i', $info['create_time']);
  288. $info['end_time_text'] = date('H:i', $info['end_time']? $info['end_time'] : time());
  289. $info['fans_num'] = MemberCollectService::make()->getViewFansCountByType($info['user_id'], $id, 2);
  290. $info['new_fans'] = MemberCollectService::make()->getNewFansCount($info['user_id'], $id,2, $info['create_time']);
  291. return $info;
  292. }
  293. $this->error = 1003;
  294. return true;
  295. }
  296. /**
  297. * 获取直播推流/拉流地址
  298. * @param $streamName
  299. * @param string $appName
  300. * @param string $playType
  301. * @param int $expireTime
  302. * @return array
  303. */
  304. public function getLiveUrl($streamName, $appName = 'xlapp', $playType = 'rtmp', $expireTime = 1440)
  305. {
  306. $cachekey = "caches:live:urls:{$streamName}_{$appName}_{$playType}";
  307. $datas = RedisService::get($cachekey);
  308. if($datas){
  309. return $datas;
  310. }
  311. $playUrls = [];
  312. //未开启鉴权Key的情况下
  313. $pushDomain = ConfigService::make()->getConfigByCode('live_push_url');
  314. $playDomain = ConfigService::make()->getConfigByCode('live_play_url');
  315. $pushKey = ConfigService::make()->getConfigByCode('push_url_key');
  316. $playKey = ConfigService::make()->getConfigByCode('play_url_key');
  317. $timeStamp = time() + $expireTime * 60;
  318. if ($pushKey == '') {
  319. $pushUrl = 'rtmp://' . $pushDomain . '/' . $appName . '/' . $streamName;
  320. } else {
  321. $sstring = '/' . $appName . '/' . $streamName . '-' . $timeStamp . '-0-0-' . $pushKey;
  322. $md5hash = md5($sstring);
  323. $pushUrl = 'rtmp://' . $pushDomain . '/' . $appName . '/' . $streamName . '?auth_key=' . $timeStamp . '-0-0-' . $md5hash;
  324. }
  325. if ($playKey == '') {
  326. $playUrls['rtmp'] = 'rtmp://' . $playDomain . '/' . $appName . '/' . $streamName;
  327. $playUrls['flv'] = 'http://' . $playDomain . '/' . $appName . '/' . $streamName . '.flv';
  328. $playUrls['hls'] = 'http://' . $playDomain . '/' . $appName . '/' . $streamName . '.m3u8';
  329. } else {
  330. $rtmpSstring = '/' . $appName . '/' . $streamName . '-' . $timeStamp . '-0-0-' . $playKey;
  331. $rtmpMd5hash = md5($rtmpSstring);
  332. $playUrls['rtmp'] = 'rtmp://' . $playDomain . '/' . $appName . '/' . $streamName . '?auth_key=' . $timeStamp . '-0-0-' . $rtmpMd5hash;
  333. $flvSstring = '/' . $appName . '/' . $streamName . '.flv-' . $timeStamp . '-0-0-' . $playKey;
  334. $flvMd5hash = md5($flvSstring);
  335. $playUrls['flv'] = 'http://' . $playDomain . '/' . $appName . '/' . $streamName . '.flv?auth_key=' . $timeStamp . '-0-0-' . $flvMd5hash;
  336. $hlsSstring = '/' . $appName . '/' . $streamName . '.m3u8-' . $timeStamp . '-0-0-' . $playKey;
  337. $hlsMd5hash = md5($hlsSstring);
  338. $playUrls['hls'] = 'http://' . $playDomain . '/' . $appName . '/' . $streamName . '.m3u8?auth_key=' . $timeStamp . '-0-0-' . $hlsMd5hash;
  339. }
  340. $datas = [
  341. 'push_url' => $pushUrl,
  342. 'play_url' => isset($playUrls[$playType]) ? $playUrls[$playType] : '',
  343. 'play_urls' => $playUrls,
  344. ];
  345. RedisService::set($cachekey, $datas, 1800);
  346. return $datas;
  347. }
  348. /**
  349. * 创建直播间
  350. * @param $userId 直逼用户
  351. * @param $params
  352. * @return array|false
  353. */
  354. public function create($userId, $params)
  355. {
  356. $liveLevel = ConfigService::make()->getConfigByCode('live_open_level');
  357. $liveLevel = $liveLevel > 0 ? $liveLevel : 0;
  358. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])->select(['id', 'nickname', 'member_level', 'status'])->first();
  359. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  360. $nickname = isset($userInfo['nickname']) ? $userInfo['nickname'] : '';
  361. $memberLevel = isset($userInfo['member_level']) ? $userInfo['member_level'] : 0;
  362. if (empty($userInfo) || $status != 1) {
  363. $this->error = 2024;
  364. return false;
  365. }
  366. if($memberLevel < $liveLevel){
  367. $this->error = 2040;
  368. return false;
  369. }
  370. // 验证是否有开播中断播的继续播
  371. $data = [
  372. 'type' => isset($params['type']) ? intval($params['type']) : 1,
  373. 'user_id' => $userId,
  374. 'title' => isset($params['title']) && $params['title'] ? trim($params['title']) : $nickname.'正在直播',
  375. 'description' => isset($params['description']) && $params['description'] ? trim($params['description']) : lang('我正在直播,快来看看吧'),
  376. 'category' => isset($params['category']) ? intval($params['category']) : 0,
  377. 'visible_type' => isset($params['visible_type']) ? intval($params['visible_type']) : 0,
  378. 'visible_users' => isset($params['visible_users']) ? trim($params['visible_users']) : '',
  379. 'chat_type' => isset($params['chat_type']) ? intval($params['chat_type']) : 0,
  380. 'chat_status' => isset($params['chat_status']) ? intval($params['chat_status']) : 1,
  381. 'pay_status' => isset($params['pay_status']) ? intval($params['pay_status']) : 1,
  382. 'open_area' => isset($params['open_area']) ? intval($params['open_area']) : 1,
  383. 'view_allow' => isset($params['view_allow']) ? intval($params['view_allow']) : 1,
  384. 'push_url' => isset($params['push_url']) ? trim($params['push_url']) : '',
  385. 'play_url' => isset($params['play_url']) ? trim($params['play_url']) : '',
  386. 'update_time'=> time(),
  387. 'status' =>1,
  388. 'mark'=>1,
  389. ];
  390. if($liveId = $this->model->where(['user_id'=> $userId,'status'=>1,'mark'=>1])->orderBy('create_time','desc')->value('id')){
  391. if(!$this->model->where(['user_id'=> $userId,'status'=>1,'mark'=>1])->update($data)){
  392. $this->error = 2042;
  393. return false;
  394. }
  395. }else{
  396. $data['create_time'] = time();
  397. $this->model->where(['user_id'=> $userId,'mark'=>1])->update(['status'=>2,'update_time'=>time()]);
  398. if(!$liveId = $this->model->insertGetId($data)){
  399. $this->error = 2042;
  400. return false;
  401. }
  402. }
  403. $data['id'] = $liveId;
  404. $data['member'] = MemberModel::where(['id'=> $userId])->select(['id','nickname','avatar','status'])->first();
  405. $data['member'] = $data['member']? $data['member'] : [];
  406. $data['member']['is_follow'] = 1;
  407. if(isset($data['member']['avatar'])){
  408. $data['member']['avatar'] = $data['member']['avatar']? $data['member']['avatar'] : '/images/member/logo.png';
  409. $data['member']['avatar'] = get_image_url($data['member']['avatar']);
  410. }
  411. $this->error = 2041;
  412. return $data;
  413. }
  414. }