PostRepositories.php 19 KB

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