# -*- coding: utf-8 -*-
import logging
from scrapy import signals
import sys, os
from func_timeout import func_set_timeout
sys.path.append(os.path.dirname(os.path.dirname(sys.path[0])))  # 上级目录


class AddLastEventIdMiddleware:
    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    @func_set_timeout(3)
    def get_cookie(self, data):
        import execjs
        import platform
        logging.info(f"请求参数{data}")
        cwd = os.path.dirname(__file__)
        # with open(cwd + '\\js\\17encrypt.js', 'r') as f:
        if "Windows" == platform.system():
            with open(cwd + '\\js\\17encrypt.js', 'r') as f:
                ctx = execjs.compile(f.read())
                anti_content = ctx.call('getCookie', data)
                return anti_content
        else:
            with open(cwd + '/js/17encrypt.js', 'r') as f:
                ctx = execjs.compile(f.read())
                anti_content = ctx.call('getCookie', data)
                return anti_content

    def process_request(self, request, spider):
        request.cookies = {"Last-Event-ID": self.get_cookie(request.meta.get("fdata"))}
        logging.info(f"添加Last-Event-ID参数:{request.cookies.get('Last-Event-ID')[0:10]}")

    def process_response(self, request, response, spider):
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


