PostRepositories.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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($type, $uid)
  278. {
  279. $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
  280. $where = [];
  281. if($type == 'create'){
  282. $where[] = ['post.uid', $uid];
  283. $post = $this->post;
  284. $order = 'post.id';
  285. }elseif($type == 'collect'){
  286. $post = $this->post->join('post_collect', 'post_collect.post_id', '=', 'post.id');
  287. $where[] = ['post_collect.uid', $uid];
  288. $order = 'post_collect.id';
  289. }else{
  290. $post = $this->post->join('post_share', 'post_share.post_id', '=', 'post.id');
  291. $where[] = ['post_share.uid', $uid];
  292. $order = 'post_share.updated_at';
  293. }
  294. return $post
  295. ->join('post_data', 'post_data.post_id', '=', 'post.id')
  296. ->select('post.*')
  297. ->where($where)
  298. ->orderBy($order,'desc')
  299. ->paginate($perPage);
  300. }
  301. /**
  302. * 内容详情
  303. */
  304. public function detail($id)
  305. {
  306. return $this->post
  307. ->join('post_data', 'post_data.post_id', '=', 'post.id')
  308. ->select('post.*')
  309. ->find($id);
  310. }
  311. /**
  312. * 推荐内容列表
  313. */
  314. public function suggestPost($request)
  315. {
  316. $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
  317. return $this->post
  318. ->join('post_data', 'post_data.post_id', '=', 'post.id')
  319. ->select('post.*')
  320. ->orderBy('weight','desc')
  321. ->paginate($perPage);
  322. }
  323. /**
  324. * 话题内容
  325. */
  326. public function topicPost($request)
  327. {
  328. $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
  329. return $this->post
  330. ->join('post_data', 'post_data.post_id', '=', 'post.id')
  331. ->select('post.*')
  332. ->whereRaw('FIND_IN_SET(' . $request['id'] . ',post.topic_ids)')
  333. ->orderBy('id','desc')
  334. ->paginate($perPage);
  335. }
  336. /**
  337. * 评论列表
  338. */
  339. public function commentList($request)
  340. {
  341. $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
  342. return $this->postComment
  343. ->where('post_id', $request['post_id'])
  344. ->where('parent_id', 0)
  345. ->orderBy('id','desc')
  346. ->paginate($perPage);
  347. }
  348. /**
  349. * 回复列表
  350. */
  351. public function replyList($request)
  352. {
  353. $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
  354. return $this->postComment
  355. ->where('parent_id', $request['id'])
  356. ->orderBy('id','desc')
  357. ->paginate($perPage);
  358. }
  359. /**
  360. * 话题列表
  361. */
  362. public function topicList($request)
  363. {
  364. $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
  365. $where = [];
  366. if(isset($request['category_id'])){
  367. $topic = $this->topic->join('category_topic', 'category_topic.topic_id', '=', 'topic.id')->select('topic.*');
  368. $where[] = ['category_topic.category_id', $request['category_id']];
  369. }else{
  370. $topic = $this->topic;
  371. }
  372. if(isset($request['is_suggest'])){
  373. $where[] = ['topic.is_suggest', $request['is_suggest']];
  374. }
  375. if(isset($request['name'])){
  376. $where[] = ['topic.name', 'like', "%{$request['name']}%"];
  377. }
  378. return $topic
  379. ->where($where)
  380. ->orderBy('id','desc')
  381. ->paginate($perPage);
  382. }
  383. /**
  384. * 更新帖子统计数量
  385. * @param $request
  386. * @return mixed
  387. */
  388. public function updatePostData($request)
  389. {
  390. $postId = isset($request['post_id'])?$request['post_id']:0;
  391. if(empty($postId)){
  392. Log::debug("非帖子类操作,不操作帖子统计数量".json_encode($request));
  393. return true;
  394. }
  395. $post = PostData::where('post_id', $postId)->first();
  396. if (isset($request['behavior_flag']) && $request['behavior_flag'] == 'read') {
  397. $post->pv += 1;
  398. $post->pv_real += 1;
  399. Log::debug("帖子:".$postId."被阅读,pv +1");
  400. } elseif (isset($request['behavior_flag']) && $request['behavior_flag'] == 'unlike') {
  401. $post->dislike_count += 1;
  402. PostDislike::create(['uid'=>$request['target_id'],'post_id'=>$request['post_id']]);
  403. Log::debug("帖子:".$postId."被不喜欢,unlike +1");
  404. } elseif (isset($request['behavior_flag']) && $request['behavior_flag'] == 'like') {
  405. if($request['behavior_value']){
  406. $post->praise_count += 1;
  407. $post->praise_real_count += 1;
  408. PostLike::create(['uid'=>$request['target_id'],'post_id'=>$request['post_id']]);
  409. Log::debug("帖子:".$postId."被点赞,praise_count +1");
  410. }else{
  411. $post->praise_count -= 1;
  412. $post->praise_real_count -= 1;
  413. PostLike::where(['uid'=>$request['target_id'],'post_id'=>$request['post_id']])->delete();
  414. Log::debug("帖子:".$postId."被取消点赞,praise_count -1");
  415. }
  416. } elseif (isset($request['behavior_flag']) && $request['behavior_flag'] == 'forward') {
  417. $post->share_count += 1;
  418. $post->share_real_count += 1;
  419. $shareRow = PostShare::where(['uid'=>$request['target_id'],'post_id'=>$request['post_id']])->first();
  420. if($shareRow){
  421. PostShare::where(['uid'=>$request['target_id'],'post_id'=>$request['post_id']])->update(['uid'=>$request['target_id'],'post_id'=>$request['post_id']]);
  422. }else{
  423. PostShare::create(['uid'=>$request['target_id'],'post_id'=>$request['post_id']]);
  424. }
  425. Log::debug("帖子:".$postId."被分享,share_count +1");
  426. } elseif (isset($request['behavior_flag']) && $request['behavior_flag'] == 'comment') {
  427. $post->comment_count += 1;
  428. Log::debug("帖子:".$postId."被评论,comment_count +1");
  429. } elseif (isset($request['behavior_flag']) && $request['behavior_flag'] == 'collect') {
  430. if($request['behavior_value']) {
  431. $post->collect_count += 1;
  432. $post->collect_real_count += 1;
  433. PostCollect::create(['uid'=>$request['target_id'],'post_id'=>$request['post_id']]);
  434. Log::debug("帖子:".$postId."被收藏,collect_count +1");
  435. }else{
  436. $post->collect_count -= 1;
  437. $post->collect_real_count -= 1;
  438. PostCollect::where(['uid'=>$request['target_id'],'post_id'=>$request['post_id']])->delete();
  439. Log::debug("帖子:".$postId."被取消收藏,collect_count -1");
  440. }
  441. }
  442. $this->collectPostId($request['post_id']);
  443. return $post->save();
  444. }
  445. /**
  446. * 收集所有有操作的帖子,存入redis
  447. * 供后续计算帖子权重
  448. * @param $id
  449. */
  450. public function collectPostId($id)
  451. {
  452. $key = "community_calc_post_score";
  453. Redis::sadd($key,$id);
  454. Log::debug('存入帖子'.$id.'到权重列表');
  455. }
  456. /**
  457. * 话题详情
  458. */
  459. public function topicDetail($id)
  460. {
  461. return $this->topic
  462. ->find($id);
  463. }
  464. /**
  465. * 获取话题
  466. */
  467. public function getTopic($ids)
  468. {
  469. $topics = $this->topic
  470. ->whereIn('id', explode(',',$ids))
  471. ->orderByRaw(DB::raw("FIELD(id,{$ids})"))
  472. ->get();
  473. $data = [];
  474. foreach($topics as $topic){
  475. $data[] = [
  476. 'id' => $topic->id,
  477. 'name' => $topic->name,
  478. 'img' => $topic->img,
  479. 'follow_count' => $topic->follow->count() + 9876,
  480. ];
  481. }
  482. return $data;
  483. }
  484. /**
  485. * 获取内容视频组
  486. */
  487. public function getPostVideo($ids)
  488. {
  489. return $this->post
  490. ->select('id', 'img', 'uid', 'username', 'avatar')
  491. ->whereIn('id', explode(',',$ids))
  492. ->where('type', 'video')
  493. ->get();
  494. }
  495. //用户内容数,转发数,收藏数统计
  496. public function memberPostStatistics(){
  497. $token = JWTAuth::decode(JWTAuth::getToken());
  498. $postCount = $this->post->where('uid',$token['user']->uid)->count();
  499. $postCollectCount = $this->postCollect->where('uid',$token['user']->uid)->count();
  500. $postShareCount = $this->postShare->where('uid',$token['user']->uid)->count();
  501. $data = ['post_count'=>$postCount,'share_count'=>$postShareCount,'collect_count'=>$postCollectCount];
  502. return jsonSuccess($data);
  503. }
  504. }