LiveService.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  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. $time = $info['end_time']? intval($info['end_time'] - $info['create_time']) : intval(time() - $info['create_time']);
  400. $info['status'] = $status;
  401. $info['live_hour'] = $time > 3600 ? intval($time/3600) : 0;
  402. $info['live_minute'] = $time%3600? intval($time%3600/60) : 0;
  403. $info['time_text'] = date('H:i', $info['create_time']);
  404. $info['end_time_text'] = date('H:i', $info['end_time']? $info['end_time'] : time());
  405. $info['fans_num'] = MemberCollectService::make()->getViewFansCountByType($info['user_id'], $id, 2);
  406. $info['new_fans'] = MemberCollectService::make()->getNewFansCount($info['user_id'], $id,2, $info['create_time']);
  407. return $info;
  408. }
  409. $this->error = 1003;
  410. return true;
  411. }
  412. /**
  413. * 获取直播推流/拉流地址
  414. * @param $streamName
  415. * @param string $appName
  416. * @param string $playType
  417. * @param int $expireTime
  418. * @return array
  419. */
  420. public function getLiveUrl($streamName, $appName = 'xlapp', $playType = 'rtmp', $expireTime = 1440)
  421. {
  422. $cachekey = "caches:live:urls:{$streamName}_{$appName}_{$playType}";
  423. $datas = RedisService::get($cachekey);
  424. if($datas){
  425. return $datas;
  426. }
  427. $playUrls = [];
  428. //未开启鉴权Key的情况下
  429. $pushDomain = ConfigService::make()->getConfigByCode('live_push_url');
  430. $playDomain = ConfigService::make()->getConfigByCode('live_play_url');
  431. $pushKey = ConfigService::make()->getConfigByCode('push_url_key');
  432. $playKey = ConfigService::make()->getConfigByCode('play_url_key');
  433. $timeStamp = time() + $expireTime * 60;
  434. if ($pushKey == '') {
  435. $pushUrl = 'rtmp://' . $pushDomain . '/' . $appName . '/' . $streamName;
  436. } else {
  437. $sstring = '/' . $appName . '/' . $streamName . '-' . $timeStamp . '-0-0-' . $pushKey;
  438. $md5hash = md5($sstring);
  439. $pushUrl = 'rtmp://' . $pushDomain . '/' . $appName . '/' . $streamName . '?auth_key=' . $timeStamp . '-0-0-' . $md5hash;
  440. }
  441. if ($playKey == '') {
  442. $playUrls['rtmp'] = 'rtmp://' . $playDomain . '/' . $appName . '/' . $streamName;
  443. $playUrls['flv'] = 'http://' . $playDomain . '/' . $appName . '/' . $streamName . '.flv';
  444. $playUrls['hls'] = 'http://' . $playDomain . '/' . $appName . '/' . $streamName . '.m3u8';
  445. } else {
  446. $rtmpSstring = '/' . $appName . '/' . $streamName . '-' . $timeStamp . '-0-0-' . $playKey;
  447. $rtmpMd5hash = md5($rtmpSstring);
  448. $playUrls['rtmp'] = 'rtmp://' . $playDomain . '/' . $appName . '/' . $streamName . '?auth_key=' . $timeStamp . '-0-0-' . $rtmpMd5hash;
  449. $flvSstring = '/' . $appName . '/' . $streamName . '.flv-' . $timeStamp . '-0-0-' . $playKey;
  450. $flvMd5hash = md5($flvSstring);
  451. $playUrls['flv'] = 'http://' . $playDomain . '/' . $appName . '/' . $streamName . '.flv?auth_key=' . $timeStamp . '-0-0-' . $flvMd5hash;
  452. $hlsSstring = '/' . $appName . '/' . $streamName . '.m3u8-' . $timeStamp . '-0-0-' . $playKey;
  453. $hlsMd5hash = md5($hlsSstring);
  454. $playUrls['hls'] = 'http://' . $playDomain . '/' . $appName . '/' . $streamName . '.m3u8?auth_key=' . $timeStamp . '-0-0-' . $hlsMd5hash;
  455. }
  456. $datas = [
  457. 'push_url' => $pushUrl,
  458. 'play_url' => isset($playUrls[$playType]) ? $playUrls[$playType] : '',
  459. 'play_urls' => $playUrls,
  460. ];
  461. RedisService::set($cachekey, $datas, 1800);
  462. return $datas;
  463. }
  464. /**
  465. * 创建直播间
  466. * @param $userId 直逼用户
  467. * @param $params
  468. * @return array|false
  469. */
  470. public function create($userId, $params)
  471. {
  472. $liveLevel = ConfigService::make()->getConfigByCode('live_open_level');
  473. $liveLevel = $liveLevel > 0 ? $liveLevel : 0;
  474. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])->select(['id', 'nickname', 'member_level', 'status'])->first();
  475. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  476. $nickname = isset($userInfo['nickname']) ? $userInfo['nickname'] : '';
  477. $memberLevel = isset($userInfo['member_level']) ? $userInfo['member_level'] : 0;
  478. if (empty($userInfo) || $status != 1) {
  479. $this->error = 2024;
  480. return false;
  481. }
  482. if($memberLevel < $liveLevel){
  483. $this->error = 2040;
  484. return false;
  485. }
  486. // 验证是否有开播中断播的继续播
  487. $data = [
  488. 'type' => isset($params['type']) ? intval($params['type']) : 1,
  489. 'user_id' => $userId,
  490. 'title' => isset($params['title']) && $params['title'] ? trim($params['title']) : $nickname.'正在直播',
  491. 'description' => isset($params['description']) && $params['description'] ? trim($params['description']) : lang('我正在直播,快来看看吧'),
  492. 'category' => isset($params['category']) ? intval($params['category']) : 0,
  493. 'visible_type' => isset($params['visible_type']) ? intval($params['visible_type']) : 0,
  494. 'visible_users' => isset($params['visible_users']) ? trim($params['visible_users']) : '',
  495. 'chat_type' => isset($params['chat_type']) ? intval($params['chat_type']) : 0,
  496. 'chat_status' => isset($params['chat_status']) ? intval($params['chat_status']) : 1,
  497. 'pay_status' => isset($params['pay_status']) ? intval($params['pay_status']) : 1,
  498. 'open_area' => isset($params['open_area']) ? intval($params['open_area']) : 1,
  499. 'view_allow' => isset($params['view_allow']) ? intval($params['view_allow']) : 1,
  500. 'push_url' => isset($params['push_url']) ? trim($params['push_url']) : '',
  501. 'play_url' => isset($params['play_url']) ? trim($params['play_url']) : '',
  502. 'update_time'=> time(),
  503. 'status' =>1,
  504. 'mark'=>1,
  505. ];
  506. if($liveId = $this->model->where(['user_id'=> $userId,'status'=>1,'mark'=>1])->orderBy('create_time','desc')->value('id')){
  507. if(!$this->model->where(['user_id'=> $userId,'status'=>1,'mark'=>1])->update($data)){
  508. $this->error = 2042;
  509. return false;
  510. }
  511. }else{
  512. $data['create_time'] = time();
  513. $this->model->where(['user_id'=> $userId,'mark'=>1])->update(['status'=>2,'update_time'=>time()]);
  514. if(!$liveId = $this->model->insertGetId($data)){
  515. $this->error = 2042;
  516. return false;
  517. }
  518. }
  519. $data['id'] = $liveId;
  520. $data['member'] = MemberModel::where(['id'=> $userId])->select(['id','nickname','avatar','status'])->first();
  521. $data['member'] = $data['member']? $data['member'] : [];
  522. $data['member']['is_follow'] = 1;
  523. if(isset($data['member']['avatar'])){
  524. $data['member']['avatar'] = $data['member']['avatar']? $data['member']['avatar'] : '/images/member/logo.png';
  525. $data['member']['avatar'] = get_image_url($data['member']['avatar']);
  526. }
  527. $this->error = 2041;
  528. return $data;
  529. }
  530. /**
  531. * 直播打赏
  532. * @param $userId 打赏用户ID
  533. * @param $params 参数
  534. * @return bool
  535. */
  536. public function reward($userId, $params)
  537. {
  538. $liveId = isset($params['live_id'])? intval($params['live_id']) : 0;
  539. $giftId = isset($params['gift_id'])? intval($params['gift_id']) : 0;
  540. $liveInfo = $this->model->with(['member'])->where(['id'=> $liveId,'mark'=>1])
  541. ->select(['id','user_id','category','pay_status','status'])
  542. ->first();
  543. $status = isset($liveInfo['status'])? $liveInfo['status'] : 0;
  544. $payStatus = isset($liveInfo['pay_status'])? $liveInfo['pay_status'] : 0;
  545. $liveUserId = isset($liveInfo['user_id'])? $liveInfo['user_id'] : 0;
  546. $liveMember = isset($liveInfo['member'])? $liveInfo['member'] : [];
  547. $liveUserUsdt = isset($liveMember['usdt'])? $liveMember['usdt'] : 0;
  548. $bonusUserId = isset($liveMember['parent_id'])? $liveMember['parent_id'] : 0;
  549. if(empty($liveInfo) || empty($liveMember) || $status != 1){
  550. $this->error = 2301;
  551. return false;
  552. }
  553. if($payStatus!=1){
  554. $this->error = 2302;
  555. return false;
  556. }
  557. $giftInfo = LiveGiftModel::where(['id'=> $giftId,'status'=>1,'mark'=>1])
  558. ->select(['id','name','money'])
  559. ->first();
  560. $money = isset($giftInfo['money'])? intval($giftInfo['money']) : 0;
  561. if(empty($giftInfo) || $money<=0){
  562. $this->error = 2303;
  563. return false;
  564. }
  565. // 用户信息
  566. $userInfo = MemberModel::where(['id'=> $userId,'mark'=>1])
  567. ->select(['id','nickname','parent_id','point_id','balance','status'])
  568. ->first();
  569. $balance = isset($userInfo['balance'])? floatval($userInfo['balance']) : 0;
  570. if($balance < $money){
  571. $this->error = 2304;
  572. return false;
  573. }
  574. // 直播推荐人(经纪人)
  575. $bounsUserInfo = [];
  576. $bonusUserLevel = 0;
  577. if($bonusUserId){
  578. $bounsUserInfo = MemberModel::where(['id'=> $bonusUserId,'status'=>1,'mark'=>1])
  579. ->select(['id','nickname','parent_id','point_id','member_level','usdt','balance','status'])
  580. ->first();
  581. $bonusUserLevel = isset($bounsUserInfo['member_level'])? $bounsUserInfo['member_level'] : 0;
  582. }
  583. // TODO 打赏订单
  584. $orderNo = get_order_num('RW');
  585. $awardLevel = ConfigService::make()->getConfigByCode('live_award_level',5); // 推荐奖励等级
  586. $awardLevel = $awardLevel>=1 && $awardLevel<=30? $awardLevel : 5;
  587. $awardRate = ConfigService::make()->getConfigByCode('award_rewad_rate',10); // 推荐奖励比例%
  588. $awardRate = $awardRate>=0 && $awardLevel<100? $awardRate : 10;
  589. $xdPrice = ConfigService::make()->getConfigByCode('xd_price',100); // 星豆价格
  590. $xdPrice = $xdPrice>0.01 && $xdPrice <=10000? $xdPrice : 100;
  591. $usdt = moneyFormat($money/$xdPrice,2);
  592. // 推荐佣金
  593. $bonusUsdt = $awardRate? moneyFormat($usdt * $awardRate/100, 4) : 0;
  594. DB::beginTransaction();
  595. $order = [
  596. 'live_id'=> $liveId,
  597. 'user_id'=> $userId,
  598. 'live_user_id'=> $liveUserId,
  599. 'gift_id'=> $giftId,
  600. 'order_no'=> $orderNo,
  601. 'type'=> 1,
  602. 'money'=> $money,
  603. 'usdt'=> $usdt,
  604. 'bonus_rate'=> $awardRate? $awardRate : 0,
  605. 'bonus_usdt'=> $bonusUserId>0? $bonusUsdt : 0,
  606. 'bonus_uid'=> $bonusUserId,
  607. 'bonus_status'=> $bonusUserLevel >= $awardLevel? 1 : 2,
  608. 'create_time'=> time(),
  609. 'status'=> 1,
  610. 'mark'=>1
  611. ];
  612. if(!$orderId = RewardOrderModel::insertGetId($order)){
  613. DB::rollBack();
  614. $this->error = 2305;
  615. return false;
  616. }
  617. // 扣除打赏用户余额
  618. $updateData = ['balance'=>DB::raw("balance - {$money}"),'update_time'=>time()];
  619. if(!MemberModel::where(['id'=> $userId,'mark'=>1])->update($updateData)){
  620. DB::rollBack();
  621. $this->error = 2305;
  622. return false;
  623. }
  624. // 明细
  625. $log = [
  626. 'user_id'=> $userId,
  627. 'source_id'=> $liveId,
  628. 'source_order_no'=> $orderNo,
  629. 'user_type'=> 1,
  630. 'type'=>1,
  631. 'coin_type'=> 2,
  632. 'money'=> $money,
  633. 'date'=> date('Y-m-d'),
  634. 'actual_money'=> $usdt,
  635. 'balance'=> $balance,
  636. 'create_time'=> time(),
  637. 'remark'=> '礼物打赏',
  638. 'status'=> 1,
  639. 'mark'=> 1,
  640. ];
  641. if(!AccountLogModel::insertGetId($log)){
  642. DB::rollBack();
  643. $this->error = 2305;
  644. return false;
  645. }
  646. // 被打赏主播账户USDT账户进账
  647. $updateData = ['usdt'=>DB::raw("usdt + {$usdt}"),'update_time'=>time()];
  648. if(!MemberModel::where(['id'=> $liveUserId,'mark'=>1])->update($updateData)){
  649. DB::rollBack();
  650. $this->error = 2305;
  651. return false;
  652. }
  653. // 明细
  654. $log = [
  655. 'user_id'=> $liveUserId,
  656. 'source_id'=> $liveId,
  657. 'source_order_no'=> $orderNo,
  658. 'user_type'=> 1,
  659. 'type'=> 1,
  660. 'coin_type'=> 1,
  661. 'money'=> $usdt,
  662. 'date'=> date('Y-m-d'),
  663. 'actual_money'=> $usdt,
  664. 'balance'=> $liveUserUsdt,
  665. 'create_time'=> time(),
  666. 'remark'=> '礼物打赏',
  667. 'status'=> 1,
  668. 'mark'=> 1,
  669. ];
  670. if(!AccountLogModel::insertGetId($log)){
  671. DB::rollBack();
  672. $this->error = 2305;
  673. return false;
  674. }
  675. // TODO 浏览用户更新打赏统计
  676. if(!VideoCollectService::make()->getCollectCacheInfo($userId, $liveId, 1,2)){
  677. $data = [
  678. 'user_id'=> $userId,
  679. 'type'=> 1,
  680. 'source_type'=> 2,
  681. 'collect_id'=> $liveId,
  682. 'reward_total'=> $money,
  683. 'category_id'=> isset($liveInfo['category'])? $liveInfo['category'] : 0,
  684. 'collect_uid'=> isset($liveInfo['user_id'])? $liveInfo['user_id'] : 0,
  685. 'create_time'=> time(),
  686. 'status'=> 1,
  687. ];
  688. if(!VideoCollectModel::insertGetId($data)){
  689. DB::rollBack();
  690. $this->error = 2305;
  691. return false;
  692. }
  693. RedisService::set("caches:videos:collect:temp_{$userId}_{$liveId}_1_2", $data, rand(10,30));
  694. RedisService::clear("caches:videos:recommend:{$userId}_1_2");
  695. RedisService::clear("caches:member:fans:{$userId}_{$liveId}_2");
  696. RedisService::clear("caches:live:users_{$liveId}_{$userId}");
  697. }
  698. // 更新
  699. 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()])){
  700. DB::rollBack();
  701. $this->error = 2305;
  702. return false;
  703. }
  704. // TODO 直播间打赏统计
  705. $updateData = ['reward_total'=>DB::raw("reward_total + {$money}"),'update_time'=>time()];
  706. if(!$this->checkUserReward($userId, $liveId)){
  707. // 打赏人数统计
  708. $updateData['reward_num'] = DB::raw("reward_num + 1");
  709. }
  710. if(!$this->model->where(['id'=> $liveId])->update($updateData)){
  711. DB::rollBack();
  712. $this->error = 2305;
  713. return false;
  714. }
  715. // TODO 推荐奖励(等级需要超过)
  716. $dateTime = date('Y-m-d H:i:s');
  717. $liveName = isset($liveMember['nickname']) && $liveMember['nickname']? $liveMember['nickname'] : $liveUserId;
  718. $userNickname = isset($userInfo['nickname']) && $userInfo['nickname']? $userInfo['nickname'] : $userId;
  719. if($bonusUserId>0 && $bonusUserLevel >= $awardLevel && $bonusUsdt>0){
  720. // 账户变动
  721. $updateData = ['usdt'=>DB::raw("usdt + {$bonusUsdt}"),'update_time'=>time()];
  722. if(!MemberModel::where(['id'=> $bonusUserId,'mark'=>1])->update($updateData)){
  723. DB::rollBack();
  724. $this->error = 2305;
  725. return false;
  726. }
  727. // 明细
  728. $log = [
  729. 'user_id'=> $bonusUserId,
  730. 'source_id'=> $liveId,
  731. 'source_order_no'=> $orderNo,
  732. 'user_type'=> 1,
  733. 'type'=> 10,
  734. 'coin_type'=> 1,
  735. 'money'=> $usdt,
  736. 'date'=> date('Y-m-d'),
  737. 'actual_money'=> $usdt,
  738. 'balance'=> $liveUserUsdt,
  739. 'create_time'=> time(),
  740. 'remark'=> '推荐打赏奖励',
  741. 'status'=> 1,
  742. 'mark'=> 1,
  743. ];
  744. if(!AccountLogModel::insertGetId($log)){
  745. DB::rollBack();
  746. $this->error = 2305;
  747. return false;
  748. }
  749. // 消息
  750. MessageService::make()->pushMessage($userId, lang('打赏推荐奖励通知'), lang('打赏推荐奖励通知内容',['time'=> $dateTime,'usdt'=>$bonusUsdt,'live_name'=>$liveName]),3);
  751. }
  752. DB::commit();
  753. // TODO 推送站内消息
  754. MessageService::make()->pushMessage($userId, lang('打赏消费通知'), lang('打赏消费通知内容',['time'=> $dateTime,'money'=>$money,'live_name'=>$liveName]),3);
  755. MessageService::make()->pushMessage($liveUserId, lang('打赏通知'), lang('打赏通知内容',['time'=> $dateTime,'money'=>$money,'nickname'=>$userNickname]),3);
  756. $this->error = 2306;
  757. return ['id'=>$orderId];
  758. }
  759. /**
  760. * 验证是否打赏过
  761. * @param $userId 打赏用户ID
  762. * @param $liveId 直播间ID
  763. * @return array|mixed
  764. */
  765. public function checkUserReward($userId, $liveId)
  766. {
  767. $cacheKey = "caches:live:reward:{$userId}_{$liveId}";
  768. $data = RedisService::get($cacheKey);
  769. if($data || RedisService::exists($cacheKey)){
  770. return $data;
  771. }
  772. $data = RewardOrderModel::where(['user_id'=> $userId,'live_id'=> $liveId])->value('id');
  773. if($data){
  774. RedisService::set($cacheKey, $data, rand(3600, 7200));
  775. }
  776. return $data;
  777. }
  778. }