wzq 5 anni fa
parent
commit
bc04683cb4

+ 161 - 0
app/Console/Commands/VirusAdd.php

@@ -0,0 +1,161 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: Administrator
+ * Date: 2019/6/24
+ * Time: 9:52
+ */
+namespace App\Console\Commands;
+
+
+use GuzzleHttp\Exception\RequestException;
+use Illuminate\Console\Command;
+use Illuminate\Support\Facades\Log;
+use PhpAmqpLib\Connection\AMQPStreamConnection;
+use GuzzleHttp\Client;
+
+class VirusAdd extends Command
+{
+    /**
+     * The name and signature of the console command.
+     *
+     * @var string
+     */
+    protected $signature = 'virus:add';
+
+    /**
+     * The console command description.
+     *
+     * @var string
+     */
+    protected $description = 'virus添加数据';
+
+    protected $channel;
+    protected $connection;
+
+    protected $queue = 'virus_add';
+
+    /**
+     * Create a new command instance.
+     *
+     * @return void
+     */
+    public function __construct()
+    {
+        parent::__construct();
+        $this->connection = $this->getConnection();
+        $this->channel = $this->connection->channel();
+        $this->channel->exchange_declare($this->queue, 'fanout', false, true, false);
+        // 初始化virus域名
+        $this->client = new Client([
+            'base_uri' => config('customer.VIRUS_URL'),
+            'timeout' => 3
+        ]);
+    }
+
+    public function getConnection()
+    {
+        $conn = false;
+        if ($this->connection) {
+            return $this->connection;
+        }
+        for ($i = 0; $i < 3; $i++) {
+            $connection = $this->createConn();
+            if ($connection) {
+                $conn = $connection;
+                break;
+            }
+            Log::info("create amqp conn retry=" . $i);
+        }
+        return $conn;
+    }
+
+    public function createConn()
+    {
+        try {
+            $connection = new AMQPStreamConnection(env('MQ_HOST'), env('MQ_PORT'), env('MQ_USERNAME'), env('MQ_PWD'), env('MQ_VHOST'));
+        } catch (\Exception $exception) {
+            Log::info("AMQP connection Error" . $exception->getMessage());
+            $connection = false;
+        }
+        return $connection;
+    }
+
+    /**
+     * Execute the console command.
+     *
+     * @return mixed
+     */
+    public function handle()
+    {
+        Log::info('接收一条消息');
+        $queue_name = $this->queue;
+        $this->channel->queue_declare($queue_name, false, true, false, false);
+        $this->channel->queue_bind($queue_name, $this->queue);
+        $callback = function ($msg) {
+            $this->line(date('Y-m-d H:i:S').$msg->body);
+            $data = \GuzzleHttp\json_decode($msg->body, true);
+            $this->line('接收一条消息收到数据' . $msg->body);
+            $res = $this->send($data);
+            if ($res) {
+                $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
+            }
+        };
+        $this->channel->basic_consume($queue_name, '', false, false, false, false, $callback);
+
+        while (count($this->channel->callbacks)) {
+            $this->channel->wait();
+        }
+        $this->channel->close();
+        $this->connection->close();
+
+
+    }
+
+    private function send($data)
+    {
+        try {
+            // 签名设置
+            $signKey = [
+                'app_id' => config('customer.VIRUS_APP_ID'),
+                'behavior_id' => $data['behavior_id'],
+                'target_id' => (string) $data['target_id'],
+                'action_id' => (string) $data['action_id'],
+                'behavior_flag' => $data['behavior_flag']
+            ];
+            ksort($signKey);
+            $signKey = urldecode(http_build_query($signKey));
+            $sign = md5(config('customer.VIRUS_APP_SECRET') . $signKey);
+            Log::debug('签名:'.$sign);
+            $json = [];
+            if($data['behavior_flag'] == 'publish'){
+                $json = [
+                    'app_id' => config('customer.VIRUS_APP_ID'),
+                    'behavior_id' => $data['behavior_id'],
+                    'behavior_flag' => $data['behavior_flag'],
+                    'post_id' => $data['post_id'],
+                    'post_desc' => $data['post_desc'],
+                    'post_cover' => $data['post_cover'],
+                    'target_id' => (string) $data['target_id'],
+                    'action_id' => (string) $data['action_id'],
+                    'extra' => [],
+                ];
+            }else{
+                Log::debug('行为类型错误'.json_encode($data));
+            }
+
+            $response = $this->client->request('POST', 'v2/record/add', [
+                'headers' => [
+                    'Content-Type' => 'application/json',
+                    'sign' => $sign
+                ],
+                'json' => $json
+            ]);
+//            $result = \GuzzleHttp\json_decode($response->getBody()->getContents(), true);
+            Log::debug('virus添加数据成功:'.$response->getBody()->getContents());
+            return true;
+        } catch (RequestException $e) {
+            Log::debug('virus添加数据失败:'.$e->getMessage());
+        }
+    }
+}

