123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672 |
- <?php
- /**
- * Created by PhpStorm.
- * User: edz
- * Date: 2019-06-10
- * Time: 17:53
- */
- namespace App\Repositories;
- use App\Models\Behavior;
- use App\Models\Post;
- use App\Models\PostCollect;
- use App\Models\PostComment;
- use App\Models\PostData;
- use App\Models\PostDislike;
- use App\Models\PostImgs;
- use App\Models\PostLike;
- use App\Models\PostLog;
- use App\Models\PostShare;
- use App\Models\Topic;
- use App\Service\AliYunVodService;
- use App\Service\DetectionService;
- use App\Traits\CmsTrait;
- use App\Traits\PostTrait;
- use App\Traits\UserTrait;
- use Illuminate\Database\QueryException;
- use Illuminate\Support\Carbon;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Facades\Redis;
- use Illuminate\Support\Facades\DB;
- use Tymon\JWTAuth\Facades\JWTAuth;
- class PostRepositories
- {
- use UserTrait;
- use PostTrait;
- use CmsTrait;
- public function __construct(Post $post,
- PostData $postData,
- PostImgs $postImgs,
- PostComment $postComment,
- PostCollect $postCollect,
- PostShare $postShare,
- PostLog $postLog,
- DetectionService $detectionService,
- AliYunVodService $aliYunVodService,
- Topic $topic)
- {
- $this->post = $post;
- $this->postData = $postData;
- $this->postImgs = $postImgs;
- $this->postComment = $postComment;
- $this->postCollect = $postCollect;
- $this->postShare = $postShare;
- $this->postLog = $postLog;
- $this->detectionService = $detectionService;
- $this->topic = $topic;
- $this->aliYunVodService = $aliYunVodService;
- }
- /**
- * 发布内容
- */
- public function create($request)
- {
- //验证小号
- $userInfo = $this->getUserInfo();
- if (empty($userInfo)) {
- return jsonError('获取用户信息失败');
- }
- if(!$userInfo['sns_status']){
- return jsonError('您已被禁言');
- }
- $isValid = 0;
- if($userInfo['strength']){
- $isValid = 1;
- }
- // $oneHourTime = Carbon::now()->addHours(-1)->toDateTimeString();
- // $oneHourPostCount = $this->post->where('uid', $userInfo['uid'])->where('created_at', '>', $oneHourTime)->count();
- // if($oneHourPostCount > 5){
- // return jsonError('创作欲望太强啦,休息一下,看看其他用户的内容吧!');
- // }
- $detectionText = $request['title'] .','. $request['content'];
- $detectionTextResult = $this->detectionService->checkText($detectionText);
- if ($detectionTextResult['code']<0) {
- return jsonError('内容违规,请修正哦');
- }
- $topicIds = json_decode($request['topic_ids'], true);
- $topicCount = count($topicIds);
- if($topicCount == 0 || $topicCount > 5){
- return jsonError('所选话题必须1-5个');
- }
- //验证话题
- $hasTopicCount = $this->topic->whereIn('id', $topicIds)->count();
- if($topicCount != $hasTopicCount){
- Log::error('所选话题非法'.$request['topic_ids']);
- return jsonError('所选话题非法');
- }
- $imgs = [];
- if($request['type'] == 'image'){
- $imgs = json_decode($request['imgs'], true);
- $imgCount = count($imgs);
- if($imgCount == 0 || $imgCount > 9){
- return jsonError('所传图集必须1-9个');
- }
- }
- $allImg = array_merge($imgs, [$request['img']]);
- $detectionImageResult = $this->detectionService->checkImg($allImg);
- if ($detectionImageResult['code']<0) {
- return jsonError('图片违规,请修正哦');
- }
- $videoUrl = "";
- $videoId = "";
- if(isset($request['video']) && $request['video']){
- $videoId = $request['video'];
- for($i=0;$i<3;$i++){
- $videoUrl = $this->aliYunVodService->getPlayUrlByVideoId($request['video']);
- Log::debug('video-url:'.$videoUrl);
- if($videoUrl){
- break;
- }
- }
- if(empty($videoUrl)){
- return jsonError('发布失败,请重试');
- }
- }
- $data = [
- 'uid' => $userInfo['uid'],
- 'username' => $userInfo['username'],
- 'mobile' => $userInfo['mobile'],
- 'avatar' => $userInfo['avatar']??'',
- 'type' => $request['type'],
- 'img' => $request['img'],
- 'video' => $videoUrl,
- 'video_id' => $videoId,
- 'topic_ids' => implode(',', $topicIds),
- 'title' => isset($request['title'])? $request['title'] : '',
- 'content' => $request['content'],
- 'location' => isset($request['location'])? $request['location'] : '',
- 'is_suggest' => 0,
- 'is_hide' => 0
- ];
- $date = date('Y-m-d H:i:s');
- $fresh = (Carbon::now()->timestamp) - (Carbon::parse("2019-05-01 00:00:00")->timestamp);
- $score = $fresh / 86400;
- DB::beginTransaction();
- try{
- $post = $this->post->create($data);
- $postData = $this->postData->create([
- 'post_id' => $post->id,
- 'pv' => 0,
- 'pv_real' => 0,
- 'dislike_count' => 0,
- 'praise_count' => 0,
- 'praise_real_count' => 0,
- 'share_count' => 0,
- 'share_real_count' => 0,
- 'comment_count' => 0,
- 'collect_count' => 0,
- 'collect_real_count' => 0,
- 'available_bean' => $this->availableBean(),
- 'will_collect_bean' => rand(100, 200),
- 'collect_bean' => 0,
- 'weight' => $score
- ]);
- if($imgs){
- $imgData = [];
- foreach($imgs as $img){
- $imgData[] = [
- 'post_id' => $post->id,
- 'img' => $img,
- 'created_at' => $date,
- 'updated_at' => $date
- ];
- }
- $this->postImgs->insert($imgData);
- }
- DB::commit();
- Redis::zadd('post_trigger_type', $isValid, $post->id);
- foreach($topicIds as $id){
- Redis::zincrby('topic.user_uid'.$userInfo['uid'], 1, $id);
- }
- return jsonSuccess([
- 'post_id' => $post->id,
- 'h5url' => config('customer.share_post_h5url')."?post_id={$post->id}&invite_code={$userInfo['invite_code']}",
- 'bean' => $postData->available_bean,
- ]);
- }catch (QueryException $exception){
- DB::rollBack();
- Log::debug('发布内容失败:'.$exception->getMessage());
- return jsonError('发布内容失败,请重试');
- }
- }
- /**
- * 评论&回复
- */
- public function comment($request)
- {
- //验证小号
- $userInfo = $this->getUserInfo();
- if (empty($userInfo)) {
- return jsonError('获取用户信息失败');
- }
- if(!$userInfo['sns_status']){
- return jsonError('您已被禁言');
- }
- $oneHourTime = Carbon::now()->addHours(-1)->toDateTimeString();
- $oneHourCommentCount = $this->postComment->where('uid', $userInfo['uid'])->where('created_at', '>', $oneHourTime)->count();
- if($oneHourCommentCount > 59){
- return jsonError('回复了这么多,休息休息,喝口水吧!');
- }
- $detectionTextResult = $this->detectionService->checkText($request['content']);
- if ($detectionTextResult['code']<0) {
- return jsonError('内容违规,请修正哦');
- }
- $post = $this->post->find($request['post_id']);
- if(!$post){
- return jsonError('获取内容信息失败');
- }
- $data = [
- 'uid' => $userInfo['uid'],
- 'post_id' => $request['post_id'],
- 'parent_id' => 0,
- 'username' => $userInfo['username'],
- 'reply_uid' => 0,
- 'reply_username' => '',
- 'avatar' => $userInfo['avatar']??'',
- 'content' => $request['content'],
- 'is_delete' => 0,
- ];
- if(isset($request['parent_id']) && $request['parent_id'] != 0){
- $comment = $this->postComment->find($request['parent_id']);
- if(!$comment || $comment->post_id != $post->id){
- return jsonError('获取评论信息失败');
- }
- if($comment->parent_id){
- return jsonError('只能回复评论');
- }
- $data['parent_id'] = $request['parent_id'];
- if(isset($request['reply_uid']) && isset($request['reply_username'])){
- $data['reply_uid'] = $request['reply_uid'];
- $data['reply_username'] = $request['reply_username'];
- }else{
- $data['reply_uid'] = 0;
- $data['reply_username'] = '';
- }
- }
- DB::beginTransaction();
- try{
- $comment = $this->postComment->create($data);
- DB::commit();
- return jsonSuccess(['id' => $comment->id], '评论成功');
- }catch (QueryException $exception){
- DB::rollBack();
- Log::debug('评论内容失败:'.$exception->getMessage());
- return jsonError('评论内容失败,请重试');
- }
- }
- /**
- * 内容列表
- */
- public function lists($request)
- {
- $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
- return $this->post
- ->join('post_data', 'post_data.post_id', '=', 'post.id')
- ->select('post.*')
- ->where(function($query) use ($request){
- if(isset($request['keyword'])){
- $query->where('title', 'like', "%{$request['keyword']}%")
- ->orWhere('content', 'like', "%{$request['keyword']}%");
- }
- })
- ->where(function($query) use ($request){
- if(isset($request['topic_ids']) && $request['topic_ids']){
- $topicIds = json_decode($request['topic_ids'], true);
- foreach ($topicIds as $key=>$id) {
- if ($key==0) {
- $query->whereRaw('FIND_IN_SET('.$id.', post.topic_ids)');
- } else {
- $query->orWhereRaw('FIND_IN_SET('.$id.', post.topic_ids)');
- }
- }
- }
- })
- ->orderBy('weight','desc')
- ->paginate($perPage);
- }
- /**
- * 视频列表
- */
- public function video($request)
- {
- $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
- $where = [];
- $id = 0;
- if(isset($request['id'])){
- $id = $request['id'];
- }
- $where[] = ['type', 'video'];
- if(isset($request['type'])){
- if($request['type'] == 'hot'){
- $ids = Redis::get('hotVideoIds');
- if(!$ids){
- $ids = $this->hotVideoIds();
- if(!$ids){
- $ids = '';
- }
- }
- Log::debug('热门视频ids'.$ids);
- return $this->post
- ->join('post_data', 'post_data.post_id', '=', 'post.id')
- ->select('post.*', DB::raw("IF (post.id = {$id},1,0) as sort"))
- ->where($where)
- ->whereIn('post.id', explode(',', $ids))
- ->orderBy('sort', 'desc')
- ->orderByRaw(DB::raw("FIELD(post.id,{$ids})"))
- ->paginate($perPage);
- }elseif($request['type'] == 'one'){
- $where[] = ['post.id', $id];
- return $this->post
- ->join('post_data', 'post_data.post_id', '=', 'post.id')
- ->select('post.*')
- ->where($where)
- ->paginate($perPage);
- }
- }
- return $this->post
- ->join('post_data', 'post_data.post_id', '=', 'post.id')
- ->select('post.*', DB::raw("IF (post.id = {$id},1,0) as sort"))
- ->where($where)
- ->orderBy('sort', 'desc')
- ->orderBy('weight','desc')
- ->paginate($perPage);
- }
- /**
- * 个人中心内容列表
- */
- public function MyPost($request, $uid)
- {
- $type = $request['type'];
- $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
- $where = [];
- if($type == 'create'){
- $where[] = ['post.uid', $uid];
- $post = $this->post;
- $order = 'post.id';
- }elseif($type == 'collect'){
- $post = $this->post->withTrashed()->join('post_collect', 'post_collect.post_id', '=', 'post.id');
- $where[] = ['post_collect.uid', $uid];
- $order = 'post_collect.id';
- }else{
- $post = $this->post->withTrashed()->join('post_share', 'post_share.post_id', '=', 'post.id');
- $where[] = ['post_share.uid', $uid];
- $order = 'post_share.updated_at';
- }
- return $post
- ->join('post_data', 'post_data.post_id', '=', 'post.id')
- ->select('post.*')
- ->where($where)
- ->orderBy($order,'desc')
- ->paginate($perPage);
- }
- /**
- * 内容详情
- */
- public function detail($id)
- {
- $row = $this->post
- ->join('post_data', 'post_data.post_id', '=', 'post.id')
- ->select('post.*')
- ->find($id);
- Log::debug($id);
- Log::debug($this->post->toSql());
- return $row;
- }
- /**
- * 内容是否存在
- */
- public function detailExists($id)
- {
- return $this->post->where('id', $id)->exists();
- }
- /**
- * 推荐内容列表
- */
- public function suggestPost($request)
- {
- $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
- return $this->post
- ->join('post_data', 'post_data.post_id', '=', 'post.id')
- ->select('post.*')
- ->orderBy('weight','desc')
- ->paginate($perPage);
- }
- /**
- * 话题内容
- */
- public function topicPost($request)
- {
- $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
- return $this->post
- ->join('post_data', 'post_data.post_id', '=', 'post.id')
- ->select('post.*')
- ->whereRaw('FIND_IN_SET(' . $request['id'] . ',post.topic_ids)')
- ->orderBy('id','desc')
- ->paginate($perPage);
- }
- /**
- * 评论列表
- */
- public function commentList($request)
- {
- $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
- return $this->postComment
- ->where('post_id', $request['post_id'])
- ->where('parent_id', 0)
- ->orderBy('id','desc')
- ->paginate($perPage);
- }
- /**
- * 回复列表
- */
- public function replyList($request)
- {
- $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
- return $this->postComment
- ->where('parent_id', $request['id'])
- ->orderBy('id','desc')
- ->paginate($perPage);
- }
- /**
- * 话题列表
- */
- public function topicList($request)
- {
- $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
- $where = [];
- if(isset($request['category_id']) && $request['category_id']){
- $topic = $this->topic->join('category_topic', 'category_topic.topic_id', '=', 'topic.id')->select('topic.*');
- $where[] = ['category_topic.category_id', $request['category_id']];
- }else{
- $topic = $this->topic;
- }
- if(isset($request['is_suggest']) && $request['is_suggest']){
- $where[] = ['topic.is_hot', $request['is_suggest']];
- }
- if(isset($request['name'])){
- $where[] = ['topic.name', 'like', "%{$request['name']}%"];
- }
- return $topic
- ->where($where)
- ->orderBy('id','desc')
- ->paginate($perPage);
- }
- /**
- * 更新帖子统计数量
- * @param $request
- * @return mixed
- */
- public function updatePostData($request)
- {
- $postId = isset($request['post_id'])?$request['post_id']:0;
- if(empty($postId)){
- Log::debug("非帖子类操作,不操作帖子统计数量".json_encode($request));
- return true;
- }
- $post = PostData::where('post_id', $postId)->first();
- if(!$post) return true;
- if (isset($request['behavior_flag']) && $request['behavior_flag'] == 'read') {
- $post->pv += 1;
- $post->pv_real += 1;
- Log::debug("帖子:".$postId."被阅读,pv +1");
- } elseif (isset($request['behavior_flag']) && $request['behavior_flag'] == 'unlike') {
- $post->dislike_count += 1;
- PostDislike::create(['uid'=>$request['target_id'],'post_id'=>$request['post_id']]);
- Log::debug("帖子:".$postId."被不喜欢,unlike +1");
- } elseif (isset($request['behavior_flag']) && $request['behavior_flag'] == 'like') {
- if($request['behavior_value']){
- $post->praise_count += 1;
- $post->praise_real_count += 1;
- PostLike::create(['uid'=>$request['target_id'],'post_id'=>$request['post_id']]);
- Log::debug("帖子:".$postId."被点赞,praise_count +1");
- }else{
- $post->praise_count -= 1;
- $post->praise_real_count -= 1;
- PostLike::where(['uid'=>$request['target_id'],'post_id'=>$request['post_id']])->delete();
- Log::debug("帖子:".$postId."被取消点赞,praise_count -1");
- }
- } elseif (isset($request['behavior_flag']) && $request['behavior_flag'] == 'forward') {
- $post->share_count += 1;
- $post->share_real_count += 1;
- $shareRow = PostShare::where(['uid'=>$request['target_id'],'post_id'=>$request['post_id']])->first();
- if($shareRow){
- PostShare::where(['uid'=>$request['target_id'],'post_id'=>$request['post_id']])->update(['uid'=>$request['target_id'],'post_id'=>$request['post_id']]);
- }else{
- PostShare::create(['uid'=>$request['target_id'],'post_id'=>$request['post_id']]);
- }
- Log::debug("帖子:".$postId."被分享,share_count +1");
- } elseif (isset($request['behavior_flag']) && $request['behavior_flag'] == 'comment') {
- $post->comment_count += 1;
- Log::debug("帖子:".$postId."被评论,comment_count +1");
- } elseif (isset($request['behavior_flag']) && $request['behavior_flag'] == 'collect') {
- if($request['behavior_value']) {
- $post->collect_count += 1;
- $post->collect_real_count += 1;
- PostCollect::create(['uid'=>$request['target_id'],'post_id'=>$request['post_id']]);
- Log::debug("帖子:".$postId."被收藏,collect_count +1");
- }else{
- $post->collect_count -= 1;
- $post->collect_real_count -= 1;
- PostCollect::where(['uid'=>$request['target_id'],'post_id'=>$request['post_id']])->delete();
- Log::debug("帖子:".$postId."被取消收藏,collect_count -1");
- }
- }
- $this->collectPostId($request['post_id']);
- return $post->save();
- }
- /**
- * 收集所有有操作的帖子,存入redis
- * 供后续计算帖子权重
- * @param $id
- */
- public function collectPostId($id)
- {
- $key = "community_calc_post_score";
- Redis::sadd($key,$id);
- Log::debug('存入帖子'.$id.'到权重列表');
- }
- /**
- * 话题详情
- */
- public function topicDetail($id)
- {
- return $this->topic
- ->find($id);
- }
- /**
- * 获取话题
- */
- public function getTopic($ids)
- {
- $topics = $this->topic
- ->whereIn('id', explode(',',$ids))
- ->orderByRaw(DB::raw("FIELD(id,{$ids})"))
- ->get();
- $data = [];
- foreach($topics as $topic){
- $data[] = [
- 'id' => $topic->id,
- 'name' => $topic->name,
- 'img' => $topic->img,
- 'follow_count' => getNumber($topic->follow->count() + config('customer.add_topic_follow_count')),
- ];
- }
- return $data;
- }
- /**
- * 获取内容视频组
- */
- public function getPostVideo($ids)
- {
- return $this->post
- ->select('id', 'img', 'uid', 'username', 'avatar')
- ->whereIn('id', explode(',',$ids))
- ->where('type', 'video')
- ->get();
- }
- //用户内容数,转发数,收藏数统计
- public function memberPostStatistics($uid){
- $postCount = $this->post->where('uid',$uid)->count();
- $postCollectCount = $this->postCollect->where('uid',$uid)->count();
- $postShareCount = $this->postShare->where('uid',$uid)->count();
- $data = ['post_count'=>$postCount,'share_count'=>$postShareCount,'collect_count'=>$postCollectCount];
- return jsonSuccess($data);
- }
- /**
- * 删除内容
- */
- public function delete($request)
- {
- //验证用户信息
- $userInfo = $this->getUserInfo();
- if (empty($userInfo)) {
- return jsonError('获取用户信息失败');
- }
- $post = $this->post->find($request['id']);
- if(!$post){
- return jsonError('获取内容信息失败');
- }
- if($post->uid != $userInfo['uid']){
- return jsonError('只能删除自己发布的内容');
- }
- $logData = [
- 'uid' => $userInfo['uid'],
- 'operator_type' => 'user',
- 'post_id' => $request['id'],
- 'username' => $userInfo['username'],
- 'log_type' => 'delete',
- 'content' => json_encode(['delete' => $request['id']]),
- ];
- DB::beginTransaction();
- try{
- $post->delete();
- $this->postLog->create($logData);
- DB::commit();
- Log::debug('删除内容失败:'.$request['id']);
- return jsonSuccess('删除内容成功');
- }catch (QueryException $exception){
- DB::rollBack();
- Log::debug('删除内容失败:'.$request['id'].$exception->getMessage());
- return jsonError('删除内容失败,请重试');
- }
- }
- }
|