PostRepositories.php 19 KB

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