+ 2 - 0
app/Console/Kernel.php

@@ -6,6 +6,7 @@ use App\Console\Commands\Apollo;
 use App\Console\Commands\Downloads;
 use App\Console\Commands\PostStatistics;
 use App\Console\Commands\PostYesterday;
+use App\Console\Commands\VirusAdd;
 use Illuminate\Console\Scheduling\Schedule;
 use Laravel\Lumen\Console\Kernel as ConsoleKernel;
 
@@ -20,6 +21,7 @@ class Kernel extends ConsoleKernel
         Apollo::class,
         PostYesterday::class,
         Downloads::class,
+        VirusAdd::class,
         PostStatistics::class
     ];
 

+ 30 - 8
app/Repositories/Post/PostRepository.php

@@ -9,6 +9,7 @@
 
 namespace App\Repositories\Post;
 
+use App\Models\Behavior;
 use App\Models\CategoryTopic;
 use App\Models\Post;
 use App\Models\PostComment;
@@ -42,6 +43,7 @@ class PostRepository
                                 PostImgs $postImgs,
                                 PostLog $postLog,
                                 RabbitMqUtil $rabbitMqUtil,
+                                Behavior $behavior,
                                 CategoryTopic $categoryTopic,
                                 PostStatistics $postStatistics,
                                 Topic $topic)
@@ -52,6 +54,7 @@ class PostRepository
         $this->postImgs = $postImgs;
         $this->postLog = $postLog;
         $this->rabbitMqUtil = $rabbitMqUtil;
+        $this->behavior = $behavior;
         $this->categoryTopic = $categoryTopic;
         $this->topic = $topic;
         $this->postStatistics = $postStatistics;
@@ -62,15 +65,15 @@ class PostRepository
      */
     public function create($request)
     {
+
         //验证小号
-        //todo 小号
-//        $userInfo = $this->getUserInfo($request['uid']);
-//        if(!$userInfo || $userInfo['type'] != 1){
-//            return Response::create([
-//                'message'  => '所选小号信息有误',
-//                'status_code'   => 500
-//            ]);
-//        }
+        $userInfo = $this->getUserInfo($request['uid']);
+        if(!$userInfo || !$userInfo['data'] || $userInfo['data']['type'] != 1){
+            return Response::create([
+                'message'  => '所选小号信息有误',
+                'status_code'   => 500
+            ]);
+        }
         //验证话题
         $topicIdsArray = $this->topic->whereIn('id', explode(',', $request['topic_ids']))->pluck('id')->toArray();
         $topicCount = count($topicIdsArray);
@@ -150,6 +153,25 @@ class PostRepository
             foreach ($topicIdsArray as $id) {
                 Redis::zincrby('topic.user_uid' . $request['uid'], 1, $id);
             }
+
+            $virus = $this->behavior->where('behavior_identification', 'publish')->first();
+            if($virus){
+                if($post->title){
+                    $desc = $post->title;
+                }else{
+                    $desc = subtext(strip_tags($post->content), 20);
+                }
+                $this->rabbitMqUtil->push('virus_add', [
+                    'behavior_id' => $virus->virus_behavior_id,
+                    'behavior_flag' => 'publish',
+                    'post_id' => $post->id,
+                    'post_desc' => $desc,
+                    'post_cover' => $post->img,
+                    'target_id' => $post->uid,
+                    'action_id' => $post->id,
+            ]);
+            }
+
             return Response::create();
 
         } catch (QueryException $exception) {

+ 1 - 1
app/Traits/UserTrait.php

@@ -17,7 +17,7 @@ trait UserTrait
             $array = [
                 'json' => ['uid' => $uid], 'query' => [], 'http_errors' => false,'headers'=>['Authorization'=>"Bearer ".JWTAuth::getToken()]
             ];
-            return http($url,$array, true, 'get');
+            return http($url,$array, false, 'get');
         } catch (\Exception $e) {
             return [];
         }

+ 3 - 0
config/customer.tpl

@@ -3,4 +3,7 @@
 return [
     'jwt_secret' => '{jwt_secret}',
     'manage_service_url' => '{manage_service_url}',
+    'VIRUS_URL' => '{VIRUS_URL}',
+    'VIRUS_APP_ID' => '{VIRUS_APP_ID}',
+    'VIRUS_APP_SECRET ' => '{VIRUS_APP_SECRET}',
 ];