RankDataController.php 7.5 KB
<?php

namespace App\Http\Controllers\Bside\RankData;


use App\Helper\Arr;
use App\Helper\GoogleSpeedApi;
use App\Helper\QuanqiusouApi;
use App\Http\Controllers\Bside\BaseController;
use App\Http\Logic\Aside\Project\ProjectLogic;
use App\Http\Logic\Bside\RankDataLogic;
use App\Models\RankData\RankData;
use App\Models\RankData\Speed as GoogleSpeedModel;
use App\Services\BatchExportService;
use App\Utils\HttpUtils;
use GuzzleHttp\Client;
use GuzzleHttp\Promise\Utils;
use Illuminate\Support\Facades\Storage;

/**
 * Class GoogleRankController
 * @package App\Http\Controllers\Bside
 * @author zbj
 * @date 2023/5/9
 */
class RankDataController extends BaseController
{

    public function index(RankDataLogic $logic)
    {
        $data = $logic->index();
        return $this->success($data);
    }

    /**
     * 关键词排名列表
     * @param RankDataLogic $logic
     * @return \Illuminate\Http\JsonResponse
     * @author zbj
     * @date 2023/5/15
     */
    public function keywords_rank_list(RankDataLogic $logic){
        $data = $logic->keywords_rank_list();
        return $this->success($data);
    }


    /**
     * 刷新测速
     * @param ProjectLogic $projectLogic
     * @param GoogleSpeedApi $googleSpeedApi
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\AsideGlobalException
     * @throws \App\Exceptions\BsideGlobalException
     * @author zbj
     * @date 2023/5/15
     */
    public function speed(ProjectLogic $projectLogic, GoogleSpeedApi $googleSpeedApi){
        $project_id = $this->user['project_id'];
        $project = $projectLogic->getProjectInfo($project_id);
        $domain = $project['deploy_optimize']['domain'] ?? '';
        $data = $googleSpeedApi->run($domain);
        if($data){
            $model = GoogleSpeedModel::where('project_id', $project_id)->first();
            $model->project_id = $project_id;
            $model->data = $data;
            $model->updated_date = date('Y-m-d');
            $model->save();
        }else{
            $data = [];
        }
        return $this->success($data);
    }

    /**
     * 数据导出
     * @author zbj
     * @date 2023/5/15
     */
    public function export(RankDataLogic $logic){
        $lang = $this->request['lang'] ??'';
        $data = $logic->keywords_rank_list(true);
        $img_position = $video_position= false;
        foreach ($data as &$item){
            $item['lang'] = $this->request['lang'] ?: 'en';
            $item['g_text'] = RankData::gMap()[$item['g']]??'';
            $item['img_position'] = $item['img_position'] ?? '';
            $item['video_position'] = $item['video_position'] ?? '';
            foreach ($item['position'] as $date => $position){
                $item[$date] = $position;
            }
            if(!empty($item['img_position'])){
                $img_position = true;
            }
            if(!empty($item['video_position'])){
                $video_position = true;
            }
        }

        $map = [
            'keyword' => '关键词',
            'domain' => '排名网址',
            'lang' => '语言',
            'g_text' => '关键词类型',
        ];
        foreach ($data[0]['position'] as $date => $position){
            $map[$date] = $date;
        }
        $img_position && $map['img_position'] = '图片';
        $video_position && $map['video_position'] = '视频';

        //生成文件,发送到客户端
        $table = new BatchExportService($lang . "关键词数据导出");
        $file = $table->head($map)->data($data)->save();
        if (!$file) {
            throw new \Exception('文件生成失败,请重试');
        }
        $fileurl = Storage::disk('runtime')->url($file);
//        return Storage::disk('runtime')->download($file); //直接下载
        return $this->success(['url' => $fileurl]);
    }

    /**
     * 历史数据导出
     * @author zbj
     * @date 2023/5/15
     */
    public function export_history(RankDataLogic $logic, ProjectLogic $projectLogic, QuanqiusouApi $quanqiusouApi){
        $project_id = $this->user['project_id'];
        $project = $projectLogic->getProjectInfo($project_id);
        $lang = $this->request['lang'] ??'';
        $data = $quanqiusouApi->getHistoryCount($project['deploy_optimize']['api_no'], $lang);
        if($lang){
            foreach ($data['data'] as &$item){
                $item['c_date'] = date("Y-m-d",strtotime($item['c_date'] . ' +1day'));
                $item['reach'] = $item['home_cnt'] >= $data['bz_count'] ? '是' : '否';
            }
            $map = [
                'c_date' => '日期',
                'home_cnt' => '第一页',
                'reach' => '是否达标',
            ];
        }else{
            foreach ($data['data'] as &$item){
                $item['c_date'] = date("Y-m-d",strtotime($item['c_date'] . ' +1day'));
                $item['reach'] = $item['cnt_home'] >= $project['deploy_build']['keyword_num'] ? '是' : '否';
            }
            $map = [
                'c_date' => '日期',
                'cnt_first' => '排名第一',
                'cnt_home' => '第一页',
                'cnt_thirty' => '前三页',
                'cnt_fifty' => '前五页',
                'cnt_hundred' => '前十页',
                'reach' => '是否达标',
            ];
        }


        //生成文件,发送到客户端
        $table = new BatchExportService($lang . "关键词历史数据导出");
        $file = $table->head($map)->data($data['data'])->save();
        if (!$file) {
            throw new \Exception('文件生成失败,请重试');
        }
        $fileurl = Storage::disk('runtime')->url($file);
//        return Storage::disk('runtime')->download($file); //直接下载
        return $this->success(['url' => $fileurl]);
    }

    /**
     * 实时获取关键词排名
     * @author zbj
     * @date 2023/5/16
     */
    public function get_google_rank(){
        $url_arr = parse_url($this->request['url']);
        $param = [
            'keyword' => trim($this->request['keyword']),
            'url' => $url_arr['host'] ?? $url_arr['path'],
            'extend_urls' => $this->request['extend_urls'],
            'lang' => $this->request['lang'],
            'use_groups' => 2
        ];


        if ($this->request['w']) {
            $data = [
                'position' => 0,
                'image_position' => 0,
                'video_position' => 0,
            ];
            $client = new Client([
                'base_uri' => 'http://rank.waimaoq.com',
                'timeout' => '20'
            ]);

            $promises['position'] = $client->getAsync('/luminati_rank?'.Arr::query($param));
            $promises['image_position'] = $client->getAsync('/google_image?'.Arr::query($param));
            $promises['video_position'] = $client->getAsync('/google_video?'.Arr::query($param));

            // 等待所有请求响应完成
            $results  = Utils::settle($promises)->wait();
            foreach ($results as $key => $result) {
                if ($result['state'] == 'fulfilled') {
                    $res = Arr::s2a($result['value']->getBody()->getContents());
                    $data[$key] = $res['position'] ?? 0;
                }
            }
        }else{
            $data = [
                'position' => 0,
            ];
            $res = HttpUtils::get('http://rank.waimaoq.com/luminati_rank', $param);
            if ($res) {
                $res = Arr::s2a($res);
                $data['position'] = $res['position'];
            }
        }
        return $this->success($data);
    }
}