LiveService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. ->orWhereIn('a.visible_users', 'like',"%{$userId},%")
  94. ->orWhereIn('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. public function getInfo($id, $userId)
  149. {
  150. $info = $this->model->with(['member'])->where(['id'=> $id,'mark'=>1])->first();
  151. if($info && isset($info['member'])){
  152. if(isset($info['member']['avatar'])){
  153. $info['member']['avatar'] = $info['member']['avatar']? $info['member']['avatar'] : '/images/member/logo.png';
  154. $info['member']['avatar'] = get_image_url($info['member']['avatar']);
  155. }
  156. if($info['user_id'] == $userId){
  157. $info['is_foolow'] = 1;
  158. }else{
  159. $checkFollow = MemberCollectService::make()->checkCollect($userId, $info['user_id'], 1);
  160. $info['is_follow'] = $checkFollow? 1 : 0;
  161. }
  162. // 观看权限
  163. $info['view_limit'] = 0;
  164. // 浏览历史
  165. if(!VideoCollectService::make()->getCollectCacheInfo($userId, $id, 1)){
  166. $data = [
  167. 'user_id'=> $userId,
  168. 'type'=> 1,
  169. 'collect_id'=> $id,
  170. 'collect_uid'=> isset($info['user_id'])? $info['user_id'] : 0,
  171. 'tags'=> isset($info['tags'])? $info['tags'] : '',
  172. 'create_time'=> time(),
  173. 'status'=> 1,
  174. ];
  175. VideoCollectModel::insert($data);
  176. RedisService::clear("caches:videos:recommend:{$userId}_2");
  177. }
  178. // 更新播放量
  179. if(!RedisService::get("caches:live:player:{$userId}_{$id}")){
  180. $this->model->where(['id'=> $id])->update(['views'=>DB::raw('views + 1'),'update_time'=>time()]);
  181. RedisService::set("caches:live:player:{$userId}_{$id}", ['user_id'=> $userId,'id'=>$id], rand(600, 1800));
  182. $info['views'] += 1;
  183. }
  184. // 结束直播
  185. if($info['create_time'] <= time() - 30 * 60 && $info['status'] == 1){
  186. $this->model->where(['id'=> $id])->update(['status'=>2,'update_time'=>time()]);
  187. $info['status'] = 2;
  188. }
  189. }
  190. return $info;
  191. }
  192. /**
  193. * 更新播放浏览历史
  194. * @param $userId 用户ID
  195. * @param $id 视频ID
  196. * @return false
  197. */
  198. public function updatePlay($userId, $id)
  199. {
  200. // 浏览历史
  201. if(!VideoCollectService::make()->getCollectCacheInfo($userId, $id, 1,2)){
  202. $info = $this->model->from('live as a')
  203. ->where(['a.id'=> $id,'a.mark'=>1])
  204. ->select(['a.id','a.category_id','a.user_id'])
  205. ->first();
  206. if(empty($info)){
  207. return false;
  208. }
  209. $data = [
  210. 'user_id'=> $userId,
  211. 'type'=> 1,
  212. 'source_type'=> 2,
  213. 'collect_id'=> $id,
  214. 'category_id'=> isset($info['category_id'])? $info['category_id'] : 0,
  215. 'collect_uid'=> isset($info['user_id'])? $info['user_id'] : 0,
  216. 'create_time'=> time(),
  217. 'status'=> 1,
  218. ];
  219. VideoCollectModel::insert($data);
  220. RedisService::set("caches:videos:collect:temp_{$userId}_{$id}_1_2", $data, rand(10,30));
  221. RedisService::clear("caches:videos:recommend:{$userId}_1_2");
  222. }
  223. // 更新播放量
  224. if(!RedisService::get("caches:live:player:{$userId}_{$id}")){
  225. $this->model->where(['id'=> $id])->update(['views'=>DB::raw('views + 1'),'update_time'=>time()]);
  226. RedisService::set("caches:live:player:{$userId}_{$id}", ['user_id'=> $userId,'id'=>$id], rand(600, 1800));
  227. $info['views'] += 1;
  228. }
  229. $this->error = 1010;
  230. return true;
  231. }
  232. /**
  233. * 状态设置
  234. * @return bool
  235. */
  236. public function status()
  237. {
  238. $id = request()->post('id', 0);
  239. $status = request()->post('status', 2);
  240. if ($id && !$this->model->where(['id' => $id, 'mark' => 1])->value('id')) {
  241. $this->error = 2981;
  242. return false;
  243. }
  244. if($this->model->where(['id'=> $id,'mark'=>1])->update(['status'=>$status, 'update_time'=> time()])){
  245. $this->error = 1002;
  246. return true;
  247. }
  248. $this->error = 1003;
  249. return true;
  250. }
  251. /**
  252. * 获取直播推流/拉流地址
  253. * @param $streamName
  254. * @param string $appName
  255. * @param string $playType
  256. * @param int $expireTime
  257. * @return array
  258. */
  259. public function getLiveUrl($streamName, $appName = 'xlapp', $playType = 'rtmp', $expireTime = 1440)
  260. {
  261. $cachekey = "caches:live:urls:{$streamName}_{$appName}_{$playType}";
  262. $datas = RedisService::get($cachekey);
  263. if($datas){
  264. return $datas;
  265. }
  266. $playUrls = [];
  267. //未开启鉴权Key的情况下
  268. $pushDomain = ConfigService::make()->getConfigByCode('live_push_url');
  269. $playDomain = ConfigService::make()->getConfigByCode('live_play_url');
  270. $pushKey = ConfigService::make()->getConfigByCode('push_url_key');
  271. $playKey = ConfigService::make()->getConfigByCode('play_url_key');
  272. $timeStamp = time() + $expireTime * 60;
  273. if ($pushKey == '') {
  274. $pushUrl = 'rtmp://' . $pushDomain . '/' . $appName . '/' . $streamName;
  275. } else {
  276. $sstring = '/' . $appName . '/' . $streamName . '-' . $timeStamp . '-0-0-' . $pushKey;
  277. $md5hash = md5($sstring);
  278. $pushUrl = 'rtmp://' . $pushDomain . '/' . $appName . '/' . $streamName . '?auth_key=' . $timeStamp . '-0-0-' . $md5hash;
  279. }
  280. if ($playKey == '') {
  281. $playUrls['rtmp'] = 'rtmp://' . $playDomain . '/' . $appName . '/' . $streamName;
  282. $playUrls['flv'] = 'http://' . $playDomain . '/' . $appName . '/' . $streamName . '.flv';
  283. $playUrls['hls'] = 'http://' . $playDomain . '/' . $appName . '/' . $streamName . '.m3u8';
  284. } else {
  285. $rtmpSstring = '/' . $appName . '/' . $streamName . '-' . $timeStamp . '-0-0-' . $playKey;
  286. $rtmpMd5hash = md5($rtmpSstring);
  287. $playUrls['rtmp'] = 'rtmp://' . $playDomain . '/' . $appName . '/' . $streamName . '?auth_key=' . $timeStamp . '-0-0-' . $rtmpMd5hash;
  288. $flvSstring = '/' . $appName . '/' . $streamName . '.flv-' . $timeStamp . '-0-0-' . $playKey;
  289. $flvMd5hash = md5($flvSstring);
  290. $playUrls['flv'] = 'http://' . $playDomain . '/' . $appName . '/' . $streamName . '.flv?auth_key=' . $timeStamp . '-0-0-' . $flvMd5hash;
  291. $hlsSstring = '/' . $appName . '/' . $streamName . '.m3u8-' . $timeStamp . '-0-0-' . $playKey;
  292. $hlsMd5hash = md5($hlsSstring);
  293. $playUrls['hls'] = 'http://' . $playDomain . '/' . $appName . '/' . $streamName . '.m3u8?auth_key=' . $timeStamp . '-0-0-' . $hlsMd5hash;
  294. }
  295. $datas = [
  296. 'push_url' => $pushUrl,
  297. 'play_url' => isset($playUrls[$playType]) ? $playUrls[$playType] : '',
  298. 'play_urls' => $playUrls,
  299. ];
  300. RedisService::set($cachekey, $datas, 1800);
  301. return $datas;
  302. }
  303. /**
  304. * 创建直播间
  305. * @param $userId 直逼用户
  306. * @param $params
  307. * @return array|false
  308. */
  309. public function create($userId, $params)
  310. {
  311. $liveLevel = ConfigService::make()->getConfigByCode('live_open_level');
  312. $liveLevel = $liveLevel > 0 ? $liveLevel : 0;
  313. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])->select(['id', 'nickname', 'member_level', 'status'])->first();
  314. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  315. $nickname = isset($userInfo['nickname']) ? $userInfo['nickname'] : '';
  316. $memberLevel = isset($userInfo['member_level']) ? $userInfo['member_level'] : 0;
  317. if (empty($userInfo) || $status != 1) {
  318. $this->error = 2024;
  319. return false;
  320. }
  321. if($memberLevel < $liveLevel){
  322. $this->error = 2040;
  323. return false;
  324. }
  325. // 验证是否有开播中断播的继续播
  326. $data = [
  327. 'type' => isset($params['type']) ? intval($params['type']) : 1,
  328. 'user_id' => $userId,
  329. 'title' => isset($params['title']) && $params['title'] ? trim($params['title']) : $nickname.'正在直播',
  330. 'description' => isset($params['description']) && $params['description'] ? trim($params['description']) : '我正在直播,快来看看吧',
  331. 'category' => isset($params['category']) ? intval($params['category']) : 0,
  332. 'visible_type' => isset($params['visible_type']) ? intval($params['visible_type']) : 0,
  333. 'visible_users' => isset($params['visible_users']) ? trim($params['visible_users']) : '',
  334. 'chat_type' => isset($params['chat_type']) ? intval($params['chat_type']) : 0,
  335. 'chat_status' => isset($params['chat_status']) ? intval($params['chat_status']) : 1,
  336. 'pay_status' => isset($params['pay_status']) ? intval($params['pay_status']) : 1,
  337. 'open_area' => isset($params['open_area']) ? intval($params['open_area']) : 1,
  338. 'view_allow' => isset($params['view_allow']) ? intval($params['view_allow']) : 1,
  339. 'push_url' => isset($params['push_url']) ? trim($params['push_url']) : '',
  340. 'play_url' => isset($params['play_url']) ? trim($params['play_url']) : '',
  341. 'update_time'=> time(),
  342. 'status' =>1,
  343. 'mark'=>1,
  344. ];
  345. if($liveId = $this->model->where(['user_id'=> $userId,'status'=>1,'mark'=>1])->orderBy('create_time','desc')->value('id')){
  346. if(!$this->model->where(['user_id'=> $userId,'status'=>1,'mark'=>1])->update($data)){
  347. $this->error = 2042;
  348. return false;
  349. }
  350. }else{
  351. $data['create_time'] = time();
  352. $this->model->where(['user_id'=> $userId,'mark'=>1])->update(['status'=>2,'update_time'=>time()]);
  353. if(!$liveId = $this->model->insertGetId($data)){
  354. $this->error = 2042;
  355. return false;
  356. }
  357. }
  358. $data['id'] = $liveId;
  359. $data['member'] = MemberModel::where(['id'=> $userId])->select(['id','nickname','avatar','status'])->first();
  360. $data['member'] = $data['member']? $data['member'] : [];
  361. $data['member']['is_follow'] = 1;
  362. if(isset($data['member']['avatar'])){
  363. $data['member']['avatar'] = $data['member']['avatar']? $data['member']['avatar'] : '/images/member/logo.png';
  364. $data['member']['avatar'] = get_image_url($data['member']['avatar']);
  365. }
  366. $this->error = 2041;
  367. return $data;
  368. }
  369. }