PostRepositories.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: edz
  5. * Date: 2019-06-10
  6. * Time: 17:53
  7. */
  8. namespace App\Repositories;
  9. use App\Models\Behavior;
  10. use App\Models\Post;
  11. use App\Models\PostCollect;
  12. use App\Models\PostComment;
  13. use App\Models\PostData;
  14. use App\Models\PostDislike;
  15. use App\Models\PostImgs;
  16. use App\Models\PostLike;
  17. use App\Models\PostShare;
  18. use App\Models\Topic;
  19. use App\Service\AliYunVodService;
  20. use App\Service\DetectionService;
  21. use App\Traits\CmsTrait;
  22. use App\Traits\PostTrait;
  23. use App\Traits\UserTrait;
  24. use Illuminate\Database\QueryException;
  25. use Illuminate\Support\Carbon;
  26. use Illuminate\Support\Facades\Log;
  27. use Illuminate\Support\Facades\Redis;
  28. use Illuminate\Support\Facades\DB;
  29. use Tymon\JWTAuth\Facades\JWTAuth;
  30. class PostRepositories
  31. {
  32. use UserTrait;
  33. use PostTrait;
  34. use CmsTrait;
  35. public function __construct(Post $post,
  36. PostData $postData,
  37. PostImgs $postImgs,
  38. PostComment $postComment,
  39. PostCollect $postCollect,
  40. PostShare $postShare,
  41. DetectionService $detectionService,
  42. AliYunVodService $aliYunVodService,
  43. Topic $topic)
  44. {
  45. $this->post = $post;
  46. $this->postData = $postData;
  47. $this->postImgs = $postImgs;
  48. $this->postComment = $postComment;
  49. $this->postCollect = $postCollect;
  50. $this->postShare = $postShare;
  51. $this->detectionService = $detectionService;
  52. $this->topic = $topic;
  53. $this->aliYunVodService = $aliYunVodService;
  54. }
  55. /**
  56. * 发布内容
  57. */
  58. public function create($request)
  59. {
  60. //验证小号
  61. $userInfo = $this->getUserInfo();
  62. if (empty($userInfo)) {
  63. return jsonError('获取用户信息失败');
  64. }
  65. if(!$userInfo['sns_status']){
  66. return jsonError('您已被禁言');
  67. }
  68. $isValid = 0;
  69. if($userInfo['strength']){
  70. $isValid = 1;
  71. }
  72. // $oneHourTime = Carbon::now()->addHours(-1)->toDateTimeString();
  73. // $oneHourPostCount = $this->post->where('uid', $userInfo['uid'])->where('created_at', '>', $oneHourTime)->count();
  74. // if($oneHourPostCount > 5){
  75. // return jsonError('创作欲望太强啦,休息一下,看看其他用户的内容吧!');
  76. // }
  77. $detectionText = $request['title'] .','. $request['content'];
  78. $detectionTextResult = $this->detectionService->checkText($detectionText);
  79. if ($detectionTextResult['code']<0) {
  80. return jsonError('内容违规,请修正哦');
  81. }
  82. $topicIds = json_decode($request['topic_ids'], true);
  83. $topicCount = count($topicIds);
  84. if($topicCount == 0 || $topicCount > 5){
  85. return jsonError('所选话题必须1-5个');
  86. }
  87. //验证话题
  88. $hasTopicCount = $this->topic->whereIn('id', $topicIds)->count();
  89. if($topicCount != $hasTopicCount){
  90. Log::error('所选话题非法'.$request['topic_ids']);
  91. return jsonError('所选话题非法');
  92. }
  93. $imgs = [];
  94. if($request['type'] == 'image'){
  95. $imgs = json_decode($request['imgs'], true);
  96. $imgCount = count($imgs);
  97. if($imgCount == 0 || $imgCount > 9){
  98. return jsonError('所传图集必须1-9个');
  99. }
  100. }
  101. $allImg = array_merge($imgs, [$request['img']]);
  102. $detectionImageResult = $this->detectionService->checkImg($allImg);
  103. if ($detectionImageResult['code']<0) {
  104. return jsonError('图片违规,请修正哦');
  105. }
  106. $videoUrl = "";
  107. $videoId = "";
  108. if(isset($request['video']) && $request['video']){
  109. $videoId = $request['video'];
  110. for($i=0;$i<3;$i++){
  111. $videoUrl = $this->aliYunVodService->getPlayUrlByVideoId($request['video']);
  112. Log::debug('video-url:'.$videoUrl);
  113. if($videoUrl){
  114. break;
  115. }
  116. }
  117. if(empty($videoUrl)){
  118. return jsonError('发布失败,请重试');
  119. }
  120. }
  121. $data = [
  122. 'uid' => $userInfo['uid'],
  123. 'username' => $userInfo['username'],
  124. 'mobile' => $userInfo['mobile'],
  125. 'avatar' => $userInfo['avatar']??'',
  126. 'type' => $request['type'],
  127. 'img' => $request['img'],
  128. 'video' => $videoUrl,
  129. 'video_id' => $videoId,
  130. 'topic_ids' => implode(',', $topicIds),
  131. 'title' => isset($request['title'])? $request['title'] : '',
  132. 'content' => $request['content'],
  133. 'location' => isset($request['location'])? $request['location'] : '',
  134. 'is_suggest' => 0,
  135. 'is_hide' => 0
  136. ];
  137. $date = date('Y-m-d H:i:s');
  138. $fresh = (Carbon::now()->timestamp) - (Carbon::parse("2019-05-01 00:00:00")->timestamp);
  139. $score = $fresh / 86400;
  140. DB::beginTransaction();
  141. try{
  142. $post = $this->post->create($data);
  143. $postData = $this->postData->create([
  144. 'post_id' => $post->id,
  145. 'pv' => 0,
  146. 'pv_real' => 0,
  147. 'dislike_count' => 0,
  148. 'praise_count' => 0,
  149. 'praise_real_count' => 0,
  150. 'share_count' => 0,
  151. 'share_real_count' => 0,
  152. 'comment_count' => 0,
  153. 'collect_count' => 0,
  154. 'collect_real_count' => 0,
  155. 'available_bean' => $this->availableBean(),
  156. 'will_collect_bean' => rand(100, 200),
  157. 'collect_bean' => 0,
  158. 'weight' => $score
  159. ]);
  160. if($imgs){
  161. $imgData = [];
  162. foreach($imgs as $img){
  163. $imgData[] = [
  164. 'post_id' => $post->id,
  165. 'img' => $img,
  166. 'created_at' => $date,
  167. 'updated_at' => $date
  168. ];
  169. }
  170. $this->postImgs->insert($imgData);
  171. }
  172. DB::commit();
  173. Redis::zadd('post_trigger_type', $isValid, $post->id);
  174. foreach($topicIds as $id){
  175. Redis::zincrby('topic.user_uid'.$userInfo['uid'], 1, $id);
  176. }
  177. return jsonSuccess([
  178. 'post_id' => $post->id,
  179. 'h5url' => config('customer.share_post_h5url')."?post_id={$post->id}&invite_code={$userInfo['invite_code']}",
  180. 'bean' => $postData->available_bean,
  181. ]);
  182. }catch (QueryException $exception){
  183. DB::rollBack();
  184. Log::debug('发布内容失败:'.$exception->getMessage());
  185. return jsonError('发布内容失败,请重试');
  186. }
  187. }
  188. /**
  189. * 评论&回复
  190. */
  191. public function comment($request)
  192. {
  193. //验证小号
  194. $userInfo = $this->getUserInfo();
  195. if (empty($userInfo)) {
  196. return jsonError('获取用户信息失败');
  197. }
  198. if(!$userInfo['sns_status']){
  199. return jsonError('您已被禁言');
  200. }
  201. $oneHourTime = Carbon::now()->addHours(-1)->toDateTimeString();
  202. $oneHourCommentCount = $this->postComment->where('uid', $userInfo['uid'])->where('created_at', '>', $oneHourTime)->count();
  203. if($oneHourCommentCount > 59){
  204. return jsonError('回复了这么多,休息休息,喝口水吧!');
  205. }
  206. $detectionTextResult = $this->detectionService->checkText($request['content']);
  207. if ($detectionTextResult['code']<0) {
  208. return jsonError('内容违规,请修正哦');
  209. }
  210. $post = $this->post->find($request['post_id']);
  211. if(!$post){
  212. return jsonError('获取内容信息失败');
  213. }
  214. $data = [
  215. 'uid' => $userInfo['uid'],
  216. 'post_id' => $request['post_id'],
  217. 'parent_id' => 0,
  218. 'username' => $userInfo['username'],
  219. 'reply_uid' => 0,
  220. 'reply_username' => '',
  221. 'avatar' => $userInfo['avatar']??'',
  222. 'content' => $request['content'],
  223. 'is_delete' => 0,
  224. ];
  225. if(isset($request['parent_id']) && $request['parent_id'] != 0){
  226. $comment = $this->postComment->find($request['parent_id']);
  227. if(!$comment || $comment->post_id != $post->id){
  228. return jsonError('获取评论信息失败');
  229. }
  230. if($comment->parent_id){
  231. return jsonError('只能回复评论');
  232. }
  233. $data['parent_id'] = $request['parent_id'];
  234. if(isset($request['reply_uid']) && isset($request['reply_username'])){
  235. $data['reply_uid'] = $request['reply_uid'];
  236. $data['reply_username'] = $request['reply_username'];
  237. }else{
  238. $data['reply_uid'] = 0;
  239. $data['reply_username'] = '';
  240. }
  241. }
  242. DB::beginTransaction();
  243. try{
  244. $comment = $this->postComment->create($data);
  245. DB::commit();
  246. return jsonSuccess(['id' => $comment->id], '评论成功');
  247. }catch (QueryException $exception){
  248. DB::rollBack();
  249. Log::debug('评论内容失败:'.$exception->getMessage());
  250. return jsonError('评论内容失败,请重试');
  251. }
  252. }
  253. /**
  254. * 内容列表
  255. */
  256. public function lists($request)
  257. {
  258. $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
  259. return $this->post
  260. ->join('post_data', 'post_data.post_id', '=', 'post.id')
  261. ->select('post.*')
  262. ->where(function($query) use ($request){
  263. if(isset($request['keyword'])){
  264. $query->where('title', 'like', "%{$request['keyword']}%")
  265. ->orWhere('content', 'like', "%{$request['keyword']}%");
  266. }
  267. })
  268. ->where(function($query) use ($request){
  269. if(isset($request['topic_ids']) && $request['topic_ids']){
  270. $topicIds = json_decode($request['topic_ids'], true);
  271. foreach ($topicIds as $key=>$id) {
  272. if ($key==0) {
  273. $query->whereRaw('FIND_IN_SET('.$id.', post.topic_ids)');
  274. } else {
  275. $query->orWhereRaw('FIND_IN_SET('.$id.', post.topic_ids)');
  276. }
  277. }
  278. }
  279. })
  280. ->orderBy('weight','desc')
  281. ->paginate($perPage);
  282. }
  283. /**
  284. * 视频列表
  285. */
  286. public function video($request)
  287. {
  288. $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
  289. $where = [];
  290. $id = 0;
  291. if(isset($request['id'])){
  292. $id = $request['id'];
  293. }
  294. $where[] = ['type', 'video'];
  295. if(isset($request['type'])){
  296. if($request['type'] == 'hot'){
  297. $ids = Redis::get('hotVideoIds');
  298. if(!$ids){
  299. $ids = $this->hotVideoIds();
  300. if(!$ids){
  301. $ids = '';
  302. }
  303. }
  304. Log::debug('热门视频ids'.$ids);
  305. return $this->post
  306. ->join('post_data', 'post_data.post_id', '=', 'post.id')
  307. ->select('post.*', DB::raw("IF (post.id = {$id},1,0) as sort"))
  308. ->where($where)
  309. ->whereIn('post.id', explode(',', $ids))
  310. ->orderBy('sort', 'desc')
  311. ->orderByRaw(DB::raw("FIELD(post.id,{$ids})"))
  312. ->paginate($perPage);
  313. }elseif($request['type'] == 'one'){
  314. $where[] = ['post.id', $id];
  315. return $this->post
  316. ->join('post_data', 'post_data.post_id', '=', 'post.id')
  317. ->select('post.*')
  318. ->where($where)
  319. ->paginate($perPage);
  320. }
  321. }
  322. return $this->post
  323. ->join('post_data', 'post_data.post_id', '=', 'post.id')
  324. ->select('post.*', DB::raw("IF (post.id = {$id},1,0) as sort"))
  325. ->where($where)
  326. ->orderBy('sort', 'desc')
  327. ->orderBy('weight','desc')
  328. ->paginate($perPage);
  329. }
  330. /**
  331. * 个人中心内容列表
  332. */
  333. public function MyPost($request, $uid)
  334. {
  335. $type = $request['type'];
  336. $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
  337. $where = [];
  338. if($type == 'create'){
  339. $where[] = ['post.uid', $uid];
  340. $post = $this->post;
  341. $order = 'post.id';
  342. }elseif($type == 'collect'){
  343. $post = $this->post->join('post_collect', 'post_collect.post_id', '=', 'post.id');
  344. $where[] = ['post_collect.uid', $uid];
  345. $order = 'post_collect.id';
  346. }else{
  347. $post = $this->post->join('post_share', 'post_share.post_id', '=', 'post.id');
  348. $where[] = ['post_share.uid', $uid];
  349. $order = 'post_share.updated_at';
  350. }
  351. return $post
  352. ->join('post_data', 'post_data.post_id', '=', 'post.id')
  353. ->select('post.*')
  354. ->where($where)
  355. ->orderBy($order,'desc')
  356. ->paginate($perPage);
  357. }
  358. /**
  359. * 内容详情
  360. */
  361. public function detail($id)
  362. {
  363. return $this->post
  364. ->join('post_data', 'post_data.post_id', '=', 'post.id')
  365. ->select('post.*')
  366. ->find($id);
  367. }
  368. /**
  369. * 内容是否存在
  370. */
  371. public function detailExists($id)
  372. {
  373. return $this->post->where('id', $id)->exists();
  374. }
  375. /**
  376. * 推荐内容列表
  377. */
  378. public function suggestPost($request)
  379. {
  380. $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
  381. return $this->post
  382. ->join('post_data', 'post_data.post_id', '=', 'post.id')
  383. ->select('post.*')
  384. ->orderBy('weight','desc')
  385. ->paginate($perPage);
  386. }
  387. /**
  388. * 话题内容
  389. */
  390. public function topicPost($request)
  391. {
  392. $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
  393. return $this->post
  394. ->join('post_data', 'post_data.post_id', '=', 'post.id')
  395. ->select('post.*')
  396. ->whereRaw('FIND_IN_SET(' . $request['id'] . ',post.topic_ids)')
  397. ->orderBy('id','desc')
  398. ->paginate($perPage);
  399. }
  400. /**
  401. * 评论列表
  402. */
  403. public function commentList($request)
  404. {
  405. $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
  406. return $this->postComment
  407. ->where('post_id', $request['post_id'])
  408. ->where('parent_id', 0)
  409. ->orderBy('id','desc')
  410. ->paginate($perPage);
  411. }
  412. /**
  413. * 回复列表
  414. */
  415. public function replyList($request)
  416. {
  417. $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
  418. return $this->postComment
  419. ->where('parent_id', $request['id'])
  420. ->orderBy('id','desc')
  421. ->paginate($perPage);
  422. }
  423. /**
  424. * 话题列表
  425. */
  426. public function topicList($request)
  427. {
  428. $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
  429. $where = [];
  430. if(isset($request['category_id'])){
  431. $topic = $this->topic->join('category_topic', 'category_topic.topic_id', '=', 'topic.id')->select('topic.*');
  432. $where[] = ['category_topic.category_id', $request['category_id']];
  433. }else{
  434. $topic = $this->topic;
  435. }
  436. if(isset($request['is_suggest'])){
  437. $where[] = ['topic.is_hot', $request['is_suggest']];
  438. }
  439. if(isset($request['name'])){
  440. $where[] = ['topic.name', 'like', "%{$request['name']}%"];
  441. }
  442. return $topic
  443. ->where($where)
  444. ->orderBy('id','desc')
  445. ->paginate($perPage);
  446. }
  447. /**
  448. * 更新帖子统计数量
  449. * @param $request
  450. * @return mixed
  451. */
  452. public function updatePostData($request)
  453. {
  454. $postId = isset($request['post_id'])?$request['post_id']:0;
  455. if(empty($postId)){
  456. Log::debug("非帖子类操作,不操作帖子统计数量".json_encode($request));
  457. return true;
  458. }
  459. $post = PostData::where('post_id', $postId)->first();
  460. if (isset($request['behavior_flag']) && $request['behavior_flag'] == 'read') {
  461. $post->pv += 1;
  462. $post->pv_real += 1;
  463. Log::debug("帖子:".$postId."被阅读,pv +1");
  464. } elseif (isset($request['behavior_flag']) && $request['behavior_flag'] == 'unlike') {
  465. $post->dislike_count += 1;
  466. PostDislike::create(['uid'=>$request['target_id'],'post_id'=>$request['post_id']]);
  467. Log::debug("帖子:".$postId."被不喜欢,unlike +1");
  468. } elseif (isset($request['behavior_flag']) && $request['behavior_flag'] == 'like') {
  469. if($request['behavior_value']){
  470. $post->praise_count += 1;
  471. $post->praise_real_count += 1;
  472. PostLike::create(['uid'=>$request['target_id'],'post_id'=>$request['post_id']]);
  473. Log::debug("帖子:".$postId."被点赞,praise_count +1");
  474. }else{
  475. $post->praise_count -= 1;
  476. $post->praise_real_count -= 1;
  477. PostLike::where(['uid'=>$request['target_id'],'post_id'=>$request['post_id']])->delete();
  478. Log::debug("帖子:".$postId."被取消点赞,praise_count -1");
  479. }
  480. } elseif (isset($request['behavior_flag']) && $request['behavior_flag'] == 'forward') {
  481. $post->share_count += 1;
  482. $post->share_real_count += 1;
  483. $shareRow = PostShare::where(['uid'=>$request['target_id'],'post_id'=>$request['post_id']])->first();
  484. if($shareRow){
  485. PostShare::where(['uid'=>$request['target_id'],'post_id'=>$request['post_id']])->update(['uid'=>$request['target_id'],'post_id'=>$request['post_id']]);
  486. }else{
  487. PostShare::create(['uid'=>$request['target_id'],'post_id'=>$request['post_id']]);
  488. }
  489. Log::debug("帖子:".$postId."被分享,share_count +1");
  490. } elseif (isset($request['behavior_flag']) && $request['behavior_flag'] == 'comment') {
  491. $post->comment_count += 1;
  492. Log::debug("帖子:".$postId."被评论,comment_count +1");
  493. } elseif (isset($request['behavior_flag']) && $request['behavior_flag'] == 'collect') {
  494. if($request['behavior_value']) {
  495. $post->collect_count += 1;
  496. $post->collect_real_count += 1;
  497. PostCollect::create(['uid'=>$request['target_id'],'post_id'=>$request['post_id']]);
  498. Log::debug("帖子:".$postId."被收藏,collect_count +1");
  499. }else{
  500. $post->collect_count -= 1;
  501. $post->collect_real_count -= 1;
  502. PostCollect::where(['uid'=>$request['target_id'],'post_id'=>$request['post_id']])->delete();
  503. Log::debug("帖子:".$postId."被取消收藏,collect_count -1");
  504. }
  505. }
  506. $this->collectPostId($request['post_id']);
  507. return $post->save();
  508. }
  509. /**
  510. * 收集所有有操作的帖子,存入redis
  511. * 供后续计算帖子权重
  512. * @param $id
  513. */
  514. public function collectPostId($id)
  515. {
  516. $key = "community_calc_post_score";
  517. Redis::sadd($key,$id);
  518. Log::debug('存入帖子'.$id.'到权重列表');
  519. }
  520. /**
  521. * 话题详情
  522. */
  523. public function topicDetail($id)
  524. {
  525. return $this->topic
  526. ->find($id);
  527. }
  528. /**
  529. * 获取话题
  530. */
  531. public function getTopic($ids)
  532. {
  533. $topics = $this->topic
  534. ->whereIn('id', explode(',',$ids))
  535. ->orderByRaw(DB::raw("FIELD(id,{$ids})"))
  536. ->get();
  537. $data = [];
  538. foreach($topics as $topic){
  539. $data[] = [
  540. 'id' => $topic->id,
  541. 'name' => $topic->name,
  542. 'img' => $topic->img,
  543. 'follow_count' => getNumber($topic->follow->count() + config('customer.add_topic_follow_count')),
  544. ];
  545. }
  546. return $data;
  547. }
  548. /**
  549. * 获取内容视频组
  550. */
  551. public function getPostVideo($ids)
  552. {
  553. return $this->post
  554. ->select('id', 'img', 'uid', 'username', 'avatar')
  555. ->whereIn('id', explode(',',$ids))
  556. ->where('type', 'video')
  557. ->get();
  558. }
  559. //用户内容数,转发数,收藏数统计
  560. public function memberPostStatistics($uid){
  561. $postCount = $this->post->where('uid',$uid)->count();
  562. $postCollectCount = $this->postCollect->where('uid',$uid)->count();
  563. $postShareCount = $this->postShare->where('uid',$uid)->count();
  564. $data = ['post_count'=>$postCount,'share_count'=>$postShareCount,'collect_count'=>$postCollectCount];
  565. return jsonSuccess($data);
  566. }
  567. }