Browse Source

Merge branch 'develop' of http://git.caihongxingqiu.net/rainbow/community-service into develop

xielin 5 years ago
parent
commit
470b6e27a0

+ 1 - 1
app/Http/Controllers/V1/CategoryController.php

@@ -35,7 +35,7 @@ class CategoryController extends Controller {
         if ($validator->fails()) {
             return jsonError($validator->errors()->first());
         }
-        $categoryList = $this->categoryRepository->getTopics($request->all());
+        $categoryList = $this->categoryRepository->getTopics($data['ids']);
         return $this->jsonSuccess($categoryList);
     }
 }

+ 66 - 0
app/Http/Controllers/V1/MemberFollowTopic.php

@@ -0,0 +1,66 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: Administrator
+ * Date: 2019-06-15
+ * Time: 15:09
+ */
+namespace App\Http\Controllers\V1;
+use App\Repositories\MemberFollowTopicRepository;
+use App\Transformers\MemberFollowTopicTanrformer;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Validator;
+use League\Fractal\Manager;
+use League\Fractal\Pagination\IlluminatePaginatorAdapter;
+use League\Fractal\Resource\Collection;
+use League\Fractal\Resource\Item;
+
+class MemberFollowTopic extends Controller {
+    public function __construct(MemberFollowTopicRepository $memberFollowTopicRepository) {
+        $this->memberFollowTopicRepository = $memberFollowTopicRepository;
+    }
+
+    //关注推荐话题
+    public function memberFollowTopic(Request $request){
+        $data = $request->all();
+        $validator = Validator::make($data, [
+            'topic_group_ids' => 'required|string',
+        ]);
+        if ($validator->fails()) {
+            return $this->jsonError($validator->errors()->first());
+        }
+        return $this->memberFollowTopicRepository->setMemberFollowTopic($data['topic_group_ids']);
+    }
+    //关注单个话题
+    public function followTopic(Request $request){
+        $data = $request->all();
+        $validator = Validator::make($data, [
+            'topic_id' => 'required|integer',
+        ]);
+        if ($validator->fails()) {
+            return $this->jsonError($validator->errors()->first());
+        }
+        return $this->memberFollowTopicRepository->follow($data['topic_id']);
+    }
+    //关注单个话题
+    public function cancelFollowTopic(Request $request){
+        $data = $request->all();
+        $validator = Validator::make($data, [
+            'topic_id' => 'required|integer',
+        ]);
+        if ($validator->fails()) {
+            return $this->jsonError($validator->errors()->first());
+        }
+        return $this->memberFollowTopicRepository->cancel($data['topic_id']);
+    }
+    //我关注话题列表
+    public function index(Request $request){
+        $data = $request->all();
+        $list = $this->memberFollowTopicRepository->list($data);
+        $fractal = new Manager();
+        $resource = new Collection($list, new MemberFollowTopicTanrformer());
+        $resource->setPaginator(new IlluminatePaginatorAdapter($list));
+        $data = $fractal->createData($resource)->toArray();
+        return jsonSuccess($data);
+    }
+}

+ 86 - 0
app/Http/Controllers/V1/PostController.php

@@ -11,6 +11,7 @@ namespace App\Http\Controllers\V1;
 use App\Repositories\PostRepositories;
 use App\Traits\UserTrait;
 use App\Transformers\Post\CommentTransformer;
+use App\Transformers\Post\DetailTransformer;
 use App\Transformers\Post\ListTransformer;
 use App\Transformers\Post\ReplyTransformer;
 use App\Transformers\Post\SuggestTransformer;
@@ -32,6 +33,44 @@ class PostController extends Controller
         $this->postRepositories = $postRepositories;
     }
 
