# -*- coding: utf-8 -*-
# TVBox Python Spider: 啪啪练习室 (sgfan.ppplx72.sbs)
# 站点结构（实测 2026-11-15）:
#   全站页面 AES-256-GCM 加密：HTML 只剩一个 JS 壳，密文分块 base64 拼成，
#   key = 两个 32 字节值 XOR，iv 12 字节，AAD 变长；浏览器解密后 document.write 真 HTML。
#   分类: /list.php?id={id}&page={pg}，导航 27 个，每页 19 条
#   卡片: li > a.thumbnail[href=/video.php?id=] + img.loadi[data-original] + h5 标题
#   详情: /video.php?id={vid}，标题取 <b> 或 <title> 去 "-在线播放" 后缀；
#         播放 hls.loadSource('https://voddadaiziN.com:52866/.../index.m3u8')，直链验 #EXTM3U
#   搜索: /search.php?content={kw} 第1页；翻页走 /list.php?id={sid}&page=N，
#         sid 在第1页分页链接里（每关键词固定，翻页时重抓第1页取）
#   封面: coverXX.imgmbr.top 明文 JPEG，可直取；详情页无本片封面，vod_pic 留空
#   注意: m3u8 片头有 3 段约 10 秒广告分片，播完自动进正片（未做切除）

import re
import json
import time
import base64
import urllib.parse
import urllib.request

try:
    import requests
    _HAS_REQUESTS = True
except Exception:
    _HAS_REQUESTS = False
    requests = None

try:
    from base.spider import Spider as BaseSpider
except Exception:
    try:
        from spider import Spider as BaseSpider
    except Exception:
        class BaseSpider(object):
            pass


# ---------- 纯 Python AES-256-GCM 兜底（无 Crypto / cryptography 时用） ----------
# S 盒由伽罗瓦域运算运行时推导；AES-256 加密 14 轮 + CTR + GHASH。
# 用本站首页真实密文验证过：与 PyCryptodome 解密结果逐字节一致。


def _gf_mul(a, b):
    p = 0
    for _ in range(8):
        if b & 1:
            p ^= a
        hi = a & 0x80
        a = ((a << 1) & 0xFF) ^ (0x1B if hi else 0)
        b >>= 1
    return p


def _build_sbox():
    inv = [0] * 256
    for i in range(1, 256):
        for j in range(1, 256):
            if _gf_mul(i, j) == 1:
                inv[i] = j
                break

    def rotl8(x, n):
        return ((x << n) | (x >> (8 - n))) & 0xFF
    sbox = [0] * 256
    for i in range(256):
        a = inv[i]
        sbox[i] = (a ^ rotl8(a, 1) ^ rotl8(a, 2) ^ rotl8(a, 3) ^ rotl8(a, 4) ^ 0x63) & 0xFF
    return sbox


_SBOX = _build_sbox()
_RCON = (0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36, 0x6C, 0xD8, 0xAB, 0x4D)


