LiveService.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  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. if($info && isset($info['member'])){
  162. if(isset($info['member']['avatar'])){
  163. $info['member']['avatar'] = $info['member']['avatar']? $info['member']['avatar'] : '/images/member/logo.png';
  164. $info['member']['avatar'] = get_image_url($info['member']['avatar']);
  165. }
  166. if($info['user_id'] == $userId){
  167. $info['is_follow'] = 1;
  168. }else{
  169. $checkFollow = MemberCollectService::make()->checkCollect($userId, $info['user_id'], 1);
  170. $info['is_follow'] = $checkFollow? 1 : 0;
  171. }
  172. // 观看权限
  173. $info['view_limit'] = 0;
  174. // 浏览历史
  175. if(!VideoCollectService::make()->getCollectCacheInfo($userId, $id, 1, 2)){
  176. $data = [
  177. 'user_id'=> $userId,
  178. 'type'=> 1,
  179. 'source_type'=> 2,
  180. 'collect_id'=> $id,
  181. 'collect_uid'=> isset($info['user_id'])? $info['user_id'] : 0,
  182. 'tags'=> isset($info['tags'])? $info['tags'] : '',
  183. 'create_time'=> time(),
  184. 'status'=> 1,
  185. ];
  186. VideoCollectModel::insert($data);
  187. RedisService::clear("caches:videos:recommend:{$userId}_2");
  188. RedisService::clear("caches:member:fans:{$userId}_{$id}_2");
  189. RedisService::clear("caches:live:users_{$id}_{$userId}");
  190. }
  191. // 更新播放量
  192. if(!RedisService::get("caches:live:player:{$userId}_{$id}")){
  193. $this->model->where(['id'=> $id])->update(['views'=>DB::raw('views + 1'),'update_time'=>time()]);
  194. RedisService::set("caches:live:player:{$userId}_{$id}", ['user_id'=> $userId,'id'=>$id], rand(600, 1800));
  195. $info['views'] += 1;
  196. }
  197. // 结束直播
  198. /*if($info['create_time'] <= time() - 2 * 86400 && $info['status'] == 1){
  199. $this->model->where(['id'=> $id])->update(['status'=>2,'update_time'=>time()]);
  200. $info['status'] = 2;
  201. }*/
  202. }
  203. return $info;
  204. }
  205. /**
  206. * 获取直播间在线观众数据
  207. * @param $params
  208. * @param $pageSize
  209. * @param int $userId
  210. * @return array|mixed
  211. */
  212. public function getUserList($params, $pageSize=200, $userId=0)
  213. {
  214. $liveId = isset($params['live_id'])? $params['live_id'] : 0;
  215. $cachekey = "caches:live:users_{$liveId}_{$userId}";
  216. $datas = RedisService::get($cachekey);
  217. if($datas || RedisService::exists($cachekey)){
  218. return $datas? $datas : [
  219. 'current' => ['user_id'=> $userId,'rank'=>0,'reward_total'=>0],
  220. 'rank_limit'=> 200,
  221. 'total' => 0,
  222. 'list' => []
  223. ];
  224. }
  225. $rankNum = ConfigService::make()->getConfigByCode('live_show_rank', 200);
  226. $rankNum = $rankNum>20 && $rankNum <= 300? $rankNum : 200;
  227. $model = MemberModel::from('member as a')
  228. ->leftJoin('video_collect as b',function($join) use($liveId){
  229. $join->on('a.id','=','b.user_id')
  230. ->where(['b.type'=>1,'b.collect_id'=> $liveId,'b.source_type'=>2,'b.is_online'=>1,'b.status'=>1,'b.mark'=>1]);
  231. })
  232. ->where(['a.status'=>1,'a.mark'=>1])
  233. ->where('b.id','>', 0)
  234. ->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']);
  235. $countModel = clone $model;
  236. $total = $countModel->distinct('a.id')->count('a.id');
  237. $datas = $model->groupBy('a.id')
  238. ->orderBy('b.reward_total','desc')
  239. ->orderBy('b.create_time','asc')
  240. ->limit($rankNum)->get();
  241. $datas = $datas? $datas->toArray() : [];
  242. $rankData = ['user_id'=> $userId,'rank'=>0,'reward_total'=>0];
  243. if ($datas) {
  244. foreach ($datas as $k=> &$item) {
  245. $item['time_text'] = isset($item['create_time']) ? dateFormat($item['create_time'], 'Y-m-d H:i') : '';
  246. $item['avatar'] = isset($item['avatar']) && $item['avatar']? get_image_url($item['avatar']) : get_image_url('/images/member/logo.png');
  247. $item['reward_total'] = isset($item['reward_total']) && $item['reward_total']? format_num(intval($item['reward_total'])) : 0;
  248. if($item['id'] == $userId){
  249. $rankData['rank'] = ($k+1)>$rankNum? 0 : ($k+1);
  250. $rankData['reward_total'] = $item['reward_total']? format_num(intval($item['reward_total'])) : 0;
  251. }
  252. }
  253. // 用户排名在200名外的数据
  254. if($rankData['rank'] <= 0 && $rankData['reward_total']<=0 && count($datas) > $rankNum){
  255. $rewardTotal = VideoCollectModel::where(['user_id'=> $userId,'type'=>1,'collect_id'=> $liveId,'source_type'=>2,'status'=>1,'mark'=>1])
  256. ->value('reward_total');
  257. $rankData['reward_total'] = $rewardTotal? format_num(intval($rewardTotal)) : 0;
  258. }
  259. $totalText = $total>=10000 && $total<=100000? intval($total/10000).'万' : intval($total);
  260. RedisService::set($cachekey, ['current' => $rankData,'rank_limit'=> $rankNum,'total'=> $total,'total_text'=>$totalText,'list'=> $datas], rand(3,5));
  261. }
  262. return [
  263. 'current' => $rankData,
  264. 'rank_limit'=> $rankNum,
  265. 'total' => $total,
  266. 'total_text' => $total>=10000 && $total<=100000? intval($total/10000).'万' : intval($total),
  267. 'list' => $datas
  268. ];
  269. }
  270. /**
  271. * 获取直播间礼物列表
  272. * @param $params
  273. * @param $pageSize
  274. * @param int $userId
  275. * @return array|mixed
  276. */
  277. public function getGiftList($params, $pageSize=30, $userId=0)
  278. {
  279. $page = request()->post('page', 1);
  280. $liveId = isset($params['live_id'])? $params['live_id'] : 0;
  281. $cachekey = "caches:live:gift_{$liveId}_{$userId}_{$page}";
  282. $datas = RedisService::get($cachekey);
  283. if($datas || RedisService::exists($cachekey)){
  284. return $datas? $datas : [
  285. 'pageSize'=> $pageSize,
  286. 'total' => 0,
  287. 'list' => []
  288. ];
  289. }
  290. $list = LiveGiftModel::from('live_gift as a')
  291. ->where(['a.status'=>1,'a.mark'=>1])
  292. ->select(['a.id','a.name','a.code','a.money','a.icon','a.file_url','a.sort'])
  293. ->orderBy('a.sort','desc')
  294. ->orderBy('a.create_time','asc')
  295. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  296. $list = $list ? $list->toArray() : [];
  297. if ($list && $list['data']) {
  298. foreach ($list['data'] as &$item) {
  299. $item['icon'] = isset($item['icon']) && $item['icon']? get_image_url($item['icon']) : get_image_url('/images/gift/gift.png');
  300. $item['file_url'] = isset($item['file_url']) && $item['file_url']? get_image_url($item['file_url']) : '';
  301. }
  302. RedisService::set($cachekey, [
  303. 'pageSize' => $pageSize,
  304. 'total' => isset($list['total']) ? $list['total'] : 0,
  305. 'list' => isset($list['data']) ? $list['data'] : []
  306. ], rand(5,10));
  307. }
  308. return [
  309. 'pageSize' => $pageSize,
  310. 'total' => isset($list['total']) ? $list['total'] : 0,
  311. 'list' => isset($list['data']) ? $list['data'] : []
  312. ];
  313. }
  314. /**
  315. * 更新播放浏览历史
  316. * @param $userId 用户ID
  317. * @param $id 视频ID
  318. * @return false
  319. */
  320. public function updatePlay($userId, $id)
  321. {
  322. // 浏览历史
  323. if(!VideoCollectService::make()->getCollectCacheInfo($userId, $id, 1,2)){
  324. $info = $this->model->from('live as a')
  325. ->where(['a.id'=> $id,'a.mark'=>1])
  326. ->select(['a.id','a.category','a.user_id'])
  327. ->first();
  328. if(empty($info)){
  329. return false;
  330. }
  331. $data = [
  332. 'user_id'=> $userId,
  333. 'type'=> 1,
  334. 'source_type'=> 2,
  335. 'collect_id'=> $id,
  336. 'category_id'=> isset($info['category'])? $info['category'] : 0,
  337. 'collect_uid'=> isset($info['user_id'])? $info['user_id'] : 0,
  338. 'create_time'=> time(),
  339. 'status'=> 1,
  340. ];
  341. VideoCollectModel::insert($data);
  342. RedisService::set("caches:videos:collect:temp_{$userId}_{$id}_1_2", $data, rand(10,30));
  343. RedisService::clear("caches:videos:recommend:{$userId}_1_2");
  344. RedisService::clear("caches:member:fans:{$userId}_{$id}_2");
  345. RedisService::clear("caches:live:users_{$id}_{$userId}");
  346. }
  347. // 更新播放量
  348. if(!RedisService::get("caches:player:live:{$userId}_{$id}")){
  349. $this->model->where(['id'=> $id])->update(['views'=>DB::raw('views + 1'),'update_time'=>time()]);
  350. RedisService::set("caches:player:live:{$userId}_{$id}", ['user_id'=> $userId,'id'=>$id], rand(6*3600, 86400));
  351. }
  352. $this->error = 1010;
  353. return true;
  354. }
  355. /**
  356. * 缓存数据
  357. * @param $id
  358. * @param int $status
  359. * @return array|mixed
  360. */
  361. public function getCacheInfo($id, $status=0)
  362. {
  363. $cacheKey = "caches:live:info:{$id}_{$status}";
  364. $info = RedisService::get($cacheKey);
  365. if($info){
  366. return $info;
  367. }
  368. $where = ['id' => $id, 'mark' => 1];
  369. if($status){
  370. $where['status'] = $status;
  371. }
  372. $info = $this->model->where($where)
  373. ->select(['id','user_id','create_time','end_time','views','reward_num','reward_total','like_num'])
  374. ->first();
  375. $info = $info? $info->toArray() : [];
  376. if($info){
  377. RedisService::set($cacheKey, $info, rand(3, 5));
  378. }
  379. return $info;
  380. }
  381. /**
  382. * 状态设置
  383. * @return bool
  384. */
  385. public function status()
  386. {
  387. $id = request()->post('id', 0);
  388. $status = request()->post('status', 2);
  389. if ($id && !$info = $this->getCacheInfo($id)) {
  390. $this->error = 2981;
  391. return false;
  392. }
  393. $updateData = ['status'=>$status, 'update_time'=> time()];
  394. if($status == 2){
  395. $updateData['end_time'] = time();
  396. }
  397. if($this->model->where(['id'=> $id,'mark'=>1])->update($updateData)){
  398. $this->error = 1002;
  399. $createTime = $info['create_time']? strtotime($info['create_time']) : time();
  400. $time = $info['end_time']? intval($info['end_time'] - $createTime) : intval(time() - $createTime);
  401. $info['status'] = $status;
  402. $info['live_hour'] = $time > 3600 ? intval($time/3600) : 0;
  403. $info['live_minute'] = $time%3600? intval($time%3600/60) : 0;
  404. $info['time_text'] = date('H:i', $createTime);
  405. $info['end_time_text'] = date('H:i', $info['end_time']? $info['end_time'] : time());
  406. $info['fans_num'] = MemberCollectService::make()->getViewFansCountByType($info['user_id'], $id, 2);
  407. $info['new_fans'] = MemberCollectService::make()->getNewFansCount($info['user_id'], $id,2, $createTime);
  408. return $info;
  409. }
  410. $this->error = 1003;
  411. return true;
  412. }
  413. /**
  414. * 点赞
  415. * @return bool
  416. */
  417. public function like($userId, $params)
  418. {
  419. $liveId = isset($params['live_id'])? intval($params['live_id']) : 0;
  420. $num = isset($params['num'])? intval($params['num']) : 0;
  421. if($liveId<=0 || $num<=0){
  422. return false;
  423. }
  424. $info = $this->getCacheInfo($liveId);
  425. if(empty($info)){
  426. return false;
  427. }
  428. if($this->model->where(['id'=> $liveId])->update(['like_num'=>DB::raw("like_num + {$num}"),'update_time'=>time()])){
  429. $this->error = 1017;
  430. return ['id'=>$liveId,'like_num'=>intval($info['like_num'] + $num),'nun'=>$num];
  431. }
  432. return false;
  433. }
  434. /**
  435. * 获取直播推流/拉流地址
  436. * @param $streamName
  437. * @param string $appName
  438. * @param string $playType
  439. * @param int $expireTime
  440. * @return array
  441. */
  442. public function getLiveUrl($streamName, $appName = 'xlapp', $playType = 'rtmp', $expireTime = 1440)
  443. {
  444. $cachekey = "caches:live:urls:{$streamName}_{$appName}_{$playType}";
  445. $datas = RedisService::get($cachekey);
  446. if($datas){
  447. return $datas;
  448. }
  449. $playUrls = [];
  450. //未开启鉴权Key的情况下
  451. $pushDomain = ConfigService::make()->getConfigByCode('live_push_url');
  452. $playDomain = ConfigService::make()->getConfigByCode('live_play_url');
  453. $pushKey = ConfigService::make()->getConfigByCode('push_url_key');
  454. $playKey = ConfigService::make()->getConfigByCode('play_url_key');
  455. $timeStamp = time() + $expireTime * 60;
  456. if ($pushKey == '') {
  457. $pushUrl = 'rtmp://' . $pushDomain . '/' . $appName . '/' . $streamName;
  458. } else {
  459. $sstring = '/' . $appName . '/' . $streamName . '-' . $timeStamp . '-0-0-' . $pushKey;
  460. $md5hash = md5($sstring);
  461. $pushUrl = 'rtmp://' . $pushDomain . '/' . $appName . '/' . $streamName . '?auth_key=' . $timeStamp . '-0-0-' . $md5hash;
  462. }
  463. if ($playKey == '') {
  464. $playUrls['rtmp'] = 'rtmp://' . $playDomain . '/' . $appName . '/' . $streamName;
  465. $playUrls['flv'] = 'http://' . $playDomain . '/' . $appName . '/' . $streamName . '.flv';
  466. $playUrls['hls'] = 'http://' . $playDomain . '/' . $appName . '/' . $streamName . '.m3u8';
  467. } else {
  468. $rtmpSstring = '/' . $appName . '/' . $streamName . '-' . $timeStamp . '-0-0-' . $playKey;
  469. $rtmpMd5hash = md5($rtmpSstring);
  470. $playUrls['rtmp'] = 'rtmp://' . $playDomain . '/' . $appName . '/' . $streamName . '?auth_key=' . $timeStamp . '-0-0-' . $rtmpMd5hash;
  471. $flvSstring = '/' . $appName . '/' . $streamName . '.flv-' . $timeStamp . '-0-0-' . $playKey;
  472. $flvMd5hash = md5($flvSstring);
  473. $playUrls['flv'] = 'http://' . $playDomain . '/' . $appName . '/' . $streamName . '.flv?auth_key=' . $timeStamp . '-0-0-' . $flvMd5hash;
  474. $hlsSstring = '/' . $appName . '/' . $streamName . '.m3u8-' . $timeStamp . '-0-0-' . $playKey;
  475. $hlsMd5hash = md5($hlsSstring);
  476. $playUrls['hls'] = 'http://' . $playDomain . '/' . $appName . '/' . $streamName . '.m3u8?auth_key=' . $timeStamp . '-0-0-' . $hlsMd5hash;
  477. }
  478. $datas = [
  479. 'push_url' => $pushUrl,
  480. 'play_url' => isset($playUrls[$playType]) ? $playUrls[$playType] : '',
  481. 'play_urls' => $playUrls,
  482. ];
  483. RedisService::set($cachekey, $datas, 1800);
  484. return $datas;
  485. }
  486. /**
  487. * 创建直播间
  488. * @param $userId 直逼用户
  489. * @param $params
  490. * @return array|false
  491. */
  492. public function create($userId, $params)
  493. {
  494. $liveLevel = ConfigService::make()->getConfigByCode('live_open_level');
  495. $liveLevel = $liveLevel > 0 ? $liveLevel : 0;
  496. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])->select(['id', 'nickname', 'member_level', 'status'])->first();
  497. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  498. $nickname = isset($userInfo['nickname']) ? $userInfo['nickname'] : '';
  499. $memberLevel = isset($userInfo['member_level']) ? $userInfo['member_level'] : 0;
  500. if (empty($userInfo) || $status != 1) {
  501. $this->error = 2024;
  502. return false;
  503. }
  504. if($memberLevel < $liveLevel){
  505. $this->error = 2040;
  506. return false;
  507. }
  508. // 验证是否有开播中断播的继续播
  509. $data = [
  510. 'type' => isset($params['type']) ? intval($params['type']) : 1,
  511. 'user_id' => $userId,
  512. 'title' => isset($params['title']) && $params['title'] ? trim($params['title']) : $nickname.'正在直播',
  513. 'description' => isset($params['description']) && $params['description'] ? trim($params['description']) : lang('我正在直播,快来看看吧'),
  514. 'category' => isset($params['category']) ? intval($params['category']) : 0,
  515. 'visible_type' => isset($params['visible_type']) ? intval($params['visible_type']) : 0,
  516. 'visible_users' => isset($params['visible_users']) ? trim($params['visible_users']) : '',
  517. 'chat_type' => isset($params['chat_type']) ? intval($params['chat_type']) : 0,
  518. 'chat_status' => isset($params['chat_status']) ? intval($params['chat_status']) : 1,
  519. 'pay_status' => isset($params['pay_status']) ? intval($params['pay_status']) : 1,
  520. 'open_area' => isset($params['open_area']) ? intval($params['open_area']) : 1,
  521. 'view_allow' => isset($params['view_allow']) ? intval($params['view_allow']) : 1,
  522. 'push_url' => isset($params['push_url']) ? trim($params['push_url']) : '',
  523. 'play_url' => isset($params['play_url']) ? trim($params['play_url']) : '',
  524. 'update_time'=> time(),
  525. 'status' =>1,
  526. 'mark'=>1,
  527. ];
  528. if($liveId = $this->model->where(['user_id'=> $userId,'status'=>1,'mark'=>1])->orderBy('create_time','desc')->value('id')){
  529. if(!$this->model->where(['user_id'=> $userId,'status'=>1,'mark'=>1])->update($data)){
  530. $this->error = 2042;
  531. return false;
  532. }
  533. }else{
  534. $data['create_time'] = time();
  535. $this->model->where(['user_id'=> $userId,'mark'=>1])->update(['status'=>2,'update_time'=>time()]);
  536. if(!$liveId = $this->model->insertGetId($data)){
  537. $this->error = 2042;
  538. return false;
  539. }
  540. }
  541. $data['id'] = $liveId;
  542. $data['member'] = MemberModel::where(['id'=> $userId])->select(['id','nickname','avatar','status'])->first();
  543. $data['member'] = $data['member']? $data['member'] : [];
  544. $data['member']['is_follow'] = 1;
  545. if(isset($data['member']['avatar'])){
  546. $data['member']['avatar'] = $data['member']['avatar']? $data['member']['avatar'] : '/images/member/logo.png';
  547. $data['member']['avatar'] = get_image_url($data['member']['avatar']);
  548. }
  549. $this->error = 2041;
  550. return $data;
  551. }
  552. /**
  553. * 直播打赏
  554. * @param $userId 打赏用户ID
  555. * @param $params 参数
  556. * @return bool
  557. */
  558. public function reward($userId, $params)
  559. {
  560. $liveId = isset($params['live_id'])? intval($params['live_id']) : 0;
  561. $giftId = isset($params['gift_id'])? intval($params['gift_id']) : 0;
  562. $liveInfo = $this->model->with(['member'])->where(['id'=> $liveId,'mark'=>1])
  563. ->select(['id','user_id','category','pay_status','status'])
  564. ->first();
  565. $status = isset($liveInfo['status'])? $liveInfo['status'] : 0;
  566. $payStatus = isset($liveInfo['pay_status'])? $liveInfo['pay_status'] : 0;
  567. $liveUserId = isset($liveInfo['user_id'])? $liveInfo['user_id'] : 0;
  568. $liveMember = isset($liveInfo['member'])? $liveInfo['member'] : [];
  569. $liveUserUsdt = isset($liveMember['usdt'])? $liveMember['usdt'] : 0;
  570. $bonusUserId = isset($liveMember['parent_id'])? $liveMember['parent_id'] : 0;
  571. if(empty($liveInfo) || empty($liveMember) || $status != 1){
  572. $this->error = 2301;
  573. return false;
  574. }
  575. if($payStatus!=1){
  576. $this->error = 2302;
  577. return false;
  578. }
  579. $giftInfo = LiveGiftModel::where(['id'=> $giftId,'status'=>1,'mark'=>1])
  580. ->select(['id','name','money'])
  581. ->first();
  582. $money = isset($giftInfo['money'])? intval($giftInfo['money']) : 0;
  583. if(empty($giftInfo) || $money<=0){
  584. $this->error = 2303;
  585. return false;
  586. }
  587. // 用户信息
  588. $userInfo = MemberModel::where(['id'=> $userId,'mark'=>1])
  589. ->select(['id','nickname','parent_id','point_id','balance','status'])
  590. ->first();
  591. $balance = isset($userInfo['balance'])? floatval($userInfo['balance']) : 0;
  592. if($balance < $money){
  593. $this->error = 2304;
  594. return false;
  595. }
  596. // 直播推荐人(经纪人)
  597. $bounsUserInfo = [];
  598. $bonusUserLevel = 0;
  599. if($bonusUserId){
  600. $bounsUserInfo = MemberModel::where(['id'=> $bonusUserId,'status'=>1,'mark'=>1])
  601. ->select(['id','nickname','parent_id','point_id','member_level','usdt','balance','status'])
  602. ->first();
  603. $bonusUserLevel = isset($bounsUserInfo['member_level'])? $bounsUserInfo['member_level'] : 0;
  604. }
  605. // TODO 打赏订单
  606. $orderNo = get_order_num('RW');
  607. $awardLevel = ConfigService::make()->getConfigByCode('live_award_level',5); // 推荐奖励等级
  608. $awardLevel = $awardLevel>=1 && $awardLevel<=30? $awardLevel : 5;
  609. $awardRate = ConfigService::make()->getConfigByCode('award_rewad_rate',10); // 推荐奖励比例%
  610. $awardRate = $awardRate>=0 && $awardLevel<100? $awardRate : 10;
  611. $xdPrice = ConfigService::make()->getConfigByCode('xd_price',100); // 星豆价格
  612. $xdPrice = $xdPrice>0.01 && $xdPrice <=10000? $xdPrice : 100;
  613. $usdt = moneyFormat($money/$xdPrice,2);
  614. // 推荐佣金
  615. $bonusUsdt = $awardRate? moneyFormat($usdt * $awardRate/100, 4) : 0;
  616. DB::beginTransaction();
  617. $order = [
  618. 'live_id'=> $liveId,
  619. 'user_id'=> $userId,
  620. 'live_user_id'=> $liveUserId,
  621. 'gift_id'=> $giftId,
  622. 'order_no'=> $orderNo,
  623. 'type'=> 1,
  624. 'money'=> $money,
  625. 'usdt'=> $usdt,
  626. 'bonus_rate'=> $awardRate? $awardRate : 0,
  627. 'bonus_usdt'=> $bonusUserId>0? $bonusUsdt : 0,
  628. 'bonus_uid'=> $bonusUserId,
  629. 'bonus_status'=> $bonusUserLevel >= $awardLevel? 1 : 2,
  630. 'create_time'=> time(),
  631. 'status'=> 1,
  632. 'mark'=>1
  633. ];
  634. if(!$orderId = RewardOrderModel::insertGetId($order)){
  635. DB::rollBack();
  636. $this->error = 2305;
  637. return false;
  638. }
  639. // 扣除打赏用户余额
  640. $updateData = ['balance'=>DB::raw("balance - {$money}"),'update_time'=>time()];
  641. if(!MemberModel::where(['id'=> $userId,'mark'=>1])->update($updateData)){
  642. DB::rollBack();
  643. $this->error = 2305;
  644. return false;
  645. }
  646. // 明细
  647. $log = [
  648. 'user_id'=> $userId,
  649. 'source_id'=> $liveId,
  650. 'source_order_no'=> $orderNo,
  651. 'user_type'=> 1,
  652. 'type'=>1,
  653. 'coin_type'=> 2,
  654. 'money'=> $money,
  655. 'date'=> date('Y-m-d'),
  656. 'actual_money'=> $usdt,
  657. 'balance'=> $balance,
  658. 'create_time'=> time(),
  659. 'remark'=> '礼物打赏',
  660. 'status'=> 1,
  661. 'mark'=> 1,
  662. ];
  663. if(!AccountLogModel::insertGetId($log)){
  664. DB::rollBack();
  665. $this->error = 2305;
  666. return false;
  667. }
  668. // 被打赏主播账户USDT账户进账
  669. $updateData = ['usdt'=>DB::raw("usdt + {$usdt}"),'update_time'=>time()];
  670. if(!MemberModel::where(['id'=> $liveUserId,'mark'=>1])->update($updateData)){
  671. DB::rollBack();
  672. $this->error = 2305;
  673. return false;
  674. }
  675. // 明细
  676. $log = [
  677. 'user_id'=> $liveUserId,
  678. 'source_id'=> $liveId,
  679. 'source_order_no'=> $orderNo,
  680. 'user_type'=> 1,
  681. 'type'=> 1,
  682. 'coin_type'=> 1,
  683. 'money'=> $usdt,
  684. 'date'=> date('Y-m-d'),
  685. 'actual_money'=> $usdt,
  686. 'balance'=> $liveUserUsdt,
  687. 'create_time'=> time(),
  688. 'remark'=> '礼物打赏',
  689. 'status'=> 1,
  690. 'mark'=> 1,
  691. ];
  692. if(!AccountLogModel::insertGetId($log)){
  693. DB::rollBack();
  694. $this->error = 2305;
  695. return false;
  696. }
  697. // TODO 浏览用户更新打赏统计
  698. if(!VideoCollectService::make()->getCollectCacheInfo($userId, $liveId, 1,2)){
  699. $data = [
  700. 'user_id'=> $userId,
  701. 'type'=> 1,
  702. 'source_type'=> 2,
  703. 'collect_id'=> $liveId,
  704. 'reward_total'=> $money,
  705. 'category_id'=> isset($liveInfo['category'])? $liveInfo['category'] : 0,
  706. 'collect_uid'=> isset($liveInfo['user_id'])? $liveInfo['user_id'] : 0,
  707. 'create_time'=> time(),
  708. 'status'=> 1,
  709. ];
  710. if(!VideoCollectModel::insertGetId($data)){
  711. DB::rollBack();
  712. $this->error = 2305;
  713. return false;
  714. }
  715. RedisService::set("caches:videos:collect:temp_{$userId}_{$liveId}_1_2", $data, rand(10,30));
  716. RedisService::clear("caches:videos:recommend:{$userId}_1_2");
  717. RedisService::clear("caches:member:fans:{$userId}_{$liveId}_2");
  718. RedisService::clear("caches:live:users_{$liveId}_{$userId}");
  719. }
  720. // 更新
  721. 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()])){
  722. DB::rollBack();
  723. $this->error = 2305;
  724. return false;
  725. }
  726. // TODO 直播间打赏统计
  727. $updateData = ['reward_total'=>DB::raw("reward_total + {$money}"),'update_time'=>time()];
  728. if(!$this->checkUserReward($userId, $liveId)){
  729. // 打赏人数统计
  730. $updateData['reward_num'] = DB::raw("reward_num + 1");
  731. }
  732. if(!$this->model->where(['id'=> $liveId])->update($updateData)){
  733. DB::rollBack();
  734. $this->error = 2305;
  735. return false;
  736. }
  737. // TODO 推荐奖励(等级需要超过)
  738. $dateTime = date('Y-m-d H:i:s');
  739. $liveName = isset($liveMember['nickname']) && $liveMember['nickname']? $liveMember['nickname'] : $liveUserId;
  740. $userNickname = isset($userInfo['nickname']) && $userInfo['nickname']? $userInfo['nickname'] : $userId;
  741. if($bonusUserId>0 && $bonusUserLevel >= $awardLevel && $bonusUsdt>0){
  742. // 账户变动
  743. $updateData = ['usdt'=>DB::raw("usdt + {$bonusUsdt}"),'update_time'=>time()];
  744. if(!MemberModel::where(['id'=> $bonusUserId,'mark'=>1])->update($updateData)){
  745. DB::rollBack();
  746. $this->error = 2305;
  747. return false;
  748. }
  749. // 明细
  750. $log = [
  751. 'user_id'=> $bonusUserId,
  752. 'source_id'=> $liveId,
  753. 'source_order_no'=> $orderNo,
  754. 'user_type'=> 1,
  755. 'type'=> 10,
  756. 'coin_type'=> 1,
  757. 'money'=> $usdt,
  758. 'date'=> date('Y-m-d'),
  759. 'actual_money'=> $usdt,
  760. 'balance'=> $liveUserUsdt,
  761. 'create_time'=> time(),
  762. 'remark'=> '推荐打赏奖励',
  763. 'status'=> 1,
  764. 'mark'=> 1,
  765. ];
  766. if(!AccountLogModel::insertGetId($log)){
  767. DB::rollBack();
  768. $this->error = 2305;
  769. return false;
  770. }
  771. // 消息
  772. MessageService::make()->pushMessage($userId, lang('打赏推荐奖励通知'), lang('打赏推荐奖励通知内容',['time'=> $dateTime,'usdt'=>$bonusUsdt,'live_name'=>$liveName]),3);
  773. }
  774. DB::commit();
  775. // TODO 推送站内消息
  776. MessageService::make()->pushMessage($userId, lang('打赏消费通知'), lang('打赏消费通知内容',['time'=> $dateTime,'money'=>$money,'live_name'=>$liveName]),3);
  777. MessageService::make()->pushMessage($liveUserId, lang('打赏通知'), lang('打赏通知内容',['time'=> $dateTime,'money'=>$money,'nickname'=>$userNickname]),3);
  778. $this->error = 2306;
  779. return ['id'=>$orderId];
  780. }
  781. /**
  782. * 验证是否打赏过
  783. * @param $userId 打赏用户ID
  784. * @param $liveId 直播间ID
  785. * @return array|mixed
  786. */
  787. public function checkUserReward($userId, $liveId)
  788. {
  789. $cacheKey = "caches:live:reward:{$userId}_{$liveId}";
  790. $data = RedisService::get($cacheKey);
  791. if($data || RedisService::exists($cacheKey)){
  792. return $data;
  793. }
  794. $data = RewardOrderModel::where(['user_id'=> $userId,'live_id'=> $liveId])->value('id');
  795. if($data){
  796. RedisService::set($cacheKey, $data, rand(3600, 7200));
  797. }
  798. return $data;
  799. }
  800. }