+    /**
+     * 发布内容
+     */
+    public function create(Request $request)
+    {
+        $validator = Validator::make($request->all(), [
+            'type' => ['required',Rule::in('image', 'video', 'html')],
+            'img' => 'required|url',
+            'video' => 'required_if:type,video|string|url',
+            'topic_ids' => 'required|string|max:64',
+            'title' => 'nullable|string|max:20',
+            'content' => 'required|string|max:1000',
+            'location' => 'nullable|string|max:20',
+            'imgs' => 'required_if:type,image|string',
+        ]);
+        if ($validator->fails()) {
+            return jsonError($validator->errors()->first());
+        }
+
+        return  $this->postRepositories->create($request->all());
+    }
+
+    /**
+     * 评论&回复
+     */
+    public function comment(Request $request)
+    {
+        $validator = Validator::make($request->all(), [
+            'post_id' => 'required|integer',
+            'content' => 'required|string|max:150',
+        ]);
+        if ($validator->fails()) {
+            return jsonError($validator->errors()->first());
+        }
+
+        return  $this->postRepositories->comment($request->all());
+    }
+
     /**
      * 内容列表
      */
@@ -81,6 +120,51 @@ class PostController extends Controller
         return jsonSuccess($data);
     }
 
+    /**
+     * 内容详情
+     */
+    public function detail(Request $request)
+    {
+        $validator = Validator::make($request->all(), [
+            'post_id' => 'required|integer',
+        ]);
+        if ($validator->fails()) {
+            return jsonError($validator->errors()->first());
+        }
+        $userInfo = $this->getUserInfo();
+        if(empty($userInfo)){
+            Log::info('获取用户信息失败');
+            return jsonError('获取用户信息失败');
+        }
+        $detail = $this->postRepositories->detail($request['post_id']);
+        if(!$detail){
+            return jsonError('获取内容信息失败');
+        }
+        $fractal = new Manager();
+        $res = new Item($detail, new DetailTransformer($userInfo['uid']));
+        return $array = $fractal->createData($res)->toArray();
+        $param = $request->all();
+        $list = $this->postRepositories->suggestPost($param);
+
+
+
+        $resource = new Collection($list, new SuggestTransformer($userInfo['uid']));
+        $resource->setPaginator(new IlluminatePaginatorAdapter($list));
+        $data = $fractal->createData($resource)->toArray();
+
+        if(!(isset($param['current_page']) && $param['current_page'] > 1)){
+            $newData = [];
+            foreach($data['data'] as $key => $val){
+                if($key == 1){
+                    $newData[] = ['show_type' => 1];
+                }
+                $newData[] = $val;
+            }
+            $data['data'] = $newData;
+        }
+        return jsonSuccess($data);
+    }
+
     /**
      * 评论列表
      */
@@ -133,4 +217,6 @@ class PostController extends Controller
         ];
         return jsonSuccess($data);
     }
+
+
 }

+ 7 - 7
app/Http/Middleware/JwtAuthMiddleware.php

@@ -39,13 +39,13 @@ class JwtAuthMiddleware
                 ];
                 return response()->json($error)->setStatusCode(401);
             }