def _expand_key_256(key):
    w = [0] * 60
    for i in range(8):
        w[i] = (key[4 * i] << 24) | (key[4 * i + 1] << 16) | (key[4 * i + 2] << 8) | key[4 * i + 3]
    for i in range(8, 60):
        t = w[i - 1]
        if i % 8 == 0:
            t = ((_SBOX[(t >> 16) & 0xFF] << 24) | (_SBOX[(t >> 8) & 0xFF] << 16) |
                 (_SBOX[t & 0xFF] << 8) | _SBOX[(t >> 24) & 0xFF]) ^ (_RCON[i // 8 - 1] << 24)
        elif i % 8 == 4:
            t = ((_SBOX[(t >> 24) & 0xFF] << 24) | (_SBOX[(t >> 16) & 0xFF] << 16) |
                 (_SBOX[(t >> 8) & 0xFF] << 8) | _SBOX[t & 0xFF])
        w[i] = w[i - 8] ^ t
    rk = []
    for r in range(15):
        kb = []
        for k in range(4):
            ww = w[r * 4 + k]
            kb += [(ww >> 24) & 0xFF, (ww >> 16) & 0xFF, (ww >> 8) & 0xFF, ww & 0xFF]
        rk.append(kb)
    return rk


def _aes256_encrypt_block(block, rk):
    s = [block[i] ^ rk[0][i] for i in range(16)]
    shift = (0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11)
    for r in range(1, 14):
        s = [_SBOX[x] for x in s]
        s = [s[shift[i]] for i in range(16)]
        o = [0] * 16
        for c in range(4):
            a0, a1, a2, a3 = s[4 * c], s[4 * c + 1], s[4 * c + 2], s[4 * c + 3]
            o[4 * c] = _gf_mul(2, a0) ^ _gf_mul(3, a1) ^ a2 ^ a3
            o[4 * c + 1] = a0 ^ _gf_mul(2, a1) ^ _gf_mul(3, a2) ^ a3
            o[4 * c + 2] = a0 ^ a1 ^ _gf_mul(2, a2) ^ _gf_mul(3, a3)
            o[4 * c + 3] = _gf_mul(3, a0) ^ a1 ^ a2 ^ _gf_mul(2, a3)
        s = [o[i] ^ rk[r][i] for i in range(16)]
    s = [_SBOX[x] for x in s]
    s = [s[shift[i]] for i in range(16)]
    return bytes(bytearray(s[i] ^ rk[14][i] for i in range(16)))


def _ghash_mul(x, y):
    # GF(2^128) 乘法，NIST SP 800-38D 算法 1（右移版）
    z = 0
    v = y
    for i in range(128):
        if (x >> (127 - i)) & 1:
            z ^= v
        if v & 1:
            v = (v >> 1) ^ 0xE1000000000000000000000000000000
        else:
            v >>= 1
    return z


def _ghash(h, aad, ct):
    def pad16(b):
        return b + b"\x00" * ((-len(b)) % 16)
    data = pad16(aad) + pad16(ct) + (len(aad) * 8).to_bytes(8, "big") + (len(ct) * 8).to_bytes(8, "big")
    y = 0
    for off in range(0, len(data), 16):
        y = _ghash_mul(y ^ int.from_bytes(data[off:off + 16], "big"), h)
    return y


def _aes256_gcm_decrypt_pure(key, iv, ct_with_tag, aad=b""):
    """纯 Python AES-256-GCM 解密；tag 校验失败返回 b''。"""
    if len(iv) != 12 or len(ct_with_tag) < 16:
        return b""
    ct, tag = ct_with_tag[:-16], ct_with_tag[-16:]
    rk = _expand_key_256(key)
    h = int.from_bytes(_aes256_encrypt_block(bytes(16), rk), "big")
    j0 = iv + b"\x00\x00\x00\x01"
    pt = bytearray()
    ctr = int.from_bytes(j0, "big")
    for off in range(0, len(ct), 16):
        ctr += 1
        ks = _aes256_encrypt_block(ctr.to_bytes(16, "big"), rk)
        chunk = ct[off:off + 16]
        pt += bytes(bytearray(a ^ b for a, b in zip(chunk, ks)))
    s = _ghash(h, aad, ct)
    ej0 = _aes256_encrypt_block(j0, rk)
    calc_tag = (s ^ int.from_bytes(ej0, "big")).to_bytes(16, "big")
    if calc_tag != tag:
        return b""
    return bytes(pt)


class Spider(BaseSpider):
    def init(self, extend=""):
        cfg = {}
        if extend:
            try:
                cfg = json.loads(extend) if isinstance(extend, str) else dict(extend)
            except Exception:
                cfg = {}
        if isinstance(cfg, dict):
            if cfg.get("cookie"):
                self.headers["Cookie"] = str(cfg["cookie"])
            if cfg.get("token"):
                self.headers["Authorization"] = "Bearer " + str(cfg["token"])
            try:
                self.session.headers.update(self.headers)
            except Exception:
                pass

    def __init__(self):
        super(Spider, self).__init__()
        self.site_name = "啪啪练习室"
        self.site_url = "https://sgfan.ppplx72.sbs"
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            "Referer": self.site_url + "/",
        }
        self.session = requests.Session() if _HAS_REQUESTS else None
        if self.session:
            self.session.headers.update(self.headers)
        # 导航实测 27 个分类（2026-11-15 首页导航）
        self.cats = [
            ("2372910", "精品推荐"), ("2382910", "国产传媒"), ("2392910", "探花系列"),
            ("2402910", "偷拍自拍"), ("2412910", "熟女少妇"), ("2422910", "无码专区"),
            ("2432910", "欧美性爱"), ("2442910", "颜值正义"), ("2672940", "精品网红"),
            ("2472920", "美乳巨乳"), ("2482920", "网曝事件"), ("2492920", "国产主播"),
            ("2502920", "中文字幕"), ("2512920", "制服丝袜"), ("2522920", "口交自慰"),
            ("2532920", "国产精品"), ("2542920", "大秀视频"), ("2682940", "多人群交"),
            ("2572930", "亚洲情色"), ("2582930", "强奸乱伦"), ("2592930", "伦理三级"),
            ("2602930", "女同性恋"), ("2612930", "明星换脸"), ("2622930", "A V 解说"),
            ("2632930", "少女萝莉"), ("2642930", "角色剧情"), ("2692940", "S M 调教"),
        ]

    # ---------- AES-GCM 解密（整站页面加密） ----------

    @staticmethod
    def _aes_gcm_decrypt(key, iv, ct, aad):
        """三级链：Crypto -> cryptography -> 纯 Python；全部失败返回 b''。"""
        try:
            from Crypto.Cipher import AES
            c = AES.new(key, AES.MODE_GCM, nonce=iv)
            if aad:
                c.update(aad)
            return c.decrypt_and_verify(ct[:-16], ct[-16:])
        except Exception:
            pass
        try:
            from cryptography.hazmat.primitives.ciphers.aead import AESGCM
            return AESGCM(key).decrypt(iv, ct, aad if aad else None)
        except Exception:
            pass
        try:
            return _aes256_gcm_decrypt_pure(key, iv, ct, aad or b"")
        except Exception:
            pass
        return b""

    @staticmethod
    def _scan_array(text, start):
        """从 start（指向 '[[' 后的位置）按括号深度扫出数组字面量，忽略引号内括号。
        返回含开头 '[[' 的完整字面量。"""
        depth = 2
        i = start
        in_str = False
        while i < len(text):
            ch = text[i]
            if in_str:
                if ch == "\\":
                    i += 2
                    continue
                if ch == '"':
                    in_str = False
            else:
                if ch == '"':
                    in_str = True
                elif ch == "[":
                    depth += 1
                elif ch == "]":
                    depth -= 1
                    if depth == 0:
                        return text[start - 2:i + 1]
            i += 1
        return ""

    def _decrypt_page(self, html):
        """解密 AES-GCM 加密页；非加密页原样返回；解密失败返回空串。"""
        if not html or "AES-GCM" not in html:
            return html
        try:
            # 1. 找出所有 [idx,"b64"] 数组变量（变量名每页随机）
            arrays = {}
            for m in re.finditer(r"(\w+)\s*=\s*\[\[", html):
                name = m.group(1)
                body = self._scan_array(html, m.end())
                if not body:
                    continue
                pairs = re.findall(r"\[(\d+),\"([^\"]*)\"\]", body)
                if pairs:
                    arrays[name] = pairs
            if not arrays:
                return ""
            # 2. 密文 = 分块最多的数组；单块数组 = key 材料
            ct_name = max(arrays, key=lambda k: len(arrays[k]))
            ct_pairs = arrays[ct_name]
            if len(ct_pairs) < 2:
                return ""
            ct = base64.b64decode("".join(p[1] for p in sorted(ct_pairs, key=lambda p: int(p[0]))))
            singles = {}
            for name, pairs in arrays.items():
                if len(pairs) == 1:
                    try:
                        singles[name] = base64.b64decode(pairs[0][1])
                    except Exception:
                        pass
            # 3. 按 JS 用法认角色：iv: / additionalData: / XOR 的两个解码变量
            decoded_map = {}
            for m in re.finditer(r"(\w+)\s*=\s*\w+\(\w+\((\w+)\)\)", html):
                decoded_map[m.group(1)] = m.group(2)
            iv = aad = None
            m_iv = re.search(r"iv\s*:\s*\w+\(\w+\((\w+)\)\)", html)
            if m_iv and m_iv.group(1) in singles:
                iv = singles[m_iv.group(1)]
            m_aad = re.search(r"additionalData\s*:\s*\w+\(\w+\((\w+)\)\)", html)
            if m_aad and m_aad.group(1) in singles:
                aad = singles[m_aad.group(1)]
            key_parts = []
            m_xor = re.search(r"(\w+)\[\w+\]\s*\^\s*(\w+)\[\w+\]", html)
            if m_xor:
                for dv in (m_xor.group(1), m_xor.group(2)):
                    av = decoded_map.get(dv)
                    if av and av in singles:
                        key_parts.append(singles[av])
            # 4. 兜底：按长度认（32 字节=key 两半，12 字节=iv，其余=AAD）
            if len(key_parts) != 2 or iv is None:
                b32 = [v for v in singles.values() if len(v) == 32]
                b12 = [v for v in singles.values() if len(v) == 12]
                rest = [v for v in singles.values() if len(v) not in (32, 12)]
                if len(key_parts) != 2:
                    if len(b32) < 2:
                        return ""
                    key_parts = b32[:2]
                if iv is None:
                    if not b12:
                        return ""
                    iv = b12[0]
                if aad is None:
                    aad = rest[0] if rest else b""
            if aad is None:
                aad = b""
            key = bytes(a ^ b for a, b in zip(key_parts[0], key_parts[1]))
            pt = self._aes_gcm_decrypt(key, iv, ct, aad)
            if not pt:
                return ""
            return pt.decode("utf-8", errors="ignore")
        except Exception:
            return ""

    # ---------- 请求层 ----------

    def _fetch(self, url, timeout=15):
        for _ in range(3):
            try:
                raw = ""
                if self.session:
                    r = self.session.get(url, headers=self.headers, timeout=timeout,
                                         proxies=self.session.proxies or None)
                    if r.status_code == 200:
                        raw = r.text
                if not raw:
                    req = urllib.request.Request(url, headers=self.headers)
                    with urllib.request.urlopen(req, timeout=timeout) as resp:
                        raw = resp.read().decode("utf-8", errors="ignore")
                if raw:
                    dec = self._decrypt_page(raw)
                    if dec:
                        return dec
                    # 非加密页直接返回原文（_decrypt_page 已原样返回）
                    if "AES-GCM" not in raw:
                        return raw
            except Exception:
                time.sleep(0.5)
        return ""

    def _abs(self, path):
        if not path:
            return ""
        path = str(path).strip()
        if path.startswith("http://") or path.startswith("https://"):
            return path
        if path.startswith("//"):
            return "https:" + path
        return urllib.parse.urljoin(self.site_url + "/", path)

    @staticmethod
    def _clean(s):
        if not s:
            return ""
        s = re.sub(r"<[^>]+>", "", s)
        for k, v in (("&amp;", "&"), ("&lt;", "<"), ("&gt;", ">"), ("&nbsp;", " "),
                     ("&quot;", '"'), ("&#039;", "'")):
            s = s.replace(k, v)
        return re.sub(r"\s+", " ", s).strip()

    # ---------- 解析 ----------

    def _parse_cards(self, html):
        cards = []
        seen = set()
        if not html:
            return cards
        for blk in re.findall(r"<li>(.*?)</li>", html, re.S | re.I):
            lm = re.search(r"href=[\"'](/video\.php\?id=(\d+))[\"']", blk, re.I)
            if not lm:
                continue
            vid = lm.group(2)
            if vid in seen:
                continue
            seen.add(vid)
            title = ""
            tm = re.search(r"<h5[^>]*>.*?<a[^>]*>(.*?)</a>", blk, re.S | re.I)
            if tm:
                title = self._clean(tm.group(1))
            if not title or len(title) < 2:
                continue
            pic = ""
            pm = re.search(r"data-original=[\"']([^\"'\s]+)[\"']", blk, re.I)
            if pm and "loading.svg" not in pm.group(1):
                pic = self._abs(pm.group(1))
            else:
                pm2 = re.search(r"<img[^>]+src=[\"']([^\"'\s]+)[\"']", blk, re.I)
                if pm2 and not pm2.group(1).startswith("data:") and "loading.svg" not in pm2.group(1):
                    pic = self._abs(pm2.group(1))
            remark = ""
            rm = re.search(r'<p[^>]*class=["\']vodtitle["\'][^>]*>([^<]*?)\s*-', blk, re.I)
            if rm:
                remark = self._clean(rm.group(1))
            cards.append({
                "vod_id": vid,
                "vod_name": title,
                "vod_pic": pic,
                "vod_remarks": remark,
            })
        return cards

    @staticmethod
    def _page_info(html, pg):
        """从标题“共N条数据,当前X/M页”取总数与总页数；取不到则从尾页链接取。"""
        total = 0
        pagecount = pg
        if html:
            tm = re.search(r"共(\d+)条数据,当前\d+/(\d+)页", html)
            if tm:
                total = int(tm.group(1))
                pagecount = int(tm.group(2))
            else:
                mx = 0
                for pm in re.finditer(r"page=(\d+)", html):
                    try:
                        mx = max(mx, int(pm.group(1)))
                    except Exception:
                        pass
                if mx > pg:
                    pagecount = mx
        return total, pagecount

    @staticmethod
    def _extract_play(html):
        if not html:
            return ""
        m = re.search(r"loadSource\(\s*['\"]([^'\"]+\.m3u8[^'\"]*)['\"]", html, re.I)
        if m:
            return m.group(1).replace("\\/", "/")
        for pat in (r"['\"](https?://[^'\"\s]+\.m3u8[^'\"]*)['\"]",
                    r"['\"](https?://[^'\"\s]+\.mp4[^'\"]*)['\"]"):
            m = re.search(pat, html, re.I)
            if m:
                return m.group(1).replace("\\/", "/")
        return ""

    @staticmethod
    def _search_sid(html):
        """搜索第1页分页链接里的会话 id：/list.php?id={sid}&page>=2。"""
        if not html:
            return ""
        m = re.search(r"/list\.php\?id=(\d+)&page=[2-9]\d*", html)
        return m.group(1) if m else ""

    def _probe_media(self, url):
        """验直链是否真实可用（parse:0 前的门禁）。
        m3u8：跟随跳转后读前 1KB，含 #EXTM3U 才算真；mp4：HEAD 200 且
        Content-Type 带 video 才算真。Session 与 urllib 两条路各试 1 次
        （CDN 偶发断连，换路重试能过），仍失败算不可用。"""
        for _ in range(2):
            if self._probe_session(url):
                return True
            if self._probe_urllib(url):
                return True
            time.sleep(0.5)
        return False

    def _probe_session(self, url):
        if not self.session:
            return False
        u = (url or "").lower()
        try:
            if ".m3u8" in u:
                r = self.session.get(url, headers=self.headers, timeout=10, stream=True,
                                     proxies=self.session.proxies or None)
                try:
                    head = next(r.iter_content(1024), b"")
                finally:
                    r.close()
                return r.status_code == 200 and b"#EXTM3U" in head
            if ".mp4" in u:
                r = self.session.head(url, headers=self.headers, timeout=10, allow_redirects=True,
                                      proxies=self.session.proxies or None)
                return r.status_code == 200 and "video" in (r.headers.get("Content-Type") or "").lower()
        except Exception:
            return False
        return False

    def _probe_urllib(self, url):
        u = (url or "").lower()
        try:
            if ".m3u8" in u:
                req = urllib.request.Request(url, headers=self.headers)
                with urllib.request.urlopen(req, timeout=10) as resp:
                    return resp.status == 200 and b"#EXTM3U" in resp.read(1024)
            if ".mp4" in u:
                req = urllib.request.Request(url, headers=self.headers, method="HEAD")
                with urllib.request.urlopen(req, timeout=10) as resp:
                    return resp.status == 200 and "video" in (resp.headers.get("Content-Type") or "").lower()
        except Exception:
            return False
        return False

    # ---------- 六核心方法 ----------

    def getName(self):
        return self.site_name

    def homeContent(self, filter):
        classes = [{"type_id": tid, "type_name": name} for tid, name in self.cats]
        seen = set(tid for tid, _ in self.cats)
        # 导航活抓作补充：站内新增分类自动进来
        html = self._fetch(self.site_url + "/index.php")
        if html:
            for m in re.finditer(r'href=["\']/list\.php\?id=(\d+)&page=1["\'][^>]*>([^<]{1,15})</a>', html):
                tid, name = m.group(1), self._clean(m.group(2))
                if tid not in seen and name:
                    seen.add(tid)
                    classes.append({"type_id": tid, "type_name": name})
        return {"class": classes, "filters": {}}

    def homeVideoContent(self):
        html = self._fetch(self.site_url + "/")
        return {"list": self._parse_cards(html)}

    def categoryContent(self, tid, pg, filter, extend):
        try:
            pg = int(pg)
        except Exception:
            pg = 1
        if pg < 1:
            pg = 1
        url = "%s/list.php?id=%s&page=%d" % (self.site_url, tid, pg)
        html = self._fetch(url)
        items = self._parse_cards(html)
        total, pagecount = self._page_info(html, pg)
        if not items and pagecount <= pg:
            pagecount = pg
        elif items and pagecount <= pg:
            pagecount = pg + 1
        return {
            "list": items,
            "page": pg,
            "pagecount": pagecount,
            "limit": len(items),
            "total": total
        }

    def detailContent(self, ids):
        vid = str(ids[0]) if ids else ""
        m = re.search(r"(\d+)", vid)
        vid = m.group(1) if m else vid
        url = "%s/video.php?id=%s" % (self.site_url, vid)
        html = self._fetch(url)

        title = ""
        tm = re.search(r"<div[^>]*>\s*<b>([^<]{2,120})</b>\s*</div>", html, re.S)
        if tm:
            title = self._clean(tm.group(1))
        if not title:
            tm = re.search(r"<title>(.*?)</title>", html, re.S | re.I)
            if tm:
                title = self._clean(tm.group(1).replace("-在线播放", ""))

        play_url = self._extract_play(html)
        if play_url and self._probe_media(play_url):
            vod_play_url = "正片$" + play_url
        else:
            # 拿不到真直链：回详情页走网页解析，不造假直链
            vod_play_url = "正片$" + url

        vod = {
            "vod_id": vid,
            "vod_name": title or vid,
            "vod_pic": "",
            "vod_play_from": "啪啪练习室",
            "vod_play_url": vod_play_url
        }
        return {"list": [vod]}

    def playerContent(self, flag, id, vipFlags):
        raw = str(id)
        url = raw.rsplit("$", 1)[-1] if "$" in raw else raw
        url = self._abs(url)
        if self.isVideoFormat(url) and self._probe_media(url):
            return {"parse": 0, "playUrl": "", "url": url, "header": self.headers}
        return {"parse": 1, "playUrl": "", "url": url, "header": self.headers}

    def searchContent(self, key, quick, pg="1"):
        try:
            pg = int(pg)
        except Exception:
            pg = 1
        if pg < 1:
            pg = 1
        kw = urllib.parse.quote(str(key))
        html = self._fetch("%s/search.php?content=%s" % (self.site_url, kw))
        total, pagecount = self._page_info(html, pg)
        if pg > 1:
            # 搜索翻页不走 search.php?page=（实测回第1页），走第1页分页链接里的 sid
            sid = self._search_sid(html)
            if sid:
                html = self._fetch("%s/list.php?id=%s&page=%d" % (self.site_url, sid, pg))
                total, pagecount = self._page_info(html, pg)
            else:
                return {"list": [], "page": pg, "pagecount": pagecount,
                        "limit": 0, "total": total}
        items = self._parse_cards(html)
        return {
            "list": items,
            "page": pg,
            "pagecount": pagecount,
            "limit": len(items),
            "total": total
        }

    def isVideoFormat(self, url):
        u = str(url or "").lower()
        return ".m3u8" in u or ".mp4" in u

    def manualVideoCheck(self):
        return False

    def localProxy(self, params):
        if isinstance(params, str):
            try:
                params = json.loads(params)
            except Exception:
                params = {}
        if not isinstance(params, dict):
            params = {}

        t = params.get("type", "")
        if t == "pic":
            url = urllib.parse.unquote(params.get("url", ""))
            if not url or url.startswith("http://127.0.0.1"):
                return [404, "text/plain", b"", ""]
            content = b""
            try:
                if self.session:
                    r = self.session.get(url, headers=self.headers, timeout=10,
                                         proxies=self.session.proxies or None)
                    if r.status_code == 200:
                        content = r.content
                if not content:
                    req = urllib.request.Request(url, headers=self.headers)
                    with urllib.request.urlopen(req, timeout=10) as resp:
                        content = resp.read()
            except Exception:
                return [404, "text/plain", b"", ""]
            if not content:
                return [404, "text/plain", b"", ""]
            if content[:3] == b"\xff\xd8\xff":
                return [200, "image/jpeg", content, ""]
            elif content[:8] == b"\x89PNG\r\n\x1a\n":
                return [200, "image/png", content, ""]
            elif content[:4] == b"RIFF" and content[8:12] == b"WEBP":
                return [200, "image/webp", content, ""]
            elif content[:3] == b"GIF":
                return [200, "image/gif", content, ""]
            return [200, "application/octet-stream", content, ""]

        return [200, "text/plain", b"", ""]

    def destroy(self):
        pass
