WebTrafficSpecial.php 19.0 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
<?php

namespace App\Console\Commands\WebTraffic;

use App\Helper\Arr;
use App\Models\Ai\AiBlog;
use App\Models\Product\Category;
use App\Models\Product\Product;
use App\Models\Project\OnlineCheck;
use App\Models\Project\Project;
use App\Models\Project\WebTrafficConfig;
use App\Models\WebSetting\WebLanguage;
use App\Services\ProjectServer;
use GuzzleHttp\Client;
use GuzzleHttp\Promise\Utils;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

/**
 * 网站特殊引流
 * 需要单独加流量的
 * Class Traffic
 * @package App\Console\Commands
 * @author zbj
 * @date 2023/5/18
 */
class WebTrafficSpecial extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'web_traffic_special';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '网站引流';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * google域名后缀
     * @var string[]
     */
    protected $suffix = [
        'co.jp' => '日本',
        'com.tr' => '土耳其',
        'nl' => '荷兰',
        'ru' => '俄罗斯',
        'fr' => '法国',
        'co.kr' => '韩国',
        'fi' => '芬兰',
        'be' => '比利时',
        'lt' => '立陶宛',
        'es' => '西班牙',
        'it' => '意大利',
        'com.au' => '澳大利亚',
        'no' => '挪威',
        'al' => '阿尔巴尼亚',
        'pt' => '葡萄牙',
        'lv' => '拉脱维亚',
        'hu' => '匈牙利',
        'cz' => '捷克',
        'de' => '德国',
        'ca' => '加拿大',
        'co.in' => '印度',
        'co.uk' => '英国',
        'com.vn' => '越南',
        'com.br' => '巴西',
        'co.il' => '以色列',
        'pl' => '波兰',
        'com.eg' => '埃及',
        'co.th' => '泰国',
        'sk' => '斯洛伐克',
        'ro' => '罗马尼亚',
        'com.mx' => '墨西哥',
        'com.my' => '马来西亚',
        'com.pk' => '巴基斯坦',
        'co.nz' => '新西兰',
        'co.za' => '南非',
        'com.ar' => '阿根廷',
        'com.kw' => '科威特',
        'com.sg' => '新加坡',
        'com.co' => '哥伦比亚',
        'co.id' => '印度尼西亚',
        'gr' => '希腊',
        'bg' => '保加利亚',
        'mn' => '蒙古',
        'dk' => '丹麦',
        'com.sa' => '沙特阿拉伯',
        'com.pe' => '秘鲁',
        'com.ph' => '菲律宾',
        'com.ua' => '乌克兰',
        'ge' => '格鲁吉亚',
        'ae' => '阿拉伯联合酋长国',
        'tn' => '突尼斯',
    ];

    /**
     * 概率值
     * @var int[]
     */
    protected $sjjg = [720, 280];//访问间隔占比  访问|不访问
    //访问页面类型占比  产品详情页、单页|产品分类页
    protected $ymzb = [
        'urls_cats' => 700,
        'urls_details' => 300
    ];
    protected $sdzb = [600, 200, 150, 50]; //访问页面深度占比 1页|2页|3-6页|7-11页
    protected $yddzb = [1 => 700, 2 => 300]; //移动端占比 pc|mobile
    //模拟访问来源占比 (美国)
    protected $lyzb = [
        'https://www.google.com/' => 630,
        'http://www.google.com/' => 30,
        'http://www.bing.com/' => 20,
        'https://www.bing.com/' => 5,
        'https://www.youtube.com/' => 5,
        'https://search.yahoo.com/' => 5,
        'https://www.facebook.com/' => 5,
    ];

    //俄语
    protected $eylyzb = [
        'https://www.yandex.com/' => 630,
        'https://www.google.com/' => 30,
        'http://www.google.com/' => 30,
        'http://www.bing.com/' => 20,
        'https://www.bing.com/' => 5,
        'https://www.youtube.com/' => 5,
        'https://search.yahoo.com/' => 5,
        'https://www.facebook.com/' => 5,
    ];

    protected $otherzb = [700, 300]; //模拟访问来源占比 (非美国) google.com|google.其他后缀

    protected $pc_ua = [
        0  => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11',
        1  => 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36',
        2  => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1'
    ];

    protected $mobile_ua = [
        0  => 'Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko; googleweblight) Chrome/38.0.1025.166 Mobile Safari/535.19',
    ];

    /**
     * @return bool
     */
    public function handle()
    {
        Log::channel('traffic')->info('开始运行特殊引流' );

        try {
            $this->sleep();

            $page = 1;
            while (true){
                $project_list = $this->getProjectList($page);
                if(!$project_list){
                    break;
                }
                $need_project = [];
                foreach ($project_list as $project) {
                    Log::channel('traffic')->info('开始特殊引流 project_id:' . $project['project_id']);
                    //随机引流间隔
                    $res_sjjg = $this->get_rand($this->sjjg);
                    if ($res_sjjg == 1) {
                        Log::channel('traffic')->info('随机不特殊引流 project_id:' . $project['project_id']);
                        continue;
                    }

                    $project_urls = $this->getProductUrls($project['project_id']);
                    $project_urls['home'] = $project['domain'];
                    //随机访问页面
                    $project['visit_urls'] = $this->getVisitUrls($project_urls);
                    //随机客户端
                    $project['device_port'] = $this->get_rand($this->yddzb);
                    $project['user_agent'] = $project['device_port'] == 1 ? Arr::random($this->pc_ua) : Arr::random($this->mobile_ua);

                    $need_project[] = $project;
                }
                //随机访问ip
                $ips = $this->getIpAreas(array_column($need_project, 'project_id'));

                //特殊日期 降访问率
                foreach ($need_project as $project_key => $project){
                    if(empty($ips[$project_key]['ip'])){
                        Log::channel('traffic')->info('未获取到ip project_id:' . $project['project_id']);
                        unset($need_project[$project_key]);
                        continue;
                    }
                    $diff = $ips[$project_key]['diff'];
                    //当地时间
                    $w = date('w', strtotime($diff . 'hour'));
                    $date = date('m-d', strtotime($diff . 'hour'));
                    //周五流量不变  周六周日下降20-30%  元旦圣诞下降30-50%
                    switch ($w){
                        case 0:
                        case 6:
                            //周日降20-30%
                            $rate = rand(20, 30) * 10;
                            $res = $this->get_rand([1000-$rate, $rate]);
                            break;
                        default:
                            //元旦圣诞下降30-50%
                            if(in_array($date, ['01-01', '12-25'])){
                                $rate = rand(30, 50) * 10;
                                $res = $this->get_rand([1000-$rate, $rate]);
                                break;
                            }
                            $res = 0;
                    }
                    //不访问
                    if($res == 1){
                        Log::channel('traffic')->info('特殊日期随机不特殊引流 project_id:' . $project['project_id']);
                        unset($need_project[$project_key]);
                        unset($ips[$project_key]);
                    }
                }

                //最多10层深度
                $client = new Client(['verify' => false]);
                for ($j = 0; $j < 10; $j++) {
                    for ($j = 0; $j < 10; $j++) {
                        //并发请求
                        $promises = [];
                        foreach ($need_project as $project_key => $project) {
                            if (empty($project['visit_urls'][$j])) {
                                continue;
                            }

                            $data = [
                                'ip' => $ips[$project_key]['ip'],
                                'url' => $project['visit_urls'][$j],
                                'device_port' => $project['device_port'],
                                'referrer_url' => $this->getReferer($ips[$project_key]['ip_area'], $project['lang']),
                                'user_agent' => $project['user_agent'],
                            ];
                            Log::channel('traffic')->info('traffic_special project_id:' . $project['project_id'], $data);
                            $promises[] = $client->postAsync($project['domain'] . 'api/traffic_visit', ['form_params' => $data]);
                        }

                        if($promises){
                            Utils::settle($promises)->wait();
                            //每个深度随机等待
                            sleep(rand(2, 10));
                        }
                    }
                }

                $page++;
            }
        }catch (\Exception $e){
            Log::channel('traffic')->error("special line" . $e->getLine() . ',error:' . $e->getMessage(), $e->getTrace());
        }
    }

    /**
     * 不同项目 休眠
     */
    protected function sleep(){
        sleep(rand(5,480));
    }

    /**
     * 非俄语站的引流的项目
     */
    protected function getProjectList($page){
        //设置了特殊引流的项目
        $projects = WebTrafficConfig::where('add_num', '>', 0)->pluck('add_num', 'project_id')->toArray();

        $ru_lang_id = WebLanguage::getIdByLang('ru');

        //推广项目
        $list = Project::with('domainInfo')
            ->leftJoin('gl_project_deploy_optimize as pdo', 'pdo.project_id', '=', 'gl_project.id')
            ->leftJoin('gl_project_online_check as poc', 'poc.project_id', '=', 'gl_project.id')
            ->where('pdo.domain', '>', 0)
            ->where('poc.qa_status', OnlineCheck::STATUS_ONLINE_TRUE)
            ->where('gl_project.type', Project::TYPE_TWO)
            ->where('gl_project.is_upgrade', 0)   //非升级项目
            ->where('gl_project.main_lang_id', '<>', $ru_lang_id) //非俄语站
            ->whereIn('gl_project.id', array_keys($projects))
            ->WhereRaw("NOT FIND_IN_SET(2, `level`)") //非暂停优化
            ->select(['pdo.project_id','gl_project.main_lang_id','gl_project.id'])->forPage($page, 500)->orderBy('project_id')->get();
        //其他地方在引流的域名
//        $other = DB::connection('projects_mysql')->table('projects')->where('switch', 1)->pluck('domain')->toArray();
        $other = [];
        $data = [];
        foreach ($list as $project) {

            //根据增加的次数 设置间隔
            if(Cache::get('traffic_special_' . $project['project_id'])){
                continue;
            }else{
                $ttl = 24 * 60 * 60 / ($projects[$project['project_id']] / ($this->sjjg[0] / ($this->sjjg[0] + $this->sjjg[1])));
                Cache::put('traffic_special_' . $project['project_id'], 1, $ttl);
            }

            $lang = WebLanguage::getLangById($project['main_lang_id']??1)['short'];
            if(empty($project->domainInfo['domain'])){
                continue;
            }
            //其他地方在引流就不再引流了
            if(in_array($project->domainInfo['domain'], $other)){
                continue;
            }
            $data[] = [
                'project_id' => $project['project_id'],
                'domain' => 'https://' . $project->domainInfo['domain'] . '/',
                'lang' => $lang
            ];
        }
        return $data;
    }

    /**
     * 获取产品分类、单页和详情链接
     */
    protected function getProductUrls($project_id){
        ProjectServer::useProject($project_id);
        //已发布产品分类页面
        $data['urls_cats'] = DB::connection('custom_mysql')->table('gl_product_category')
            ->where('project_id', $project_id)->where('status',  Category::STATUS_ACTIVE)
            ->whereNull('deleted_at')
            ->pluck('route','id')->toArray();

        //已发布单页面
        $data['urls_page'] = [];
//        $data['urls_page'] = DB::connection('custom_mysql')->table('gl_web_custom_template')
//            ->where('project_id', $project_id)->where('url', '<>', '404')->where('status', BCustomTemplate::STATUS_ACTIVE)->pluck('url', 'id')->toArray();

        //已发布产品详情页
        $data['urls_details'] =  DB::connection('custom_mysql')->table('gl_product')
            ->where('project_id', $project_id)->where('status', Product::STATUS_ON)
            ->whereNull('deleted_at')
            ->inRandomOrder()
            ->limit(100)
            ->pluck('route', 'id')->toArray();

        //已发布AI博客
        $ai_blog_urls = DB::connection('custom_mysql')->table('gl_ai_blog')
            ->where('project_id', $project_id)->where('status', AiBlog::STATUS_FINISH)
            ->inRandomOrder()
            ->limit(20)
            ->pluck('route', 'id')->toArray();
        foreach ($ai_blog_urls as &$ai_blog_url){
            $ai_blog_url = 'blog/' . $ai_blog_url;
        }
        //已发布AI视频
        $ai_video_urls = DB::connection('custom_mysql')->table('gl_ai_video')
            ->where('project_id', $project_id)->where('status', 2)
            ->inRandomOrder()
            ->limit(20)
            ->pluck('route', 'id')->toArray();
        foreach ($ai_video_urls as &$ai_video_url){
            $ai_video_url = 'video/' . $ai_video_url;
        }

        $data['urls_details'] = array_merge($data['urls_details'], $ai_blog_urls, $ai_video_urls);

        $data['urls_cats'] = array_merge($data['urls_cats'], $data['urls_page']);
        if(empty($data['urls_cats'])){
            $data['urls_cats'] = $data['urls_details'];
        }
        DB::disconnect('custom_mysql');
        return $data;
    }

    /**
     * 获取地区IP
     */
    protected function getIpAreas($project_ids)
    {
        //本地时间为7-23点的地区
        $h = date('H');
        $areas = [];
        $list = DB::table('gl_area_timezone')->get();
        $time_zones = [];
        foreach ($list as $v) {
            $v = (array)$v;
            $country_hour = $h + $v['diff'];
            if ($country_hour < 0) {
                $country_hour = 24 + $country_hour;
            }
            if ($country_hour >= 7 && $country_hour < 23) {
                $areas[] = $v['name'];
                $time_zones[$v['name']] = $v['diff'];
            }
        }
        $data = [];
        foreach ($project_ids as $project_id){
            //引流配置
            $config = WebTrafficConfig::getCacheInfoByProjectId($project_id);
            $main_countries = !empty($config->main_countries) ? explode(',',$config->main_countries) : [];
            $filter_countries = !empty($config->filter_countries) ? explode(',',$config->filter_countries) : [];

            //根据地区随机取该地区的IP
            $ipdata = DB::table('gl_xunpan_ipdata')->whereIn('ip_area', $areas)
                ->where(function ($query) use ($main_countries, $filter_countries){
                    if($main_countries){
                        $query->whereIn('ip_area', $main_countries);
                    }
                    if($filter_countries){
                        $query->whereNotIn('ip_area', $main_countries);
                    }
                })->inRandomOrder()->first();
            if(!$ipdata){
                $data[] = [];
                continue;
            }
            $ipdata = (array)$ipdata ?: [];
            $ipdata['diff'] = $time_zones[$ipdata['ip_area']];
            $data[] = $ipdata;
        }
        return $data;
    }

    /**
     * 概率算法
     */
    protected function get_rand($proArr) {
        $result = '';
        $proSum = array_sum($proArr);
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);
        return $result;
    }

    /**
     * 根据随机访问深度 随机获取访问页面
     */
    protected function getVisitUrls($project_urls){
        //没有分类页 就只访问首页
        if(!$project_urls['urls_cats']){
            $url[] = $project_urls['home'];
            return $url;
        }
        //随机访问深度
        $res_sdzb = $this->get_rand($this->sdzb);
        //随机访问页面类型
        $res_ymzb = $this->get_rand($this->ymzb);

        $all_url = array_merge($project_urls['urls_cats'],$project_urls['urls_details']);
        if(!$all_url){
            $url[] = $project_urls['home'];
            return $url;
        }

        $url = [];
        if($res_sdzb == 0){//深度一页
            $url[] = $project_urls[$res_ymzb] ? Arr::random($project_urls[$res_ymzb]) : '';
        }elseif($res_sdzb == 1){//深度两页
            $url[] = $project_urls['home'];
            $url[] = $project_urls[$res_ymzb] ? Arr::random($project_urls[$res_ymzb]) : '';
        }elseif($res_sdzb == 2){//深度3-6页
            $yms = rand(2,5); //随机页面数
            $url = Arr::random($all_url, $yms);
            $url = Arr::prepend($url, $project_urls['home']);//首页加到最前面去
        }elseif($res_sdzb == 3){//深度7-11页
            $yms = rand(6,10); //随机页面数
            $url = Arr::random($all_url, $yms);
            $url = Arr::prepend($url, $project_urls['home']);//首页加到最前面去
        }
        foreach ($url as &$v){
            if(!Str::contains($v, $project_urls['home'])){
                if (FALSE === strpos($v, '.htm')) {
                    $v .= '/';
                }
                $v = $project_urls['home'] . $v;
            }
        }

        Log::channel('traffic')->info('project_id:访问深度' . $res_sdzb, $url);

        return array_unique(array_filter($url));
    }

    /**
     * 获取访问来路
     */
    protected function getReferer($ip_area, $lang){

        if($lang == 'ru'){
            return $this->get_rand($this->eylyzb);
        }

        if($ip_area == '美国'){
            $referer = $this->get_rand($this->lyzb);
        }else{
            $referer = 'https://www.google.com/';

            $suffix = array_search($ip_area, $this->suffix);
            if($suffix){
                $res_qtzb = $this->get_rand($this->otherzb);
                if($res_qtzb == 1){
                    $referer = 'https://www.google.'.$suffix.'/';
                }
            }
        }
        return $referer;
    }
}