-            if ($data->sign !== md5($data->uid . config('customer.jwt_secret'))) {
-                $error = [
-                    'message' => 'request is not allow',
-                    'code' => 401,
-                ];
-                return response()->json($error);
-            }
+//            if ($data->sign !== md5($data->uid . config('customer.jwt_secret'))) {
+//                $error = [
+//                    'message' => 'request is not allow',
+//                    'code' => 401,
+//                ];
+//                return response()->json($error);
+//            }
         } catch (TokenExpiredException $e) {
             $error = [
                 'message' => 'Token is Expired',

+ 3 - 5
app/Topic.php

@@ -3,15 +3,13 @@
  * Created by PhpStorm.
  * User: Administrator
  * Date: 2019-06-15
- * Time: 10:47
+ * Time: 14:54
  */
-
 namespace App\Models;
 
-
 use Illuminate\Database\Eloquent\Model;
 
-class Topic extends Model {
-    protected $table = 'topic';
+class MemberFollowTopic extends Model{
+    protected $table = 'member_follow_topic';
     protected $guarded = [];
 }

+ 4 - 3
app/Repositories/CategoryRepository.php

@@ -27,11 +27,12 @@ class CategoryRepository {
         return $this->category->where($where)->get();
     }
     //获取多个话题
-    public function getTopics($ids = []){
+    public function getTopics($ids){
+        $ids = explode(',',$ids);
         return $this->categoryTopic
-            ->leftJoin('topic', 'categoryTopic.topic_id', '=', 'topic.id')
+            ->leftJoin('topic', 'category_topic.topic_id', '=', 'topic.id')
             ->where('topic.is_suggest',1)
-            ->whereIn('topic.category_id',$ids)
+            ->whereIn('category_topic.category_id',$ids)
             ->select('topic.id','topic.name','topic.is_suggest')
             ->get();
     }

+ 84 - 0
app/Repositories/MemberFollowTopicRepository.php

@@ -0,0 +1,84 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: Administrator
+ * Date: 2019-06-15
+ * Time: 15:01
+ */
+
+namespace App\Repositories;
+
+use App\Models\MemberFollowTopic;
+use Tymon\JWTAuth\Facades\JWTAuth;
+use Illuminate\Support\Facades\Auth;
+
+class MemberFollowTopicRepository {
+    public function __construct(MemberFollowTopic $memberFollowTopic,CategoryRepository $categoryRepository) {
+        $this->memberFollowTopic = $memberFollowTopic;
+        $this->categoryRepository = $categoryRepository;
+    }
+    //关注话题
+    public function setMemberFollowTopic($topic_group_ids){
+
+        $data = $this->categoryRepository->getTopics($topic_group_ids);
+        //获取uid
+        $token =  JWTAuth::decode(JWTAuth::getToken());
+        if($data){
+            $category_topic_data = [];
+            foreach($data as $value){
+                $category_topic_data[] = [
+                    'uid' => $token['user']->uid,
+                    'topic_id' => $value['id'],
+                ];
+            }
+            $res = $this->memberFollowTopic->insert($category_topic_data);
+            if($res){
+                return jsonSuccess();
+            }else{
+                return jsonError('关注失败');
+            }
+        }
+    }
+    //关注单个话题
+    public function follow($topic_id){
+        $token =  JWTAuth::decode(JWTAuth::getToken());
+        $info = $this->memberFollowTopic->where(['topic_id'=>$topic_id,'uid'=>$token['user']->uid])->first();
+        if($info){
+            return jsonError('您已关注该话题');
+        }
+        $data = ['uid'=>$token['user']->uid,'topic_id'=>$topic_id];
+        $res = $this->memberFollowTopic->create($data);
+        if($res){
+            return jsonSuccess();
+        }else{
+            return jsonError('关注失败');
+        }
+    }
+    //取消关注话题
+    public function cancel($topic_id){
+        $token =  JWTAuth::decode(JWTAuth::getToken());
+        $info = $this->memberFollowTopic->where(['topic_id'=>$topic_id,'uid'=>$token['user']->uid])->first();
+        if(!$info){
+            return jsonError('您没有关注该话题');
+        }
+        $res = $this->memberFollowTopic->where('id',$info->id)->delete();
+        if($res){
+            return jsonSuccess();
+        }else{
+            return jsonError('取关失败');
+        }
+    }
+    public function list($request){
+        $token =  JWTAuth::decode(JWTAuth::getToken());
+        $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
+        $where[] = ['uid',$token['user']->uid];
+        if(isset($request['name'])){
+            $where[] = ['topic.name', 'like', "%{$request['name']}%"];
+        }
+        return $this->memberFollowTopic
+                    ->leftJoin('topic', 'member_follow_topic.topic_id', '=', 'topic.id')
+                    ->where($where)
+                    ->select('member_follow_topic.id','uid','topic_id','topic.name as topic_name','topic.is_suggest')
+                    ->paginate($perPage);
+    }
+}

+ 255 - 1
app/Repositories/PostRepositories.php

@@ -14,16 +14,259 @@ use App\Models\Post;
 use App\Models\PostCollect;
 use App\Models\PostComment;
 use App\Models\PostData;
+use App\Models\PostImgs;
 use App\Models\PostLike;
+use App\Models\Topic;
+use App\Service\DetectionService;
+use App\Service\RabbitMqUtil;
+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;
 
 class PostRepositories
 {
-    public function __construct(Post $post,PostComment $postComment)
+    use UserTrait;
+    use PostTrait;
+    public function __construct(Post $post,
+                                PostData $postData,
+                                PostImgs $postImgs,
+                                PostComment $postComment,
+                                DetectionService $detectionService,
+                                RabbitMqUtil $rabbitMqUtil,
+                                Topic $topic)
     {
         $this->post = $post;
+        $this->postData = $postData;
+        $this->postImgs = $postImgs;
         $this->postComment = $postComment;
+        $this->detectionService = $detectionService;
+        $this->rabbitMqUtil = $rabbitMqUtil;
+        $this->topic = $topic;
+    }
+
+    /**
+     * 发布内容
+     */
+    public function create($request)
+    {
+        //验证小号
+        $userInfo = $this->getUserInfo();
+        if (empty($userInfo)) {
+            Log::info('获取用户信息失败');
+            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('图片违规,请修正哦');
+        }
+
+        $data = [
+            'uid' => $userInfo['uid'],
+            'username' => $userInfo['username'],
+            'mobile' => $userInfo['mobile'],
+            'avatar' => $userInfo['avatar']??'',
+            'type' => $request['type'],
+            'img' => $request['img'],
+            'video' => isset($request['video'])? $request['video'] : '',
+            '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');
+
+
+        DB::beginTransaction();
+        try{
+            $post = $this->post->create($data);
+
+            $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' => 0
+            ]);
+
+            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);
+            return jsonSuccess();
+
+        }catch (QueryException $exception){
+            DB::rollBack();
+            Log::debug('发布内容失败:'.$exception->getMessage());
+            return jsonError('发布内容失败,请重试');
+        }
+    }
+
+    /**
+     * 评论&回复
+     */
+    public function comment($request)
+    {
+        //验证小号
+        $userInfo = $this->getUserInfo();
+        if (empty($userInfo)) {
+            Log::info('获取用户信息失败');
+            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'];
+                $this->rabbitMqUtil->push('add_message', [
+                    'uid' => $request['reply_uid'],
+                    'message_show_type' => 'post_reply_main',
+                    'param' => [
+                        'uid' => $userInfo['uid'],
+                        'username' => $userInfo['username'],
+                        'post_id' => $post->id,
+                        'content' => subtext($request['content'], 20),
+                    ]
+                ]);
+            }else{
+                $data['reply_uid'] = 0;
+                $data['reply_username'] = '';
+                $this->rabbitMqUtil->push('add_message', [
+                    'uid' => $comment->uid,
+                    'message_show_type' => 'post_reply',
+                    'param' => [
+                        'uid' => $userInfo['uid'],
+                        'username' => $userInfo['username'],
+                        'post_id' => $post->id,
+                        'content' => subtext($request['content'], 20),
+                    ]
+                ]);
+            }
+        }else{
+            $this->rabbitMqUtil->push('add_message', [
+                'uid' => $post->uid,
+                'message_show_type' => 'post_comment',
+                'param' => [
+                    'uid' => $userInfo['uid'],
+                    'username' => $userInfo['username'],
+                    'post_id' => $post->id,
+                    'content' => subtext($request['content'], 20),
+                ]
+            ]);
+        }
+
+        DB::beginTransaction();
+        try{
+            $this->postComment->create($data);
+            $post->data->comment_count += 1;
+            $post->data->save();
+
+            DB::commit();
+            return jsonSuccess();
+
+        }catch (QueryException $exception){
+            DB::rollBack();
+            Log::debug('评论内容失败:'.$exception->getMessage());
+            return jsonError('评论内容失败,请重试');
+        }
     }
 
     /**
@@ -46,6 +289,17 @@ class PostRepositories
             ->paginate($perPage);
     }
 
+    /**
+     * 内容详情
+     */
+    public function detail($id)
+    {
+        return $this->post
+            ->join('post_data', 'post_data.post_id', '=', 'post.id')
+            ->select('post.*')
+            ->find($id);
+    }
+
     /**
      * 推荐内容列表
      */

+ 188 - 0
app/Service/DetectionService.php

@@ -0,0 +1,188 @@
+<?php
+namespace App\Service;
+
+use Green\Request\V20170112 as Green;
+
+class DetectionService
+{
+    /**
+     * Get the acs client
+     * @return \DefaultAcsClient
+     */
+    private function getClient()
+    {
+        date_default_timezone_set("PRC");
+        $iClientProfile = \DefaultProfile::getProfile("cn-shanghai", config('aliyun.access_key'), config('aliyun.access_secret'));
+
+        \DefaultProfile::addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
+
+        $client = new \DefaultAcsClient($iClientProfile);
+
+        return $client;
+    }
+
+    /**
+     * scene 风险场景,和传递进来的场景对应
+     * suggestion 建议用户处理,取值范围:[“pass”, “review”, “block”], pass:图片正常,review:需要人工审核,block:图片违规,
+     *            可以直接删除或者做限制处理
+     * label 文本的分类
+     * rate 浮点数,结果为该分类的概率;值越高,越趋于该分类;取值为[0.00-100.00]
+     * extras map,可选,附加信息. 该值将来可能会调整,建议不要在业务上进行依赖
+     *
+     *  -10000  检测数据有问题
+     *  10000  检测数据正常
+     *  20000  检测出异常 重试三次
+     * @param $request
+     */
+    private function processResponse($request)
+    {
+        $client = $this->getClient();
+        try {
+            $response = $client->getAcsResponse($request);
+
+            if(200 == $response->code){
+                $taskResults = $response->data;
+                $detail = [];
+                $flag = true;
+                foreach ($taskResults as $taskResult) {
+                    if(200 == $taskResult->code){
+                        $this->processSceneResult($taskResult, $flag);
+                    }else{
+                        return $this->echoStr(-2000, 'task process fail:'.$response->code);
+                    }
+                    if (isset($taskResult->filteredContent)) {
+                        array_push($detail, $taskResult->filteredContent);
+                    }
+                }
+                if($flag == false){
+                    return $this->echoStr(-10000, 'the scene is not normal', $detail);
+                }else{
+                    return $this->echoStr(10000, 'the scene is normal');
+                }
+            }else{
+                return $this->echoStr(-2000, 'detect not success. code:'.$response->code);
+            }
+        } catch (Exception $e) {
+            return $this->echoStr(-2000, $e);
+        }
+    }
+
+    /**
+     * @param $code
+     * @param $msg
+     */
+    private function echoStr($code, $msg, $detail = []){
+        return array(
+            'code' => $code,
+            'msg' => $msg,
+            'detail' => $detail
+        );
+    }
+
+    /**
+     * @param $taskResult
+     */
+    private function processSceneResult($taskResult, &$flag){
+        $sceneResults = $taskResult->results;
+        foreach ($sceneResults as $sceneResult) {
+            //根据scene和suggetion做相关的处理
+            $suggestion = $sceneResult->suggestion;
+            $rate = $sceneResult->rate;
+            if($suggestion!='pass' && $rate>80){
+                $flag = false;
+            }
+        }
+    }
+
+    /**
+     * 文本垃圾检测
+     * scenes字符串数组:
+     *   关键词识别scene场景取值keyword
+     *        分类label:正常normal 含垃圾信息spam 含广告ad 涉政politics 暴恐terrorism 色情porn 辱骂abuse
+     *                  灌水flood 命中自定义customized(阿里后台自定义)
+     *   垃圾检测识别场景scene取值antispam
+     *        分类label:正常normal 含违规信息spam 含广告ad 涉政politics 暴恐terrorism 色情porn 违禁contraband
+     *                  命中自定义customized(阿里后台自定义)
+     *
+     * tasks json数组 ,最多支持100个task即100段文本
+     * content 待检测文本,最长4000个字符
+     *
+     * @param $text 支持字符串和数组
+     * @return null
+     */
+    public function checkText($text){
+        if(empty($text)){
+            return null;
+        }
+        $request = new Green\TextScanRequest();
+        $request->setMethod("POST");
+        $request->setAcceptFormat("JSON");
+        if(is_array($text)){
+            $taskArr = [];
+            foreach($text as $k => $v){
+                $task = 'task'.$k;
+                $$task = array('dataId' =>  md5(uniqid($task)),
+                    'content' => $v,
+                    'category' => 'post',
+                    'time' => round(microtime(true)*1000)
+                );
+                array_push($taskArr, $$task);
+            }
+            $request->setContent(json_encode(array("tasks" => $taskArr,
+                "scenes" => array("antispam"))));
+        }else if(is_string($text)){
+            $task1 = array('dataId' =>  md5(uniqid()),
+                'content' => $text
+            );
+            $request->setContent(json_encode(array("tasks" => array($task1),
+                "scenes" => array("antispam"))));
+        }
+        return $this->processResponse($request);
+    }
+    /**
+     * 图片检测
+     * scenes字符串数组:
+     *   图片广告识别scene场景取值ad
+     *        分类label: 正常normal 含广告ad
+     *   图片鉴黄识别场景scene取值porn
+     *        分类label:正常normal 性感sexy 色情porn
+     *   图片暴恐涉政识别场景scene取值terrorism
+     *        分类label:正常normal terrorism含暴恐图片 outfit特殊装束 logo特殊标识 weapon武器 politics渉政 others	其它暴恐渉政
+     *
+     * tasks json数组 ,最多支持100个task即100张图片
+     *
+     * @param $img 支持字符串和数组
+     * @return null
+     */
+    public function checkImg($img){
+        if(empty($img)){
+            return null;
+        }
+        $request = new Green\ImageSyncScanRequest();
+        $request->setMethod("POST");
+        $request->setAcceptFormat("JSON");
+        if(is_array($img)){
+            $taskArr = array();
+            foreach($img as $k => $v){
+                $task = 'task'.$k;
+                $$task = array('dataId' =>  md5(uniqid($task)),
+                    'url' => $v,
+                    'time' => round(microtime(true)*1000)
+                );
+                array_push($taskArr, $$task);
+            }
+            $request->setContent(json_encode(array("tasks" => $taskArr,
+                "scenes" => array("ad", "porn", "terrorism"))));
+        }else if(is_string($img)){
+            $task1 = array('dataId' =>  md5(uniqid()),
+                'url' => $img,
+                'time' => round(microtime(true)*1000)
+            );
+            $request->setContent(json_encode(array("tasks" => array($task1),
+                "scenes" => array("ad", "porn", "terrorism"))));
+        }
+        return $this->processResponse($request);
+    }
+
+
+}

+ 34 - 0
app/Traits/PostTrait.php

@@ -0,0 +1,34 @@
+<?php
+
+/**
+ * Created by PhpStorm.
+ * User: Administrator
+ * Date: 2019/6/6
+ * Time: 18:05
+ */
+namespace App\Traits;
+
+use Illuminate\Support\Facades\Redis;
+
+trait PostTrait
+{
+    //预计可获得彩虹豆数
+    public function availableBean()
+    {
+        $bean = Redis::get('yesterday_post_create_bean');
+        $count = Redis::get('yesterday_post_count');
+        $num = 1000;
+        if($bean && $count){
+            $num = $bean / $count;
+        }
+        $h = date('h');
+        $H = date('H');
+        $t = $h * 60 / 720 + 2;
+
+
+        if(in_array(intval($H), [9,10,11,12,17.18,19,20,21])){
+            $t += 0.5;
+        }
+        return intval($num * $t);
+    }
+}

+ 14 - 0
app/Traits/UserTrait.php

@@ -25,4 +25,18 @@ trait UserTrait
         }
 
     }
