PostRepositories.php 20 KB

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