
/*=============================================================================================
	author:ZhaoJun
	version:1.0
	email:2732810281@qq.com
=============================================================================================*/


//严格模式
/*-------------------------------------------------------------------------------------------*/	
'use strict';
/*-------------------------------------------------------------------------------------------*/	
    

//爬虫常用
/*-------------------------------------------------------------------------------------------*/	    
//{headless:true, executablePath: 'C: \ Program Files (x86) \ Google \ Chrome \ Application \ chrome.exe',
//ignoreHTTPSErrors: true,
//args:['--no-sandbox','--proxy-server=socks5://127.0.0.1:1088'，"--no-sandbox","--disable-setuid-sandbox"]}
//--proxy-server="https=proxy1:80;http=socks4://baz:1080"
//--proxy-server="socks5://foobar:66"    

class base
{
    //禁止请求扩展地址[".jpg",".png"]
    //tag为假，代表阻止数组里的后缀，反之就是只允许列表的后缀
    static async denyExt(page,extArr=['.js','.css','.png','.jpg','.gif'],tag)
    {
        await page.setRequestInterception(true);
        await page.on
        (
            'request', interceptedRequest => 
            {
                var path=require('path');
                var ext=path.extname(interceptedRequest.url())
                if(!ext)
                {
                    interceptedRequest.continue();
                    return;
                }
                function make(tg)
                {
                    if(tag)
                    {
                        if(tg)
                        {
                            interceptedRequest.continue();
                        }
                        else
                        {
                            interceptedRequest.abort();
                        }
                    }
                    else
                    {
                        if(tg)
                        {
                            interceptedRequest.abort();
                        }
                        else
                        {
                            interceptedRequest.continue();
                        }
                    }
                }
                for(var index of extArr)
                {
                    if(index==ext)
                    {
                        make(true)
                        return
                    }
                }
                make()
            }
        );
    }

    static initCom(storeArr,iObj,key)
    {
        if(storeArr.length)return
        for (const k in iObj) 
        {
            const iterator=iObj[k]
            if(!iterator || !iterator.pro || !iterator[key])
            {
                continue;
            }
            for (let index = 0; index < iterator.pro; index++) 
            {
                storeArr.push(iterator[key])
            }   
        }
    }

    static  initUa()
    {
        base.initCom($SpilderUa.storePc,$SpilderUa.pc,'ua')
        base.initCom($SpilderUa.storeMobile,$SpilderUa.mobile,'ua')
    }

    static  initScreen()
    {
        base.initCom($SpilderScreen.storePc,$SpilderScreen.pc,'size')
        base.initCom($SpilderScreen.storeMobile,$SpilderScreen.mobile,'size')
    }

    static initDev()
    {
        base.initUa()
        base.initScreen()
    }
    
    static rand(arr)
    {
        return arr[(Date.now()%arr.length)]
    }

    static checkDev()
    {
        let all=$SpilderUa.rote+10
        let devs=$Sys.rand(0,all)
        //小于等于10为pc
        if(devs<10)
        {
            return base.getUa('pc')
        }
        else
        {
            return base.getUa('mobile')
        }
    }

    static getUa(tag='pc')
    {
        let randm={}
        let tagDev={}
        switch (tag) 
        {
            case 'pc':
                randm.ua=base.getVersion(base.rand($SpilderUa.storePc),tagDev)
            break;
            case 'mobile':
                randm.ua=base.getVersion(base.rand($SpilderUa.storeMobile),tagDev)
            break;
        }
        if(tagDev['@'])
        {
            randm.screen={}
            base.iphone(tagDev['@'],randm.screen)
        }
        else
        {
            randm.screen=base.getScreen(tag)
        }
        return randm
    }

    static iphone(key,obj)
    {
        switch (String(key)) 
        {
            case '5':
                obj.width=640
                obj.height=1136  
            break;
            case '6':
                obj.width=750
                obj.height=1334
            break;
            case '7':
                obj.width=750
                obj.height=1334
            break;
            case '8':
                obj.width=750
                obj.height=1334
            break;
            default:
                obj.width=1080
                obj.height=1920
            break;
        }
    }

    static getScreen(tag='pc')
    {
        switch (tag) 
        {
            case 'pc':
                return base.rand($SpilderScreen.storePc)
            break;
            case 'mobile':
                return base.rand($SpilderScreen.storeMobile)
            break;
        }
    }

    static getVersion(str,tag)
    {
        if(!str)return str
        return str.replace
        (
            /([\$|@|#])\((\d*?)\-(\d*?)\)/g,
            function(sou,tagDev,matchOne,matchTwo)
            {
                if(isNaN(matchOne) || isNaN(matchTwo))return sou
                let ver=$Sys.rand(Number(matchOne),Number(matchTwo))
                tag[tagDev]=ver
                return ver
            }
        )
    }

    static async imi(page)
    {
        let result=base.checkDev()
        //设置ua
        await page.setUserAgent(result.ua)
        // 允许运行js
        await page.setJavaScriptEnabled(true)
        // 设置页面视口的大小
        await page.setViewport(result.screen)
    }

    static async ip(host,port,ignore)
    {
        let cmd='@echo off &&'+
            'echo 【修改IE】 &&'+
            'reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyEnable /t REG_DWORD /d 1 /f &&'+
            `reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyServer /d "${host}:${port}" /f &&`+
            'rem “对于本地地址不使用代理服务器”这个勾，不会勾选上 &&'+
            `reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyOverride /t REG_SZ /d "${ignore};" /f &&`+
            'rem “对于本地地址不使用代理服务器”这个勾，会勾选上 &&'+
            `::reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyOverride /t REG_SZ /d "${ignore};<local>" /f`
        
        return await $Sys.cmd(cmd)
    }

    static init({path=false,timeout=15000,https=true,devtools=false,headless=false,args=['--no-sandbox', '--disable-setuid-sandbox']})
    {
        base.initDev()
        //--proxy-server=host:port
        //--proxy-server="socks4://foobar:1080"
        const puppeteer = require('puppeteer');
        return puppeteer.launch
        ({
            // 若是手动下载的chromium需要指定chromium地址, 默认引用地址为 /项目目录/node_modules/puppeteer/.local-chromium/
            executablePath: path,
            //设置超时时间
            timeout: timeout,
            //如果是访问https页面 此属性会忽略https错误
            ignoreHTTPSErrors: https,
            //启动浏览器的额外参数
            args:args,
            // 打开开发者工具, 当此值为true时, headless总为false
            devtools: devtools,
            // 关闭headless模式, 不会打开浏览器
            headless: headless
        })
    }
}

module.exports=base;