+
+    public function getFollowStatus($uid, $followUid) {
+        try {
+            $sign = generateSign([], config('customer.app_secret'));
+            $url = config("customer.app_service_url").'/user/v2/follow/checkStatus';
+            $array = [
+                'json' => ['sign' => $sign, 'uid' => $uid, 'follow_uid' => $followUid], 'query' => [], 'http_errors' => false,'headers'=>['Authorization'=>"Bearer ".JWTAuth::getToken()]
+            ];
+            return http($url,$array,'get');
+        } catch (\Exception $e) {
+            return [];
+        }
+
+    }
 }

+ 27 - 0
app/Transformers/MemberFollowTopicTanrformer.php

@@ -0,0 +1,27 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: Administrator
+ * Date: 2019-06-15
+ * Time: 16:55
+ */
+
+namespace App\Transformers;
+
+
+use App\Models\MemberFollowTopic;
+use League\Fractal\TransformerAbstract;
+
+class MemberFollowTopicTanrformer extends TransformerAbstract {
+
+    public function transform(MemberFollowTopic $memberFollowTopic)
+    {
+        return [
+            'id' => $memberFollowTopic['id'],
+            'uid' => $memberFollowTopic['uid'],
+            'topic_id' => $memberFollowTopic['topic_id'],
+            'topic_name' => $memberFollowTopic['topic_name'],
+            'is_suggest' => $memberFollowTopic['is_suggest'],
+        ];
+    }
+}

