PostRepositories.php 20 KB

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