GeoQuestionRes.php 6.9 KB
<?php
/**
 * @remark :
 * @name   :GeoQuestionRes.php
 * @author :lyh
 * @method :post
 * @time   :2025/7/3 15:13
 */

namespace App\Console\Commands\Geo;

use App\Models\Geo\GeoPlatform;
use App\Models\Geo\GeoQuestion;
use App\Models\Geo\GeoQuestionLog;
use App\Models\Geo\GeoQuestionResult;
use App\Models\Project\Project;
use App\Services\Geo\GeoService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class GeoQuestionRes extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'geo_question_result';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'geo设置请求获取结果';

    public function handle(){
        while (true){
            $task_id = $this->getTaskId();
            if(empty($task_id)){
                echo '无数据'.PHP_EOL;
                sleep(30);
                continue;
            }
            $questionModel = new GeoQuestion();//问题
            $info = $questionModel->read(['id'=>$task_id]);
            //获取当前项目的执行频率
            $projectModel = new Project();
            $projectInfo = $projectModel->read(['id'=>$info['project_id']],['geo_status','geo_frequency']);
            if($projectInfo['geo_status'] == 0){
                $questionModel->edit(['status'=>0],['id'=>$task_id]);
                continue;
            }
            $questionArr = $info['question'];
            if(empty($questionArr)){
                echo date('Y-m-d H:i:s').'当前任务不存在问题。'.PHP_EOL;
                $questionModel->edit(['status'=>0],['id'=>$task_id]);
            }
            //获取平台信息
            $platformModel = new GeoPlatform();//平台
            $platformArr = $platformModel->selectField(['status'=>$platformModel::STATUS_ON],'en_name');
            if(empty($platformArr)){
                echo date('Y-m-d H:i:s').'请求平台为空。'.PHP_EOL;
                continue;
            }
            $geoService = new GeoService();
            $keywordArr = $info['keywords'] ?? [];
            $urlArr = $info['url'] ?? [];
            $geoResultModel = new GeoQuestionResult();
            foreach ($questionArr as $q_item){
                foreach ($platformArr as $p_item){
                    $keywords = [];//命中的关键词
                    $urls = [];//命中的网址
                    try {
                        $result_data = $geoService->setWebSearchChatAction($q_item,$p_item);
                        echo 'success:'.$result_data['code'].PHP_EOL;
                        if(isset($result_data) && $result_data['code'] == 200){
                            $keywords = $this->getKeywords($keywordArr,$result_data['text'] ?? []);
                            $urls = $this->getUrl($urlArr,$result_data['annotations'] ?? []);
                        }
                    }catch (\Exception $e){
                        echo $e->getMessage().PHP_EOL;
                        continue;
                    }
                    //查询当前是否已有执行保存记录
                    $resultInfo = $geoResultModel->read(['project_id'=>$info['project_id'],'question_id'=>$info['id'],'platform'=>$p_item,'question'=>$q_item],['id']);
                    //保存一条结果记录
                    $data = [
                        'project_id'=>$info['project_id'],
                        'question_id'=>$info['id'],
                        'platform'=>$p_item,
                        'question'=>$q_item,
                        'keywords'=>json_encode($keywords ?? [],true),//命中的关键词
                        'text'=>json_encode($result_data ?? [],true),
                        'url'=>json_encode($urls ?? [],true),//命中的网址
                    ];
                    if($resultInfo === false){
                        $geoResultModel->addReturnId($data);
                    }else{
                        $geoResultModel->edit($data,['id'=>$resultInfo['id']]);
                    }
                    $data_log = [
                        'project_id'=>$info['project_id'],
                        'question_id'=>$info['id'],
                        'platform'=>$p_item,
                        'question'=>$q_item,
                        'text'=>json_encode($result_data ?? [],true),
                    ];
                    $geoLogModel = new GeoQuestionLog();
                    $geoLogModel->addReturnId($data_log);
                }
            }
            //更新下次执行时间
            $questionModel->edit(['current_time'=>date('Y-m-d'),'next_time'=>date('Y-m-d', strtotime(date('Y-m-d') . ' +'.(int)$projectInfo['geo_frequency'].' days'))],['id'=>$info['id']]);
        }
    }

    /**
     * @remark :获取命中的url
     * @name   :getUrl
     * @author :lyh
     * @method :post
     * @time   :2025/7/3 16:38
     */
    public function getUrl($urlArr = [],$result_annotations = [],$result_text = []){
        $url = [];
        if(!empty($urlArr)){
            foreach ($urlArr as $u_item){
                if(!empty($result_text)){
                    if (str_contains($result_text, $u_item)) {
                        $url[] = $u_item;
                    }
                }
                if(!empty($result_annotations)){
                    foreach ($result_annotations as $a_item){
                        echo 'url'.$a_item['url_citation']['url'].PHP_EOL.'当前的url:'.$u_item;
                        if (str_contains($a_item['url_citation']['url'], $u_item)) {
                            $url[] = $u_item;
                        }
                    }
                }
            }
        }
        return array_values(array_unique($url));
    }

    /**
     * @remark :获取命中的关键词
     * @name   :getKeywords
     * @author :lyh
     * @method :post
     * @time   :2025/7/3 16:26
     */
    public function getKeywords($keywordArr = [],$result_text = []){
        $keywords = [];
        if(!empty($keywordArr) && !empty($result_text)){
            foreach ($keywordArr as $k_item){
                if (str_contains($result_text, $k_item)) {
                    $keywords[] = $k_item;
                }
            }
        }
        return $keywords;
    }

    /**
     * @remark :拉取任务id
     * @name   :getTaskId
     * @author :lyh
     * @method :post
     * @time   :2025/7/3 15:15
     */
    public function getTaskId(){
        $task_id = Redis::rpop('geo_question_result');
        if(empty($task_id)){
            $questionModel = new GeoQuestion();
            $ids = $questionModel->selectField(['status'=>1,'next_time'=>['<=',date('Y-m-d')]],'id');
            if(!empty($ids)){
                foreach ($ids as $id) {
                    Redis::lpush('geo_question_result', $id);
                }
            }
            $task_id = Redis::rpop('geo_question_result');
        }
        return $task_id;
    }
}