+ 69 - 0
app/Transformers/Post/DetailTransformer.php

@@ -0,0 +1,69 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: Administrator
+ * Date: 2019/6/17
+ * Time: 16:11
+ */
+namespace  App\Transformers\Post;
+
+use App\Models\Post;
+use App\Models\PostCollect;
+use App\Models\PostComment;
+use App\Models\PostDislike;
+use App\Models\PostLike;
+use App\Traits\UserTrait;
+use Carbon\Carbon;
+use League\Fractal\TransformerAbstract;
+
+class DetailTransformer extends TransformerAbstract
+{
+    use UserTrait;
+    public function __construct($uid)
+    {
+        $this->uid = $uid;
+    }
+    public function transform(Post $post)
+    {
+        $imgs = [];
+        foreach($post->imgs as $img){
+            $imgs[] = $img['img'];
+        }
+
+        $topic = [];
+        foreach($post->topic() as $key => $val){
+            $topic[] = [
+                'id' => $key,
+                'name' => $val
+            ];
+        }
+        $isFollow = 0;
+        $followStatus = $this->getFollowStatus($this->uid, $post['uid']);
+        if($followStatus){
+            $isFollow = $followStatus;
+        }
+        return [
+            'id' => $post['id'],
+            'type' => $post['type'],
+            'created_at' => Carbon::parse($post['created_at'])->diffForHumans(),
+            'uid' => $post['uid'],
+            'username' => $post['username'],
+            'avatar' => $post['avatar'],
+            'topic' => $topic,
+            'title' => $post['title'],
+            'content' => $post['content'],
+            'location' => $post['location'],
+            'img' => $post['img'],
+            'imgs' => $imgs,
+            'video' => $post['video'],
+            'pv' => $post->data->pv,
+            'praise_count' => $post->data->praise_count,
+            'comment_count' => $post->data->comment_count,
+            'will_collect_bean' => $post->data->will_collect_bean,
+            'is_like' => PostLike::where('post_id', $post['id'])->where('uid', $this->uid)->exists()?1:0,
+            'is_dislike' => PostDislike::where('post_id', $post['id'])->where('uid', $this->uid)->exists()?1:0,
+            'is_collect' => PostCollect::where('post_id', $post['id'])->where('uid', $this->uid)->exists()?1:0,
+            'is_follow' => $isFollow,
+        ];
+    }
+}

