PostRepositories.php 20 KB

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