import random
from scrapy.core.downloader.handlers.http import HTTPDownloadHandler
from scrapy.core.downloader.contextfactory import ScrapyClientContextFactory


# ORIGIN_CIPHERS = 'TLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-128-GCM-SHA256:ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:RSA+AESGCM:RSA+AES'
requests_ciphers = 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES'
scrapy_ciphers = 'TLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-128-GCM-SHA256:ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:RSA+AESGCM:RSA+AES'
origin_ciphers_lists = [requests_ciphers, scrapy_ciphers]
ORIGIN_CIPHERS = random.choice(origin_ciphers_lists)


def shuffle_ciphers():
    CIPHERS = ORIGIN_CIPHERS.split(":")
    C = []
    for i in range(0, random.randint(3, len(CIPHERS))):
        C.append(random.choice(CIPHERS))
    # random.shuffle(C)
    CIPHERS = ":".join(C)
    return CIPHERS + ":!aNULL:!MD5:!DSS"


class MyHTTPDownloadHandler(HTTPDownloadHandler):
    def download_request(self, request, spider):
        tls_cliphers = shuffle_ciphers()
        self._contextFactory = ScrapyClientContextFactory(tls_ciphers=tls_cliphers)
        # # 配置TLS连接参数
        # # request.meta['download_slot'] = spider.url_
        # request.meta['ssl'] = {'verify': False}
        return super().download_request(request, spider)