+ 16 - 2
app/Transformers/Post/SuggestTransformer.php

@@ -13,11 +13,13 @@ use App\Models\PostCollect;
 use App\Models\PostComment;
 use App\Models\PostDislike;
 use App\Models\PostLike;
+use App\Traits\UserTrait;
 use Carbon\Carbon;
 use League\Fractal\TransformerAbstract;
 
 class SuggestTransformer extends TransformerAbstract
 {
+    use UserTrait;
     public function __construct($uid)
     {
         $this->uid = $uid;
@@ -49,6 +51,18 @@ class SuggestTransformer extends TransformerAbstract
                 'reply' => $reply,
             ];
         }
+        $topic = [];
+        foreach($post->topic() as $key => $val){
+            $topic[] = [
+                'id' => $key,
+                'name' => $val
+            ];
+        }
+        $isFollow = 0;
+        $followStatus = $this->getFollowStatus($this->uid, $post['uid']);
+        if($followStatus){
+            $isFollow = $followStatus;
+        }
         return [
             'show_type' => 0,
             'id' => $post['id'],
@@ -57,7 +71,7 @@ class SuggestTransformer extends TransformerAbstract
             'uid' => $post['uid'],
             'username' => $post['username'],
             'avatar' => $post['avatar'],
-            'topic' => $post->topic(),
+            'topic' => $topic,
             'title' => $post['title'],
             'content' => $post['content'],
             'location' => $post['location'],
@@ -72,7 +86,7 @@ class SuggestTransformer extends TransformerAbstract
             'is_dislike' => PostDislike::where('post_id', $post['id'])->where('uid', $this->uid)->exists()?1:0,
             'is_collect' => PostCollect::where('post_id', $post['id'])->where('uid', $this->uid)->exists()?1:0,
             'comment' => $comment,
-            'is_follow' => 1,
+            'is_follow' => $isFollow,
         ];
     }
 }

