UserRepository.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. <?php
  2. /**
  3. * 描述.
  4. *
  5. * @author jim <jim458734573@gmail.com>
  6. * @date 2020-01-16 17:06:43
  7. */
  8. declare(strict_types=1);
  9. namespace App\Repositories;
  10. use App\Events\Task\BindPhoneEvent;
  11. use App\Events\Task\FillCodeEvent;
  12. use App\Events\Task\InviteFriendsEvent;
  13. use App\Events\Task\TimeTaskEvent;
  14. use App\Exception\ApiException;
  15. use App\Model\Mongo\VideoHistoryModel;
  16. use App\Model\TaskAwarkLogModel;
  17. use App\Model\UserModel;
  18. use App\Model\VipCardModel;
  19. use App\Model\VipOrderModel;
  20. use App\Repositories\Service\CommonService;
  21. use App\Repositories\Service\QueueService;
  22. use App\Repositories\Utils\M3u8CacheRepository;
  23. use App\Repositories\Utils\RandomUserInfoRepository;
  24. use Carbon\Carbon;
  25. use Hyperf\Database\Model\Builder;
  26. use Hyperf\DbConnection\Db;
  27. use KZ2\Repositories\Model\Repository;
  28. use Modules\Api\Services\AuthService;
  29. use Modules\Api\Services\UserRelationService;
  30. use Psr\SimpleCache\CacheInterface;
  31. class UserRepository extends Repository
  32. {
  33. /**
  34. * 账号凭证加密的key,单个APP写死
  35. * @var string
  36. */
  37. private $_acKey = 'SbIQUxX6hSOJ8pdb';
  38. /**
  39. * 账号凭证加密的iv,单个APP写死
  40. * @var string
  41. */
  42. private $_acIv = 'CJn2wekWF2OPUkXC';
  43. // 目前APP的用户协议名
  44. private $appUserScheme = 'user://';
  45. /**
  46. * @return Builder|mixed|string
  47. */
  48. public function model()
  49. {
  50. return UserModel::class;
  51. }
  52. /**
  53. * 随机产生昵称.
  54. * @return string
  55. */
  56. public function randGenerateNick()
  57. {
  58. return RandomUserInfoRepository::getNickname();
  59. }
  60. /**
  61. * 随机产生设备号
  62. * @return string
  63. */
  64. public function randGenerateDeviceNo()
  65. {
  66. return strtolower(random(32));
  67. }
  68. /**
  69. * app用户退出登录
  70. * @param $userId
  71. * @return bool
  72. */
  73. public function userLogout($userId)
  74. {
  75. if (!$userId) {
  76. return false;
  77. }
  78. $userInfo = $this->getUserInfoFromCache($userId);
  79. if (!$userInfo) {
  80. return false;
  81. }
  82. $cacheKey = (new AuthService)
  83. ->getUserDeviceCacheKey(
  84. $userInfo['device_no'],
  85. $userInfo['device_type']
  86. );
  87. $cache = make(CacheInterface::class);
  88. $cache->delete($cacheKey);
  89. $this->delUserCache($userId);
  90. return true;
  91. }
  92. /**
  93. * 从cache里面取用户信息 头像不建议在这里面拼接URL
  94. * @param $userId
  95. * @return array|null
  96. */
  97. public function getUserInfoFromCache($userId)
  98. {
  99. if (!$userId) {
  100. return null;
  101. }
  102. $cacheKey = 'user_info:'.$userId;
  103. //缓存时间 随机2-3小时内
  104. $cacheTime = mt_rand(7200, 10800);
  105. $result = make(CacheInterface::class)
  106. ->remember(
  107. $cacheKey,
  108. $cacheTime,
  109. function () use ($userId) {
  110. $creatorRepo = make(CreatorRepository::class);
  111. $creatorTotalCoin = $creatorTotalIncome = $creatorIncome = $creatorCoin = 0;
  112. $creatorObj = $creatorRepo->detail($userId, ['id', 'total_coin', 'total_income']);
  113. if (!empty($creatorObj)) {
  114. $creatorTotalCoin = $creatorObj->total_coin;
  115. $creatorTotalIncome = $creatorObj->total_income;
  116. }
  117. $tempData = array();
  118. $dbResult = UserModel::query()->where('code', $userId)
  119. ->first();
  120. if ($dbResult) {
  121. $dbResult = $dbResult->toArray();
  122. //去掉不必要字段
  123. if ($dbResult['status'] != 1) {
  124. return null;
  125. }
  126. // $dbResult['avatar'] = make(CommonService::class)
  127. // ->getImageUrl($dbResult['avatar']);
  128. $dbResult['birth'] = strval($dbResult['birth']);
  129. $dbResult['vip_expired'] = strval($dbResult['vip_expired']);
  130. $dbResult['is_vip'] = 'n';
  131. $now = Carbon::now();
  132. $vipExpired = Carbon::parse($dbResult['vip_expired']);
  133. if ($dbResult['vip_expired'] && $vipExpired > $now) {
  134. $dbResult['is_vip'] = 'y';
  135. }
  136. $relation = make(UserRelationService::class);
  137. $dbResult['fans'] = $relation->getTotal('fans', $userId);
  138. $dbResult['flow'] = $relation->getTotal('flow', $userId);
  139. $dbResult['like'] = $relation->getLike($userId);
  140. unset($now);
  141. unset($vipExpired);
  142. $tempData = $dbResult;
  143. $tempData['creator_total_coin'] = $creatorTotalCoin;
  144. $tempData['creator_total_income'] = $creatorTotalIncome;
  145. }
  146. return $tempData;
  147. }
  148. );
  149. return $result;
  150. }
  151. /**
  152. * 清除用户的cache信息 操作了用户 如 封禁啊、增加会员了啊什么的调用此方法
  153. * @return bool
  154. */
  155. public function delUserCache($userId)
  156. {
  157. $cacheKey = 'user_info:'.$userId;
  158. make(CacheInterface::class)->delete($cacheKey);
  159. return true;
  160. }
  161. /**
  162. * 个人中心数据
  163. * @param $userId
  164. * @return array
  165. */
  166. public function getUserInfoData($userId)
  167. {
  168. $userInfo = $this->getUserInfoFromCache($userId);
  169. if (!$userInfo) {
  170. throw new ApiException('帳號異常');
  171. }
  172. $user_count = make(VideoHistoryModel::class)->db()->countDocuments(
  173. ['uid' => $userInfo['id'], 'date' => Carbon::now()->toDateString()]
  174. );
  175. $taskLogRepo = make(TaskAwarkLogRepository::class);
  176. $result = array(
  177. 'id' => $userInfo['id'],
  178. 'code' => $userInfo['code'],
  179. 'nick' => $userInfo['nick'].'',
  180. 'coins' => $userInfo['coins'],
  181. 'avatar'=> M3u8CacheRepository::getImageUrl($userInfo['avatar']),
  182. 'intro' => $userInfo['intro'].'',
  183. 'gender'=> intval($userInfo['gender']),
  184. 'is_vip'=> $userInfo['is_vip'],
  185. 'user_vip_level' => 0, // 字段vip_level,设计目的是给裂变业绩使用,所以此处有2层含义,需要通过is_vip来判断.
  186. 'play_num_notice'=> '',
  187. 'bind_mobile' => $userInfo['mobile'] ? '+'. $userInfo['area_code'] . $userInfo['mobile'] : '', // 是否注册绑定手机号通过这个是否为空字符串判断.
  188. 'flow' => $userInfo['flow'],
  189. 'fans' => $userInfo['fans'],
  190. 'like' => $userInfo['like'],
  191. 'invite' => $userInfo['invite'],
  192. 'has_parent'=> $userInfo['parent_uid'] > 0 ? 'y' : 'n',
  193. 'parent_uid' => $userInfo['parent_uid'],
  194. 'balance' => !empty($userInfo['balance']) ? $userInfo['balance'] : 0, // 余额
  195. 'max_view' => intval($userInfo['max_view']),
  196. 'channel_code' => $userInfo['channel_id'], // 渠道号.
  197. 'creator_level' => $userInfo['creator_level'] ?? 0, // 创作者等级.
  198. );
  199. $playNumNotice = '';
  200. $userVipLevel = 0;
  201. $commentSurplus = 0; // 剩余评论数
  202. $videoSurplus = 0; // 剩余观影次数.
  203. $vipDaysSurplus = 0; // VIP剩余天数.
  204. $vipTitle = ''; // VIP套餐名称.
  205. $todayTaskVideoNum = make(TaskAwarkLogRepository::class)->coutTodayOnce($userInfo['code'], TaskAwarkLogModel::REWARD_TYPE_MOVIE_CONUT);
  206. $videoSurplus = intval($userInfo['max_view']) - $user_count + $todayTaskVideoNum;
  207. if ($videoSurplus < 0) {
  208. // 容错
  209. $videoSurplus = 0;
  210. }
  211. if ($userInfo['is_vip'] == 'y') {
  212. $userVipLevel = $userInfo['vip_level'];
  213. $vipDaysSurplus = abs(Carbon::now()->diffInDays($userInfo['vip_expired']));
  214. $videoSurplus = 999999;
  215. if ($vipDaysSurplus > (10 * 365)) {
  216. $playNumNotice = '无限观看';
  217. } else {
  218. $playNumNotice = '剩余:' . strval($vipDaysSurplus) . '天';
  219. }
  220. } else {
  221. $playNumNotice = '剩余:' . strval($vipDaysSurplus) . '天';
  222. }
  223. $result['play_num_notice'] = $playNumNotice;
  224. $result['user_vip_level'] = $userVipLevel;
  225. // 最近购买最好的VIP.
  226. if ($vipDaysSurplus > 0) {
  227. $columns = ['id', 'vip_id', 'user_code', 'vip_title'];
  228. $lastVipObj = VipOrderModel::query()->where(['user_id' => $userInfo['id'], 'status' => 1])->orderBy('id', 'DESC')->first($columns);
  229. if (!empty($lastVipObj)) {
  230. $vipTitle = $lastVipObj->vip_title;
  231. }
  232. }
  233. $result['vip_title'] = $vipTitle; // VIP套餐名称.
  234. // 当天评论次数
  235. $toDayCommentSurplus = $taskLogRepo->coutTodayOnce($userId, TaskAwarkLogModel::REWARD_TYPE_COMMENT_COUNT);
  236. //找回账号的凭证
  237. $account = $this->appUserScheme .$result['code'];
  238. $account = hand_encrypt($account, $this->_acKey, $this->_acIv);
  239. $result['account_qrcode_content'] = $account;
  240. // TODO 给前端同学补结构,后面写业务逻辑.
  241. $result['video_surplus'] = $videoSurplus; // 剩余观影次数.
  242. $result['hotel_surplus'] = $userInfo['max_open_house']; // 开房查询剩余次数. todo 已开房次数还没减
  243. $result['vip_days_surplus'] = $vipDaysSurplus; // VIP剩余天数.
  244. $result['max_comment'] = $commentSurplus + $userInfo['max_comment'] + $toDayCommentSurplus; // 每日最大评论数.
  245. $result['comment_used'] = make(CommentRepository::class)->countToday($userInfo['code']); // 今日使用过评论数.
  246. $commentSurplus = $result['max_comment'] - $result['comment_used'];
  247. if ($commentSurplus < 0) {
  248. // 容错.
  249. $commentSurplus = 0;
  250. }
  251. $result['comment_surplus'] = $commentSurplus; // 今日剩余评论数.
  252. return $result;
  253. }
  254. /**
  255. * 创建用户qr内容。
  256. * @param $uid
  257. * @return string
  258. */
  259. public function createUserQrCode($uid)
  260. {
  261. $info = $this->appUserScheme.$uid;
  262. return hand_encrypt($info, $this->_acKey, $this->_acIv);
  263. }
  264. /**
  265. * 根据账号凭证找回账号
  266. * @param string $userId 当前账号邀请码
  267. * @param string $qrCode 要找回的账号的二维码内容
  268. * @return bool
  269. */
  270. public function findByQrCode($userId, $qrCode)
  271. {
  272. //当前账号
  273. $newUserInfo = $this->getUserInfoFromCache($userId);
  274. if (!$newUserInfo) {
  275. throw new ApiException('[1]帳號異常');
  276. }
  277. $account = hand_decrypt($qrCode, $this->_acKey, $this->_acIv);
  278. if (empty($account)) {
  279. throw new ApiException('[1]无效二维码内容');
  280. }
  281. $patternTxt = str_replace('/', '\\/', $this->appUserScheme);
  282. if (!preg_match('/^('. $patternTxt .')/i', $account)) {
  283. throw new ApiException('[2]无效二维码内容');
  284. }
  285. $account = str_replace($this->appUserScheme, '', $account);
  286. $oldUserInfo = $this->getUserInfoFromCache($account);
  287. if (!$oldUserInfo) {
  288. throw new ApiException('[2]帳號異常');
  289. }
  290. if ($newUserInfo['id'] == $oldUserInfo['id']) {
  291. throw new ApiException('此身份卡为当前账号,请勿重复扫描');
  292. }
  293. Db::beginTransaction();
  294. try {
  295. //交换两个账号的device_no
  296. //把旧账号的设备号、设备类型给新账号
  297. $result1 = UserModel::query()
  298. ->where('id', $newUserInfo['id'])
  299. ->update(
  300. array(
  301. 'device_no'=>$oldUserInfo['device_no'],
  302. 'device_type'=>$oldUserInfo['device_type'],
  303. 'finger_hash'=>$oldUserInfo['finger_hash'],
  304. )
  305. );
  306. //把新账号的设备号、设备类型给旧账号
  307. $result2 = UserModel::query()->where('id', $oldUserInfo['id'])
  308. ->update(
  309. array(
  310. 'device_no'=>$newUserInfo['device_no'],
  311. 'device_type'=>$newUserInfo['device_type'],
  312. 'finger_hash'=>$newUserInfo['finger_hash'],
  313. )
  314. );
  315. if ($result1 && $result2) {
  316. Db::commit();
  317. //退出登录
  318. $this->userLogout($newUserInfo['code']);
  319. $this->userLogout($oldUserInfo['code']);
  320. return true;
  321. }
  322. } catch (\Exception $e) {
  323. var_dump($e->getMessage());
  324. }
  325. Db::rollBack();
  326. return false;
  327. }
  328. /**
  329. * 绑定手机号、手机号不存在则绑定手机号。手机号存在则为根据手机号找回账号
  330. * @param string $userId
  331. * @param string $phone
  332. * @param string $code
  333. * @return bool
  334. */
  335. public function bindPhone($userId, $phone, $type)
  336. {
  337. if (!$userId || !$phone) {
  338. throw new ApiException('參數錯誤');
  339. }
  340. $userInfo = $this->getUserInfoFromCache($userId);
  341. if (!$userInfo) {
  342. throw new ApiException('帳號異常');
  343. }
  344. //处理逻辑
  345. $mobileUser = make(UserModel::class)
  346. ->where('area_code', '=', 86)
  347. ->where('mobile', '=', $phone)
  348. ->first();
  349. if ($type == 2 && $mobileUser) {
  350. throw new ApiException('该手机号已经绑定');
  351. }
  352. if ($type == 1) {
  353. if (empty($mobileUser)) {
  354. throw new ApiException('账号不存在,请确认你的手机号是否正确');
  355. }
  356. //手机号存在,实际逻辑为找回账号、交换两个用户的设备号信息
  357. $mobileUser = $mobileUser->toArray();
  358. Db::beginTransaction();
  359. try {
  360. //交换两个账号的device_no
  361. //把手机号账号的设备号、设备类型给当前账号
  362. $result1 = UserModel::query()->where('id', $userInfo['id'])
  363. ->update(
  364. array(
  365. 'device_no'=>$mobileUser['device_no'],
  366. 'device_type'=>$mobileUser['device_type'],
  367. 'finger_hash'=>$mobileUser['finger_hash'],
  368. )
  369. );
  370. //把当前账号的设备号、设备类型给手机号账号
  371. $result2 = UserModel::where('id', $mobileUser['id'])
  372. ->update(
  373. array(
  374. 'device_no'=>$userInfo['device_no'],
  375. 'device_type'=>$userInfo['device_type'],
  376. 'finger_hash'=>$userInfo['finger_hash'],
  377. )
  378. );
  379. if ($result1 && $result2) {
  380. Db::commit();
  381. //退出登录
  382. $this->userLogout($userInfo['code']);
  383. $this->userLogout($mobileUser['code']);
  384. return true;
  385. }
  386. } catch (\Exception $e) {
  387. }
  388. Db::rollBack();
  389. return false;
  390. } else {
  391. //手机号不存在、直接绑定手机号
  392. UserModel::query()->where('id', $userInfo['id'])->update(
  393. array(
  394. 'mobile'=>$phone,
  395. )
  396. );
  397. //绑定手机号
  398. dispatch_event(new BindPhoneEvent(['user_id' => $userInfo['code']]));
  399. $this->userLogout($userInfo['code']);
  400. return true;
  401. }
  402. }
  403. /**
  404. * 更新用户基本信息
  405. * @param $userId
  406. * @param $data
  407. */
  408. public function updateUserData($userId, $data)
  409. {
  410. if (!$userId || !$data) {
  411. throw new ApiException('參數錯誤');
  412. }
  413. $userInfo = $this->getUserInfoFromCache($userId);
  414. if (!$userInfo) {
  415. throw new ApiException('帳號異常');
  416. }
  417. $commonService = make(CommonService::class);
  418. $updateData = array();
  419. if (isset($data['nick'])) {
  420. $data['nick'] = $commonService->filterString($data['nick']);
  421. $tempLen = mb_strlen($data['nick'], 'utf-8');
  422. if ($tempLen > 9) {
  423. throw new ApiException('暱稱最長10個字符');
  424. }
  425. $updateData['nick'] = $data['nick'];
  426. }
  427. if (isset($data['avatar'])) {
  428. $tempLen = strpos($data['avatar'], 'ceb');
  429. if (!$tempLen) {
  430. throw new ApiException('頭像地址錯誤');
  431. }
  432. $updateData['avatar'] = $data['avatar'];
  433. }
  434. if (isset($data['intro'])) {
  435. $data['intro'] = $commonService->filterString($data['intro']);
  436. $tempLen = mb_strlen($data['intro'], 'utf-8');
  437. if ($tempLen > 199) {
  438. throw new ApiException('簡介最長200個字符');
  439. }
  440. $updateData['intro'] = $data['intro'];
  441. }
  442. if (isset($data['gender'])) {
  443. $genderArr = array(0,1,2,3);
  444. if (!in_array($data['gender'], $genderArr)) {
  445. throw new ApiException('性別錯誤');
  446. }
  447. $updateData['gender'] = $data['gender'];
  448. }
  449. if (isset($data['birth'])) {
  450. $updateData['birth'] = $data['birth'];
  451. }
  452. if (isset($data['live_code'])) {
  453. $updateData['live_code'] = $data['live_code'];
  454. }
  455. if (empty($updateData)) {
  456. throw new ApiException('無更新');
  457. }
  458. UserModel::query()->where('id', $userInfo['id'])->update($updateData);
  459. $this->delUserCache($userId);
  460. return true;
  461. }
  462. /**
  463. * 绑定邀请码
  464. * @param string $userId
  465. * @param string $parentCode
  466. */
  467. public function bindCode($userId, $parentCode)
  468. {
  469. if (!$userId || !$parentCode || $userId == $parentCode) {
  470. throw new ApiException('參數錯誤');
  471. }
  472. $userInfo = $this->getUserInfoFromCache($userId);
  473. $parentUser = $this->getUserInfoFromCache($parentCode);
  474. if (!$userInfo) {
  475. throw new ApiException('帳號異常');
  476. }
  477. if (!$parentUser) {
  478. throw new ApiException('邀請碼不存在');
  479. }
  480. //已绑定
  481. if ($userInfo['parent_uid']) {
  482. throw new ApiException('已綁定');
  483. }
  484. //互相推荐的情况
  485. if ($parentUser['parent_uid'] == $userInfo['code']) {
  486. throw new ApiException('綁定異常');
  487. }
  488. UserModel::query()->where('id', $userInfo['id'])
  489. ->update(
  490. array(
  491. 'parent_uid'=>$parentUser['code'],
  492. )
  493. );
  494. //会员裂变关系逻辑 丢队列异步执行
  495. make(QueueService::class)->createUserRelationJob(['invite_id' => $parentUser['code'], 'invited_id' => $userInfo['code']]);
  496. // 绑定邀请码任务
  497. dispatch_event(new FillCodeEvent(['user_id' => $userInfo['code']]));
  498. // 邀请好友任务
  499. dispatch_event(new InviteFriendsEvent(['user_id' => $parentUser['code']]));
  500. // 限时任务队列
  501. make(QueueService::class)->timeTaskSendRewardJob(['user_id' => $parentUser['code']], 5);
  502. $this->delUserCache($userId);
  503. $this->delUserCache($parentCode);
  504. return true;
  505. }
  506. /**
  507. * 解绑手机号
  508. * @param string $userId
  509. * @param string $phone
  510. * @param string $code
  511. * @return bool
  512. */
  513. public function unbindPhone($userId, $phone)
  514. {
  515. if (!$userId || !$phone) {
  516. throw new ApiException('參數錯誤');
  517. }
  518. $userInfo = $this->getUserInfoFromCache($userId);
  519. if (!$userInfo) {
  520. throw new ApiException('帳號異常');
  521. }
  522. //处理逻辑
  523. $mobileUser = make(UserModel::class)
  524. ->where('area_code', '=', 86)
  525. ->where('mobile', '=', $phone)
  526. ->first();
  527. if ($mobileUser) {
  528. if ($mobileUser->mobile != $phone) {
  529. throw new ApiException('帳號異常');
  530. }
  531. $mobileUser->mobile = '';
  532. //手机号存在,实际逻辑为找回账号、交换两个用户的设备号信息
  533. $mobileUser = $mobileUser->toArray();
  534. Db::beginTransaction();
  535. try {
  536. $mobileUser->save();
  537. Db::commit();
  538. } catch (\Exception $e) {
  539. }
  540. Db::rollBack();
  541. return false;
  542. } else {
  543. throw new ApiException('帳號異常');
  544. }
  545. }
  546. /**
  547. * 获取aes-key
  548. * @return string
  549. */
  550. public function getAcKey()
  551. {
  552. return $this->_acKey;
  553. }
  554. /**
  555. * 获取aes-iv
  556. * @return string
  557. */
  558. public function getAcIv()
  559. {
  560. return $this->_acIv;
  561. }
  562. /**
  563. * 获取系统头像
  564. * @return mixed
  565. */
  566. public function getSysAvatars()
  567. {
  568. $cacheRepo = make(CacheInterface::class);
  569. $cacheKey = 'user:sys_avatars';
  570. $arrData = $cacheRepo->rememberForever($cacheKey, function () {
  571. $arrData = [];
  572. $filePrefix = 'f2|/'. env('STATIC_DIR_NAME', 'doukui') . '/avatars/a_';
  573. $maxNum = 11;
  574. for ($i = 1; $i <= $maxNum; $i++) {
  575. $tmpNum = str_pad(strval($i), 3, '0', STR_PAD_LEFT);
  576. $groupUrl = $filePrefix . $tmpNum . '.ceb';
  577. $arrData[] = $groupUrl;
  578. }
  579. return $arrData;
  580. });
  581. return $arrData;
  582. }
  583. }