LiveService.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  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\AccountLogModel;
  15. use App\Models\LiveGiftModel;
  16. use App\Models\LiveModel;
  17. use App\Models\MemberModel;
  18. use App\Models\RewardOrderModel;
  19. use App\Models\VideoCollectModel;
  20. use App\Services\Api\MemberCollectService;
  21. use App\Services\Api\MessageService;
  22. use App\Services\Api\VideoCollectService;
  23. use Darabonba\OpenApi\Models\Config;
  24. use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
  25. use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
  26. use Illuminate\Support\Facades\DB;
  27. /**
  28. * 在线直播服务管理-服务类
  29. * @author laravel开发员
  30. * @since 2020/11/11
  31. * Class LiveService
  32. * @package App\Services
  33. */
  34. class LiveService extends BaseService
  35. {
  36. // 静态对象
  37. protected static $instance = null;
  38. /**
  39. * 构造函数
  40. * @author laravel开发员
  41. * @since 2020/11/11
  42. * ConfigService constructor.
  43. */
  44. public function __construct()
  45. {
  46. $this->model = new LiveModel();
  47. }
  48. /**
  49. * 静态入口
  50. * @return SmsService|static|null
  51. */
  52. public static function make()
  53. {
  54. if (!self::$instance) {
  55. self::$instance = new static();
  56. }
  57. return self::$instance;
  58. }
  59. /**
  60. * 列表数据
  61. * @param $params
  62. * @param int $pageSize
  63. * @return array
  64. */
  65. public function getDataList($params, $pageSize = 18, $field = '', $userId=0)
  66. {
  67. $where = ['a.mark' => 1,'a.status'=>1,'b.mark'=>1];
  68. $field = $field? $field : 'lev_a.*';
  69. $order = 'rand()';
  70. $model = $this->model->with(['member'])->from('live as a')
  71. ->leftJoin('member as b', 'b.id', '=', 'a.user_id')
  72. ->where($where)
  73. ->where(function ($query) use ($params) {
  74. $type = isset($params['type']) ? $params['type'] : 0;
  75. if ($type > 0) {
  76. $query->where('a.type', $type);
  77. }
  78. $categoryId = isset($params['category_id']) ? $params['category_id'] : 0;
  79. if ($categoryId > 0) {
  80. $query->where('a.category_id', $categoryId);
  81. }
  82. $uid = isset($params['user_id']) ? $params['user_id'] : 0;
  83. if ($uid > 0) {
  84. $query->where('a.user_id', $uid);
  85. }
  86. })
  87. ->where(function ($query) use ($params) {
  88. $keyword = isset($params['kw']) ? $params['kw'] : '';
  89. if ($keyword) {
  90. $query->where('a.title', 'like', "%{$keyword}%")
  91. ->orWhere('a.description', 'like', "%{$keyword}%")
  92. ->orWhere('b.nickname', 'like', "%{$keyword}%");
  93. }
  94. })->where(function ($query) use ($userId) {
  95. if ($userId) {
  96. $query->where('a.visible_users', '=', '')
  97. ->orWhere('a.visible_users', 'like',"%{$userId},%")
  98. ->orWhere('a.manage_users', 'like',"%{$userId},%");
  99. }
  100. });
  101. // 推荐的数据
  102. $countModel = clone $model;
  103. $total = $countModel->where(function($query) use($params, $userId){
  104. // 推荐视频数据
  105. $isRecommend = isset($params['is_recommend']) ? $params['is_recommend'] : 0;
  106. if ($isRecommend > 0) {
  107. $recommendData = VideoCollectService::make()->getRecommendData($userId);
  108. $uids = isset($recommendData['uids'])? $recommendData['uids'] : []; // 按用户推荐
  109. $category = isset($recommendData['category'])? $recommendData['category'] : []; // 按标签推荐
  110. if($uids){
  111. $query->orWhere(function($query) use($uids){
  112. $query->whereIn('a.user_id', $uids);
  113. });
  114. }
  115. if($category){
  116. $query->orWhere(function($query) use($category){
  117. $query->whereIn('a.category_id', $category);
  118. });
  119. }
  120. }
  121. })->count('a.id');
  122. if($total > 0){
  123. // 关联推荐数据
  124. $list = $countModel->selectRaw($field)
  125. ->orderByRaw($order)
  126. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  127. }else{
  128. // 默认推荐数据
  129. $list = $model->selectRaw($field)
  130. ->orderByRaw($order)
  131. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  132. }
  133. $list = $list ? $list->toArray() : [];
  134. if ($list && $list['data']) {
  135. foreach ($list['data'] as &$item) {
  136. $item['time_text'] = isset($item['create_time']) ? dateFormat($item['create_time'], 'Y-m-d H:i') : '';
  137. $member = isset($item['member'])? $item['member'] : [];
  138. if($member){
  139. $member['avatar'] = isset($member['avatar']) && $member['avatar']? get_image_url($member['avatar']) : get_image_url('/images/member/logo.png');
  140. }
  141. $item['like_num'] = isset($item['like_num']) && $item['like_num']? intval($item['like_num']) : 0;
  142. $item['views'] = isset($item['views']) && $item['views']? intval($item['views']) : 0;
  143. $item['member'] = $member;
  144. }
  145. }
  146. return [
  147. 'pageSize' => $pageSize,
  148. 'total' => isset($list['total']) ? $list['total'] : 0,
  149. 'list' => isset($list['data']) ? $list['data'] : []
  150. ];
  151. }
  152. /**
  153. * 详情
  154. * @param $id
  155. * @param $userId
  156. * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
  157. */
  158. public function getInfo($id, $userId)
  159. {
  160. $info = $this->model->with(['member'])->where(['id'=> $id,'mark'=>1])->first();
  161. $info = $info? $info->toArray() : [];
  162. if($info && isset($info['member'])){
  163. if(isset($info['member']['avatar'])){
  164. $info['member']['avatar'] = $info['member']['avatar']? $info['member']['avatar'] : '/images/member/logo.png';
  165. $info['member']['avatar'] = get_image_url($info['member']['avatar']);
  166. }
  167. if($info['user_id'] == $userId){
  168. $info['is_follow'] = 1;
  169. }else{
  170. $checkFollow = MemberCollectService::make()->checkCollect($userId, $info['user_id'], 1);
  171. $info['is_follow'] = $checkFollow? 1 : 0;
  172. $info['member']['is_follow'] = $checkFollow? 1 : 0;
  173. }
  174. // 用户资料
  175. $liveUserId = isset($info['user_id'])? $info['user_id'] : 0;
  176. $info['member']['fans'] = (int)MemberCollectService::make()->getCount($liveUserId, 1,1); // 粉丝数量(被关注)
  177. $info['member']['follow'] = (int)MemberCollectService::make()->getCount($liveUserId, 1,2); // 关注数量
  178. // 观看权限
  179. $info['view_limit'] = 0;
  180. if($info['status'] == 2){
  181. $createTime = $info['create_time']? strtotime($info['create_time']) : time();
  182. $time = $info['end_time']? intval($info['end_time'] - $createTime) : intval(time() - $createTime);
  183. $info['end_time'] = $info['end_time']? $info['end_time'] : time();
  184. $info['live_hour'] = $time > 3600 ? intval($time/3600) : 0;
  185. $info['live_minute'] = $time%3600? intval($time%3600/60) : 0;
  186. $info['time_text'] = $createTime<(time() - 86400)? date('m-d H:i', $createTime) : date('H:i', $createTime);
  187. $info['end_time_text'] = $info['end_time']<(time() - 86400)? date('m-d H:i', $info['end_time']) : date('H:i', $info['end_time']);
  188. $info['fans_num'] = MemberCollectService::make()->getViewFansCountByType($info['user_id'], $id, 2);
  189. $info['new_fans'] = MemberCollectService::make()->getNewFansCount($info['user_id'], $id,2, $createTime);
  190. }
  191. // 浏览历史
  192. if(!VideoCollectService::make()->getCollectCacheInfo($userId, $id, 1, 2)){
  193. $data = [
  194. 'user_id'=> $userId,
  195. 'type'=> 1,
  196. 'source_type'=> 2,
  197. 'collect_id'=> $id,
  198. 'collect_uid'=> isset($info['user_id'])? $info['user_id'] : 0,
  199. 'tags'=> isset($info['tags'])? $info['tags'] : '',
  200. 'create_time'=> time(),
  201. 'status'=> 1,
  202. ];
  203. VideoCollectModel::insert($data);
  204. RedisService::clear("caches:videos:recommend:{$userId}_2");
  205. RedisService::clear("caches:member:fans:{$userId}_{$id}_2");
  206. RedisService::clear("caches:live:users_{$id}_{$userId}");
  207. }
  208. // 更新播放量
  209. if(!RedisService::get("caches:live:player:{$userId}_{$id}")){
  210. $this->model->where(['id'=> $id])->update(['views'=>DB::raw('views + 1'),'update_time'=>time()]);
  211. RedisService::set("caches:live:player:{$userId}_{$id}", ['user_id'=> $userId,'id'=>$id], rand(600, 1800));
  212. $info['views'] += 1;
  213. }
  214. // 结束直播
  215. $createTime = $info['create_time']? strtotime($info['create_time']) : time();
  216. if($createTime <= time() - 1.5 * 86400 && $info['status'] == 1){
  217. $this->model->where(['id'=> $id])->update(['status'=>2,'end_time'=>time(),'update_time'=>time()]);
  218. $info['status'] = 2;
  219. }
  220. }
  221. return $info;
  222. }
  223. /**
  224. * 获取直播间在线观众数据
  225. * @param $params
  226. * @param $pageSize
  227. * @param int $userId
  228. * @return array|mixed
  229. */
  230. public function getUserList($params, $pageSize=200, $userId=0)
  231. {
  232. $liveId = isset($params['live_id'])? $params['live_id'] : 0;
  233. $cachekey = "caches:live:users_{$liveId}_{$userId}";
  234. $datas = RedisService::get($cachekey);
  235. if($datas || RedisService::exists($cachekey)){
  236. return $datas? $datas : [
  237. 'current' => ['user_id'=> $userId,'rank'=>0,'reward_total'=>0],
  238. 'rank_limit'=> 200,
  239. 'total' => 0,
  240. 'list' => []
  241. ];
  242. }
  243. $rankNum = ConfigService::make()->getConfigByCode('live_show_rank', 200);
  244. $rankNum = $rankNum>20 && $rankNum <= 300? $rankNum : 200;
  245. $model = MemberModel::from('member as a')
  246. ->leftJoin('video_collect as b',function($join) use($liveId){
  247. $join->on('a.id','=','b.user_id')
  248. ->where(['b.type'=>1,'b.collect_id'=> $liveId,'b.source_type'=>2,'b.is_online'=>1,'b.status'=>1,'b.mark'=>1]);
  249. })
  250. ->where(['a.status'=>1,'a.mark'=>1])
  251. ->where('b.id','>', 0)
  252. ->select(['a.id','a.nickname','a.avatar','a.member_level','a.gender','a.intro','a.status','b.create_time','b.reward_total','b.collect_id as live_id']);
  253. $countModel = clone $model;
  254. $total = $countModel->distinct('a.id')->count('a.id');
  255. $datas = $model->groupBy('a.id')
  256. ->orderBy('b.reward_total','desc')
  257. ->orderBy('b.create_time','asc')
  258. ->limit($rankNum)->get();
  259. $datas = $datas? $datas->toArray() : [];
  260. $rankData = ['user_id'=> $userId,'rank'=>0,'reward_total'=>0];
  261. if ($datas) {
  262. foreach ($datas as $k=> &$item) {
  263. $item['time_text'] = isset($item['create_time']) ? dateFormat($item['create_time'], 'Y-m-d H:i') : '';
  264. $item['avatar'] = isset($item['avatar']) && $item['avatar']? get_image_url($item['avatar']) : get_image_url('/images/member/logo.png');
  265. $item['reward_total'] = isset($item['reward_total']) && $item['reward_total']? format_num(intval($item['reward_total'])) : 0;
  266. if($item['id'] == $userId){
  267. $rankData['rank'] = ($k+1)>$rankNum? 0 : ($k+1);
  268. $rankData['reward_total'] = $item['reward_total']? format_num(intval($item['reward_total'])) : 0;
  269. }
  270. }
  271. // 用户排名在200名外的数据
  272. if($rankData['rank'] <= 0 && $rankData['reward_total']<=0 && count($datas) > $rankNum){
  273. $rewardTotal = VideoCollectModel::where(['user_id'=> $userId,'type'=>1,'collect_id'=> $liveId,'source_type'=>2,'status'=>1,'mark'=>1])
  274. ->value('reward_total');
  275. $rankData['reward_total'] = $rewardTotal? format_num(intval($rewardTotal)) : 0;
  276. }
  277. $totalText = $total>=10000 && $total<=100000? intval($total/10000).'万' : intval($total);
  278. RedisService::set($cachekey, ['current' => $rankData,'rank_limit'=> $rankNum,'total'=> $total,'total_text'=>$totalText,'list'=> $datas], rand(3,5));
  279. }
  280. return [
  281. 'current' => $rankData,
  282. 'rank_limit'=> $rankNum,
  283. 'total' => $total,
  284. 'total_text' => $total>=10000 && $total<=100000? intval($total/10000).'万' : intval($total),
  285. 'list' => $datas
  286. ];
  287. }
  288. /**
  289. * 获取直播间礼物列表
  290. * @param $params
  291. * @param $pageSize
  292. * @param int $userId
  293. * @return array|mixed
  294. */
  295. public function getGiftList($params, $pageSize=30, $userId=0)
  296. {
  297. $page = request()->post('page', 1);
  298. $liveId = isset($params['live_id'])? $params['live_id'] : 0;
  299. $cachekey = "caches:live:gift_{$liveId}_{$userId}_{$page}";
  300. $datas = RedisService::get($cachekey);
  301. if($datas || RedisService::exists($cachekey)){
  302. return $datas? $datas : [
  303. 'pageSize'=> $pageSize,
  304. 'total' => 0,
  305. 'list' => []
  306. ];
  307. }
  308. $list = LiveGiftModel::from('live_gift as a')
  309. ->where(['a.status'=>1,'a.mark'=>1])
  310. ->select(['a.id','a.name','a.code','a.money','a.icon','a.file_url','a.sort'])
  311. ->orderBy('a.sort','desc')
  312. ->orderBy('a.create_time','asc')
  313. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  314. $list = $list ? $list->toArray() : [];
  315. if ($list && $list['data']) {
  316. foreach ($list['data'] as &$item) {
  317. $item['icon'] = isset($item['icon']) && $item['icon']? get_image_url($item['icon']) : get_image_url('/images/gift/gift.png');
  318. $item['file_url'] = isset($item['file_url']) && $item['file_url']? get_image_url($item['file_url']) : '';
  319. }
  320. RedisService::set($cachekey, [
  321. 'pageSize' => $pageSize,
  322. 'total' => isset($list['total']) ? $list['total'] : 0,
  323. 'list' => isset($list['data']) ? $list['data'] : []
  324. ], rand(5,10));
  325. }
  326. return [
  327. 'pageSize' => $pageSize,
  328. 'total' => isset($list['total']) ? $list['total'] : 0,
  329. 'list' => isset($list['data']) ? $list['data'] : []
  330. ];
  331. }
  332. /**
  333. * 更新播放浏览历史
  334. * @param $userId 用户ID
  335. * @param $id 视频ID
  336. * @return false
  337. */
  338. public function updatePlay($userId, $id)
  339. {
  340. // 浏览历史
  341. if(!VideoCollectService::make()->getCollectCacheInfo($userId, $id, 1,2)){
  342. $info = $this->model->from('live as a')
  343. ->where(['a.id'=> $id,'a.mark'=>1])
  344. ->select(['a.id','a.category','a.user_id'])
  345. ->first();
  346. if(empty($info)){
  347. return false;
  348. }
  349. $data = [
  350. 'user_id'=> $userId,
  351. 'type'=> 1,
  352. 'source_type'=> 2,
  353. 'collect_id'=> $id,
  354. 'category_id'=> isset($info['category'])? $info['category'] : 0,
  355. 'collect_uid'=> isset($info['user_id'])? $info['user_id'] : 0,
  356. 'create_time'=> time(),
  357. 'status'=> 1,
  358. ];
  359. VideoCollectModel::insert($data);
  360. RedisService::set("caches:videos:collect:temp_{$userId}_{$id}_1_2", $data, rand(10,30));
  361. RedisService::clear("caches:videos:recommend:{$userId}_1_2");
  362. RedisService::clear("caches:member:fans:{$userId}_{$id}_2");
  363. RedisService::clear("caches:live:users_{$id}_{$userId}");
  364. }
  365. // 更新播放量
  366. if(!RedisService::get("caches:player:live:{$userId}_{$id}")){
  367. $this->model->where(['id'=> $id])->update(['views'=>DB::raw('views + 1'),'update_time'=>time()]);
  368. RedisService::set("caches:player:live:{$userId}_{$id}", ['user_id'=> $userId,'id'=>$id], rand(6*3600, 86400));
  369. }
  370. $this->error = 1010;
  371. return true;
  372. }
  373. /**
  374. * 缓存数据
  375. * @param $id
  376. * @param int $status
  377. * @return array|mixed
  378. */
  379. public function getCacheInfo($id, $status=0)
  380. {
  381. $cacheKey = "caches:live:info:{$id}_{$status}";
  382. $info = RedisService::get($cacheKey);
  383. if($info){
  384. return $info;
  385. }
  386. $where = ['id' => $id, 'mark' => 1];
  387. if($status){
  388. $where['status'] = $status;
  389. }
  390. $info = $this->model->where($where)
  391. ->select(['id','user_id','create_time','end_time','views','reward_num','reward_total','like_num'])
  392. ->first();
  393. $info = $info? $info->toArray() : [];
  394. if($info){
  395. RedisService::set($cacheKey, $info, rand(3, 5));
  396. }
  397. return $info;
  398. }
  399. /**
  400. * 状态设置
  401. * @return bool
  402. */
  403. public function status()
  404. {
  405. $id = request()->post('id', 0);
  406. $status = request()->post('status', 2);
  407. if ($id && !$info = $this->getCacheInfo($id)) {
  408. $this->error = 2981;
  409. return false;
  410. }
  411. $updateData = ['status'=>$status, 'update_time'=> time()];
  412. if($status == 2){
  413. $updateData['end_time'] = time();
  414. }
  415. if($this->model->where(['id'=> $id,'mark'=>1])->update($updateData)){
  416. $this->error = 1002;
  417. if($status == 2){
  418. $createTime = $info['create_time']? strtotime($info['create_time']) : time();
  419. $time = intval(time() - $createTime);
  420. $info['status'] = $status;
  421. $info['end_time'] = time();
  422. $info['live_hour'] = $time > 3600 ? intval($time/3600) : 0;
  423. $info['live_minute'] = $time%3600? intval($time%3600/60) : 0;
  424. $info['time_text'] = $createTime<(time() - 86400)? date('m-d H:i', $createTime) : date('H:i', $createTime);
  425. $info['end_time_text'] = $info['end_time']<(time() - 86400)? date('m-d H:i', $info['end_time']) : date('H:i', $info['end_time']);
  426. $info['fans_num'] = MemberCollectService::make()->getViewFansCountByType($info['user_id'], $id, 2);
  427. $info['new_fans'] = MemberCollectService::make()->getNewFansCount($info['user_id'], $id,2, $createTime);
  428. }
  429. return $info;
  430. }
  431. $this->error = 1003;
  432. return true;
  433. }
  434. /**
  435. * 点赞
  436. * @return bool
  437. */
  438. public function like($userId, $params)
  439. {
  440. $liveId = isset($params['live_id'])? intval($params['live_id']) : 0;
  441. $num = isset($params['num'])? intval($params['num']) : 0;
  442. if($liveId<=0 || $num<=0){
  443. return false;
  444. }
  445. $info = $this->getCacheInfo($liveId);
  446. if(empty($info)){
  447. return false;
  448. }
  449. if($this->model->where(['id'=> $liveId])->update(['like_num'=>DB::raw("like_num + {$num}"),'update_time'=>time()])){
  450. $this->error = 1017;
  451. return ['id'=>$liveId,'like_num'=>intval($info['like_num'] + $num),'nun'=>$num];
  452. }
  453. return false;
  454. }
  455. /**
  456. * 获取直播推流/拉流地址
  457. * @param $streamName
  458. * @param string $appName
  459. * @param string $playType
  460. * @param int $expireTime
  461. * @return array
  462. */
  463. public function getLiveUrl($streamName, $appName = 'xlapp', $playType = 'rtmp', $expireTime = 1440)
  464. {
  465. $cachekey = "caches:live:urls:{$streamName}_{$appName}_{$playType}";
  466. $datas = RedisService::get($cachekey);
  467. if($datas){
  468. return $datas;
  469. }
  470. $playUrls = [];
  471. //未开启鉴权Key的情况下
  472. $pushDomain = ConfigService::make()->getConfigByCode('live_push_url');
  473. $playDomain = ConfigService::make()->getConfigByCode('live_play_url');
  474. $pushKey = ConfigService::make()->getConfigByCode('push_url_key');
  475. $playKey = ConfigService::make()->getConfigByCode('play_url_key');
  476. $timeStamp = time() + $expireTime * 60;
  477. if ($pushKey == '') {
  478. $pushUrl = 'rtmp://' . $pushDomain . '/' . $appName . '/' . $streamName;
  479. } else {
  480. $sstring = '/' . $appName . '/' . $streamName . '-' . $timeStamp . '-0-0-' . $pushKey;
  481. $md5hash = md5($sstring);
  482. $pushUrl = 'rtmp://' . $pushDomain . '/' . $appName . '/' . $streamName . '?auth_key=' . $timeStamp . '-0-0-' . $md5hash;
  483. }
  484. if ($playKey == '') {
  485. $playUrls['rtmp'] = 'rtmp://' . $playDomain . '/' . $appName . '/' . $streamName;
  486. $playUrls['flv'] = 'http://' . $playDomain . '/' . $appName . '/' . $streamName . '.flv';
  487. $playUrls['hls'] = 'http://' . $playDomain . '/' . $appName . '/' . $streamName . '.m3u8';
  488. } else {
  489. $rtmpSstring = '/' . $appName . '/' . $streamName . '-' . $timeStamp . '-0-0-' . $playKey;
  490. $rtmpMd5hash = md5($rtmpSstring);
  491. $playUrls['rtmp'] = 'rtmp://' . $playDomain . '/' . $appName . '/' . $streamName . '?auth_key=' . $timeStamp . '-0-0-' . $rtmpMd5hash;
  492. $flvSstring = '/' . $appName . '/' . $streamName . '.flv-' . $timeStamp . '-0-0-' . $playKey;
  493. $flvMd5hash = md5($flvSstring);
  494. $playUrls['flv'] = 'http://' . $playDomain . '/' . $appName . '/' . $streamName . '.flv?auth_key=' . $timeStamp . '-0-0-' . $flvMd5hash;
  495. $hlsSstring = '/' . $appName . '/' . $streamName . '.m3u8-' . $timeStamp . '-0-0-' . $playKey;
  496. $hlsMd5hash = md5($hlsSstring);
  497. $playUrls['hls'] = 'http://' . $playDomain . '/' . $appName . '/' . $streamName . '.m3u8?auth_key=' . $timeStamp . '-0-0-' . $hlsMd5hash;
  498. }
  499. $datas = [
  500. 'push_url' => $pushUrl,
  501. 'play_url' => isset($playUrls[$playType]) ? $playUrls[$playType] : '',
  502. 'play_urls' => $playUrls,
  503. ];
  504. RedisService::set($cachekey, $datas, 1800);
  505. return $datas;
  506. }
  507. /**
  508. * 创建直播间
  509. * @param $userId 直逼用户
  510. * @param $params
  511. * @return array|false
  512. */
  513. public function create($userId, $params)
  514. {
  515. $liveLevel = ConfigService::make()->getConfigByCode('live_open_level');
  516. $liveLevel = $liveLevel > 0 ? $liveLevel : 0;
  517. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])->select(['id', 'nickname', 'member_level', 'status'])->first();
  518. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  519. $nickname = isset($userInfo['nickname']) ? $userInfo['nickname'] : '';
  520. $memberLevel = isset($userInfo['member_level']) ? $userInfo['member_level'] : 0;
  521. if (empty($userInfo) || $status != 1) {
  522. $this->error = 2024;
  523. return false;
  524. }
  525. if($memberLevel < $liveLevel){
  526. $this->error = 2040;
  527. return false;
  528. }
  529. // 验证是否有开播中断播的继续播
  530. $data = [
  531. 'type' => isset($params['type']) ? intval($params['type']) : 1,
  532. 'user_id' => $userId,
  533. 'title' => isset($params['title']) && $params['title'] ? trim($params['title']) : $nickname.'正在直播',
  534. 'description' => isset($params['description']) && $params['description'] ? trim($params['description']) : lang('我正在直播,快来看看吧'),
  535. 'category' => isset($params['category']) ? intval($params['category']) : 0,
  536. 'visible_type' => isset($params['visible_type']) ? intval($params['visible_type']) : 0,
  537. 'visible_users' => isset($params['visible_users']) ? trim($params['visible_users']) : '',
  538. 'chat_type' => isset($params['chat_type']) ? intval($params['chat_type']) : 0,
  539. 'chat_status' => isset($params['chat_status']) ? intval($params['chat_status']) : 1,
  540. 'pay_status' => isset($params['pay_status']) ? intval($params['pay_status']) : 1,
  541. 'open_area' => isset($params['open_area']) ? intval($params['open_area']) : 1,
  542. 'view_allow' => isset($params['view_allow']) ? intval($params['view_allow']) : 1,
  543. 'push_url' => isset($params['push_url']) ? trim($params['push_url']) : '',
  544. 'play_url' => isset($params['play_url']) ? trim($params['play_url']) : '',
  545. 'update_time'=> time(),
  546. 'status' =>1,
  547. 'mark'=>1,
  548. ];
  549. if($liveId = $this->model->where(['user_id'=> $userId,'status'=>1,'mark'=>1])->orderBy('create_time','desc')->value('id')){
  550. if(!$this->model->where(['user_id'=> $userId,'status'=>1,'mark'=>1])->update($data)){
  551. $this->error = 2042;
  552. return false;
  553. }
  554. }else{
  555. $data['create_time'] = time();
  556. $this->model->where(['user_id'=> $userId,'mark'=>1])->update(['status'=>2,'update_time'=>time()]);
  557. if(!$liveId = $this->model->insertGetId($data)){
  558. $this->error = 2042;
  559. return false;
  560. }
  561. }
  562. $data['id'] = $liveId;
  563. $data['member'] = MemberModel::where(['id'=> $userId])->select(['id','nickname','avatar','status'])->first();
  564. $data['member'] = $data['member']? $data['member'] : [];
  565. $data['member']['is_follow'] = 1;
  566. if(isset($data['member']['avatar'])){
  567. $data['member']['avatar'] = $data['member']['avatar']? $data['member']['avatar'] : '/images/member/logo.png';
  568. $data['member']['avatar'] = get_image_url($data['member']['avatar']);
  569. }
  570. $this->error = 2041;
  571. return $data;
  572. }
  573. /**
  574. * 直播打赏
  575. * @param $userId 打赏用户ID
  576. * @param $params 参数
  577. * @return bool
  578. */
  579. public function reward($userId, $params)
  580. {
  581. $liveId = isset($params['live_id'])? intval($params['live_id']) : 0;
  582. $giftId = isset($params['gift_id'])? intval($params['gift_id']) : 0;
  583. $liveInfo = $this->model->with(['member'])->where(['id'=> $liveId,'mark'=>1])
  584. ->select(['id','user_id','category','pay_status','reward_num','status'])
  585. ->first();
  586. $status = isset($liveInfo['status'])? $liveInfo['status'] : 0;
  587. $payStatus = isset($liveInfo['pay_status'])? $liveInfo['pay_status'] : 0;
  588. $liveUserId = isset($liveInfo['user_id'])? $liveInfo['user_id'] : 0;
  589. $liveMember = isset($liveInfo['member'])? $liveInfo['member'] : [];
  590. $liveUserUsdt = isset($liveMember['usdt'])? $liveMember['usdt'] : 0;
  591. $bonusUserId = isset($liveMember['parent_id'])? $liveMember['parent_id'] : 0;
  592. if(empty($liveInfo) || empty($liveMember) || $status != 1){
  593. $this->error = 2301;
  594. return false;
  595. }
  596. if($payStatus!=1){
  597. $this->error = 2302;
  598. return false;
  599. }
  600. $giftInfo = LiveGiftModel::where(['id'=> $giftId,'status'=>1,'mark'=>1])
  601. ->select(['id','name','money'])
  602. ->first();
  603. $money = isset($giftInfo['money'])? intval($giftInfo['money']) : 0;
  604. if(empty($giftInfo) || $money<=0){
  605. $this->error = 2303;
  606. return false;
  607. }
  608. // 用户信息
  609. $userInfo = MemberModel::where(['id'=> $userId,'mark'=>1])
  610. ->select(['id','nickname','parent_id','point_id','balance','status'])
  611. ->first();
  612. $balance = isset($userInfo['balance'])? floatval($userInfo['balance']) : 0;
  613. if($balance < $money){
  614. $this->error = 2304;
  615. return false;
  616. }
  617. // 直播推荐人(经纪人)
  618. $bounsUserInfo = [];
  619. $bonusUserLevel = 0;
  620. $bonusUserUsdt = 0;
  621. if($bonusUserId){
  622. $bounsUserInfo = MemberModel::where(['id'=> $bonusUserId,'status'=>1,'mark'=>1])
  623. ->select(['id','nickname','parent_id','point_id','member_level','usdt','balance','status'])
  624. ->first();
  625. $bonusUserLevel = isset($bounsUserInfo['member_level'])? $bounsUserInfo['member_level'] : 0;
  626. $bonusUserUsdt = isset($bounsUserInfo['usdt'])? $bounsUserInfo['usdt'] : 0;
  627. }
  628. // TODO 打赏订单
  629. $orderNo = get_order_num('RW');
  630. $awardLevel = ConfigService::make()->getConfigByCode('live_award_level',5); // 推荐奖励等级
  631. $awardLevel = $awardLevel>=1 && $awardLevel<=30? $awardLevel : 5;
  632. $awardRate = ConfigService::make()->getConfigByCode('award_rewad_rate',10); // 推荐奖励比例%
  633. $awardRate = $awardRate>=0 && $awardLevel<100? $awardRate : 10;
  634. $xdPrice = ConfigService::make()->getConfigByCode('xd_price',100); // 星豆价格
  635. $xdPrice = $xdPrice>0.01 && $xdPrice <=10000? $xdPrice : 100;
  636. $usdt = moneyFormat($money/$xdPrice,2);
  637. // 推荐佣金
  638. $bonusUsdt = $awardRate? moneyFormat($usdt * $awardRate/100, 4) : 0;
  639. DB::beginTransaction();
  640. $order = [
  641. 'live_id'=> $liveId,
  642. 'user_id'=> $userId,
  643. 'live_user_id'=> $liveUserId,
  644. 'gift_id'=> $giftId,
  645. 'order_no'=> $orderNo,
  646. 'type'=> 1,
  647. 'money'=> $money,
  648. 'usdt'=> $usdt,
  649. 'bonus_rate'=> $awardRate? $awardRate : 0,
  650. 'bonus_usdt'=> $bonusUserId>0? $bonusUsdt : 0,
  651. 'bonus_uid'=> $bonusUserId,
  652. 'bonus_status'=> $bonusUserLevel >= $awardLevel? 1 : 2,
  653. 'create_time'=> time(),
  654. 'status'=> 1,
  655. 'mark'=>1
  656. ];
  657. if(!$orderId = RewardOrderModel::insertGetId($order)){
  658. DB::rollBack();
  659. $this->error = 2305;
  660. RedisService::set("caches:live:reward:error_{$userId}", ['data'=> $order,'error'=>'创建订单失败'], 600);
  661. return false;
  662. }
  663. // 扣除打赏用户余额
  664. $updateData = ['balance'=>DB::raw("balance - {$money}"),'update_time'=>time()];
  665. if(!MemberModel::where(['id'=> $userId,'mark'=>1])->update($updateData)){
  666. DB::rollBack();
  667. $this->error = 2305;
  668. RedisService::set("caches:live:reward:error_{$userId}", ['data'=> $order,'error'=>'账户扣款失败'], 600);
  669. return false;
  670. }
  671. // 明细
  672. $log = [
  673. 'user_id'=> $userId,
  674. 'source_id'=> $liveId,
  675. 'source_order_no'=> $orderNo,
  676. 'user_type'=> 1,
  677. 'type'=>1,
  678. 'coin_type'=> 2,
  679. 'money'=> -$usdt,
  680. 'date'=> date('Y-m-d'),
  681. 'actual_money'=> -$money,
  682. 'balance'=> $balance,
  683. 'create_time'=> time(),
  684. 'remark'=> '礼物打赏消费',
  685. 'status'=> 1,
  686. 'mark'=> 1,
  687. ];
  688. if(!AccountLogModel::insertGetId($log)){
  689. DB::rollBack();
  690. $this->error = 2305;
  691. RedisService::set("caches:live:reward:error_{$userId}", ['data'=> $order,'error'=>'账户明细处理失败'], 600);
  692. return false;
  693. }
  694. // TODO 推荐奖励(等级需要超过)
  695. $realUsdt = $usdt;
  696. $dateTime = date('Y-m-d H:i:s');
  697. $liveName = isset($liveMember['nickname']) && $liveMember['nickname']? $liveMember['nickname'] : $liveUserId;
  698. $userNickname = isset($userInfo['nickname']) && $userInfo['nickname']? $userInfo['nickname'] : $userId;
  699. if($bonusUserId>0 && $bonusUserLevel >= $awardLevel && $bonusUsdt>0){
  700. // 账户变动
  701. $updateData = ['usdt'=>DB::raw("usdt + {$bonusUsdt}"),'update_time'=>time()];
  702. if(!MemberModel::where(['id'=> $bonusUserId,'mark'=>1])->update($updateData)){
  703. DB::rollBack();
  704. $this->error = 2305;
  705. RedisService::set("caches:live:reward:error_{$userId}", ['data'=> $order,'update'=>$updateData,'usdt'=>$bonusUsdt,'error'=>'主播推荐奖励处理失败'], 600);
  706. return false;
  707. }
  708. // 明细
  709. $log = [
  710. 'user_id'=> $bonusUserId,
  711. 'source_id'=> $liveId,
  712. 'source_order_no'=> $orderNo,
  713. 'user_type'=> 1,
  714. 'type'=> 10,
  715. 'coin_type'=> 1,
  716. 'money'=> $bonusUsdt,
  717. 'date'=> date('Y-m-d'),
  718. 'actual_money'=> $bonusUsdt,
  719. 'balance'=> $bonusUserUsdt,
  720. 'create_time'=> time(),
  721. 'remark'=> '打赏推荐奖励',
  722. 'status'=> 1,
  723. 'mark'=> 1,
  724. ];
  725. if(!AccountLogModel::insertGetId($log)){
  726. DB::rollBack();
  727. $this->error = 2305;
  728. RedisService::set("caches:live:reward:error_{$userId}", ['data'=> $order,'error'=>'主播推荐奖励明细处理失败'], 600);
  729. return false;
  730. }
  731. // 消息
  732. MessageService::make()->pushMessage($userId, lang('打赏推荐奖励通知'), lang('打赏推荐奖励通知内容',['time'=> $dateTime,'usdt'=>$bonusUsdt,'live_name'=>$liveName]),3);
  733. $realUsdt = moneyFormat($usdt - $bonusUsdt, 4);
  734. }
  735. // 被打赏主播账户USDT账户进账
  736. $updateData = ['usdt'=>DB::raw("usdt + {$realUsdt}"),'update_time'=>time()];
  737. if(!MemberModel::where(['id'=> $liveUserId,'mark'=>1])->update($updateData)){
  738. DB::rollBack();
  739. $this->error = 2305;
  740. RedisService::set("caches:live:reward:error_{$userId}", ['data'=> $order,'error'=>'打赏进账处理失败'], 600);
  741. return false;
  742. }
  743. // 明细
  744. $log = [
  745. 'user_id'=> $liveUserId,
  746. 'source_id'=> $liveId,
  747. 'source_order_no'=> $orderNo,
  748. 'user_type'=> 1,
  749. 'type'=> 1,
  750. 'coin_type'=> 1,
  751. 'money'=> $realUsdt,
  752. 'date'=> date('Y-m-d'),
  753. 'actual_money'=> $realUsdt,
  754. 'balance'=> $liveUserUsdt,
  755. 'create_time'=> time(),
  756. 'remark'=> '礼物打赏收入',
  757. 'status'=> 1,
  758. 'mark'=> 1,
  759. ];
  760. if(!AccountLogModel::insertGetId($log)){
  761. DB::rollBack();
  762. $this->error = 2305;
  763. RedisService::set("caches:live:reward:error_{$userId}", ['data'=> $order,'error'=>'打赏进账明细处理失败'], 600);
  764. return false;
  765. }
  766. // TODO 浏览用户更新打赏统计
  767. if(!VideoCollectService::make()->getCollectCacheInfo($userId, $liveId, 1,2)){
  768. $data = [
  769. 'user_id'=> $userId,
  770. 'type'=> 1,
  771. 'source_type'=> 2,
  772. 'collect_id'=> $liveId,
  773. 'reward_total'=> $money,
  774. 'category_id'=> isset($liveInfo['category'])? $liveInfo['category'] : 0,
  775. 'collect_uid'=> isset($liveInfo['user_id'])? $liveInfo['user_id'] : 0,
  776. 'create_time'=> time(),
  777. 'status'=> 1,
  778. ];
  779. if(!VideoCollectModel::insertGetId($data)){
  780. DB::rollBack();
  781. $this->error = 2305;
  782. RedisService::set("caches:live:reward:error_{$userId}", ['data'=> $order,'error'=>'更新打赏统计失败'], 600);
  783. return false;
  784. }
  785. RedisService::set("caches:videos:collect:temp_{$userId}_{$liveId}_1_2", $data, rand(10,30));
  786. RedisService::clear("caches:videos:recommend:{$userId}_1_2");
  787. RedisService::clear("caches:member:fans:{$userId}_{$liveId}_2");
  788. RedisService::clear("caches:live:users_{$liveId}_{$userId}");
  789. }
  790. // 更新
  791. else if (!VideoCollectModel::where(['user_id'=> $userId,'type'=>1,'source_type'=>2, 'collect_id'=>$liveId])->update(['reward_total'=> DB::raw("reward_total + {$money}"),'update_time'=>time()])){
  792. DB::rollBack();
  793. $this->error = 2305;
  794. RedisService::set("caches:live:reward:error_{$userId}", ['data'=> $order,'error'=>'更新打赏统计失败1'], 600);
  795. return false;
  796. }
  797. // TODO 直播间打赏统计
  798. $updateData = ['reward_total'=>DB::raw("reward_total + {$money}"),'update_time'=>time()];
  799. if(!$this->checkUserReward($userId, $liveId) || $liveInfo['reward_num']<=0){
  800. // 打赏人数统计
  801. $updateData['reward_num'] = DB::raw("reward_num + 1");
  802. }
  803. if(!$this->model->where(['id'=> $liveId])->update($updateData)){
  804. DB::rollBack();
  805. $this->error = 2305;
  806. RedisService::set("caches:live:reward:error_{$userId}", ['data'=> $order,'error'=>'更新打赏统计失败2'], 600);
  807. return false;
  808. }
  809. DB::commit();
  810. // TODO 推送站内消息
  811. MessageService::make()->pushMessage($userId, lang('打赏消费通知'), lang('打赏消费通知内容',['time'=> $dateTime,'money'=>$money,'live_name'=>$liveName]),3);
  812. MessageService::make()->pushMessage($liveUserId, lang('打赏通知'), lang('打赏通知内容',['time'=> $dateTime,'money'=>$money,'nickname'=>$userNickname]),3);
  813. $this->error = 2306;
  814. return ['id'=>$orderId];
  815. }
  816. /**
  817. * 验证是否打赏过
  818. * @param $userId 打赏用户ID
  819. * @param $liveId 直播间ID
  820. * @return array|mixed
  821. */
  822. public function checkUserReward($userId, $liveId)
  823. {
  824. $cacheKey = "caches:live:reward:{$userId}_{$liveId}";
  825. $data = RedisService::get($cacheKey);
  826. if($data || RedisService::exists($cacheKey)){
  827. return $data;
  828. }
  829. $data = RewardOrderModel::where(['user_id'=> $userId,'live_id'=> $liveId])->value('id');
  830. if($data){
  831. RedisService::set($cacheKey, $data, rand(3600, 7200));
  832. }
  833. return $data;
  834. }
  835. }