+ 1 - 0
bootstrap/app.php

@@ -32,6 +32,7 @@ $app->configure('auth');
 $app->configure('jwt');
 $app->configure('database');
 $app->configure('elasticsearch');
+$app->configure('aliyun');
 /*
 |--------------------------------------------------------------------------
 | Register Container Bindings

+ 1 - 0
composer.json

@@ -17,6 +17,7 @@
         "tymon/jwt-auth": "1.0.0-rc.4.1",
         "vlucas/phpdotenv": "^3.3",
         "moontoast/math": "^1.1",
+        "tomcao/aliyuncs-green": "^1.1",
         "multilinguals/apollo-client": "^0.1.2"
     },
     "require-dev": {

+ 7 - 0
config/aliyun.php

@@ -0,0 +1,7 @@
+<?php
+
+
+return [
+    'access_key'        => 'LTAIGTDKUOVQf2Ln', // accessKey
+    'access_secret'     => 'HzY9r2gDPbURQ0Vp69A7THV0RmxMkb', // accessSecret
+];

+ 11 - 0
resources/lang/zh-CN/validation.php

@@ -101,6 +101,17 @@ return [
 
     'attributes' => [
         'post_id' => '内容id',
+        'uid' => '用户uid',
+        'type' => '类型',
+        'is_suggest' => '是否推荐',
+        'img' => '图片',
+        'video' => '视频',
+        'topic_ids' => '话题id',
+        'title' => '标题',
+        'content' => '内容',
+        'location' => '位置',
+        'imgs' => '图组',
+        'imgs.*' => '图集',
     ],
     'mobile'    => '手机号码格式不正确。',
 ];

+ 12 - 0
routes/api.php

@@ -20,11 +20,23 @@ $api->version('v1', [
     $api->get('getBehaviorByIdentify', 'BehaviorController@getBehaviorByIdentify');
     //登录+验签
     $api->group(['middleware' => ['chxq_jwt_auth']], function ($api) {
+        $api->post('post', 'PostController@create');
         $api->get('post', 'PostController@index');
+        $api->get('post/detail', 'PostController@detail');
         $api->get('post/suggest', 'PostController@suggestPost');
+        $api->post('post/comment', 'PostController@comment');
         $api->get('post/comment', 'PostController@commentList');
         $api->get('post/reply', 'PostController@replyList');
         $api->get('topicCategory', 'CategoryController@index');
+        $api->get('topicCategory/getTopics', 'CategoryController@getTopics');
+        //关注推荐话题
+        $api->post('memberFollowTopic', 'MemberFollowTopic@memberFollowTopic');
+        //关注话题
+        $api->post('memberFollowTopic/follow', 'MemberFollowTopic@followTopic');
+        //取消关注
+        $api->delete('memberFollowTopic/cancel', 'MemberFollowTopic@cancelFollowTopic');
+        //关注话题列表
+        $api->get('memberFollowTopic', 'MemberFollowTopic@index');
     });
 
 });