# -*- coding: utf-8 -*-
# HGhubX（黄果短剧 huangguoai.com）- T4 Python Spider
# 由 HGhubX 2.2.0 APK（Tauri 2，com.hghubx.app）逆向提取。
# API：明文 JSON，无需登录、无需加密；播放走 POST /api/videos/{id}/episodes/{ep}/playback
# 取签名 m3u8（streams.main），parse=0 直出。封面在 pic.qnlycc.cn，相对路径需补域名。
# 注意：本站与 huangdou.me 的旧“黄果短剧.py”不是同一站，故以 App 名 HGhubX 命名，避免覆盖。
# 纯标准库，init 零网络。
import json
import re
import time
import urllib.error
import urllib.parse
import urllib.request

try:
    from urllib.error import IncompleteRead
except Exception:
    IncompleteRead = None

# ---------------- 纯 Python AES（T 表实现，封面 AES-128-CBC 解密用） ----------------
# 封面在 pic.qnlycc.cn 上是 AES-128-CBC/NoPadding 整文件加密（crypto-worker.js），
# key/iv 见 crypto-image-protocol.js（公开配置）。已用真实封面验证：解密后为合法 JPEG。
_SBOX = [
    0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
    0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
    0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
    0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
    0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
    0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
    0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
    0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
    0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
    0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
    0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
    0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
    0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
    0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
    0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
    0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16]
_INV_SBOX = [0] * 256
for _i, _v in enumerate(_SBOX):
    _INV_SBOX[_v] = _i
_RCON = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d]


def _xtime(a):
    a <<= 1
    if a & 0x100:
        a ^= 0x11b
    return a & 0xff


def _mul(a, b):
    r = 0
    while b:
        if b & 1:
            r ^= a
        a = _xtime(a)
        b >>= 1
    return r


def _build_tables():
    te = [[0] * 256 for _ in range(4)]
    td = [[0] * 256 for _ in range(4)]
    for x in range(256):
        s = _SBOX[x]
        s2 = _xtime(s)
        s3 = s2 ^ s
        te[0][x] = (s2 << 24) | (s << 16) | (s << 8) | s3
        te[1][x] = (s3 << 24) | (s2 << 16) | (s << 8) | s
        te[2][x] = (s << 24) | (s3 << 16) | (s2 << 8) | s
        te[3][x] = (s << 24) | (s << 16) | (s3 << 8) | s2
        si = _INV_SBOX[x]
        m9 = _mul(si, 9)
        m11 = _mul(si, 11)
        m13 = _mul(si, 13)
        m14 = _mul(si, 14)
        td[0][x] = (m14 << 24) | (m9 << 16) | (m13 << 8) | m11
        td[1][x] = (m11 << 24) | (m14 << 16) | (m9 << 8) | m13
        td[2][x] = (m13 << 24) | (m11 << 16) | (m14 << 8) | m9
        td[3][x] = (m9 << 24) | (m13 << 16) | (m11 << 8) | m14
    return te, td


_TE, _TD = _build_tables()


def _inv_mix_word(w):
    b0 = (w >> 24) & 0xff
    b1 = (w >> 16) & 0xff
    b2 = (w >> 8) & 0xff
    b3 = w & 0xff
    return ((_mul(b0, 14) ^ _mul(b1, 11) ^ _mul(b2, 13) ^ _mul(b3, 9)) << 24) | \
           ((_mul(b0, 9) ^ _mul(b1, 14) ^ _mul(b2, 11) ^ _mul(b3, 13)) << 16) | \
           ((_mul(b0, 13) ^ _mul(b1, 9) ^ _mul(b2, 14) ^ _mul(b3, 11)) << 8) | \
           (_mul(b0, 11) ^ _mul(b1, 13) ^ _mul(b2, 9) ^ _mul(b3, 14))


def _expand_key(key):
    nk = len(key) // 4
    nr = nk + 6
    w = [list(key[i * 4:(i + 1) * 4]) for i in range(nk)]
    for i in range(nk, 4 * (nr + 1)):
        t = list(w[i - 1])
        if i % nk == 0:
            t = t[1:] + t[:1]
            t = [_SBOX[x] for x in t]
            t[0] ^= _RCON[i // nk - 1]
        elif nk > 6 and i % nk == 4:
            t = [_SBOX[x] for x in t]
        w.append([w[i - nk][j] ^ t[j] for j in range(4)])
    return w, nr


class _AES(object):
    """AES T 表实现（解密用等效逆密码，轮密钥已预变换）。"""

    def __init__(self, key):
        w, nr = _expand_key(key)
        self.nr = nr
        self.rk = [(w[i][0] << 24) | (w[i][1] << 16) | (w[i][2] << 8) | w[i][3]
                   for i in range(len(w))]
        self.drk = list(self.rk)
        for rnd in range(1, nr):
            for j in range(4):
                self.drk[4 * rnd + j] = _inv_mix_word(self.rk[4 * rnd + j])

    def _block(self, blk, decrypt=False):
        s0 = int.from_bytes(blk[0:4], "big")
        s1 = int.from_bytes(blk[4:8], "big")
        s2 = int.from_bytes(blk[8:12], "big")
        s3 = int.from_bytes(blk[12:16], "big")
        rk = self.rk
        nr = self.nr
        if not decrypt:
            t0, t1, t2, t3 = _TE
            s0 ^= rk[0]
            s1 ^= rk[1]
            s2 ^= rk[2]
            s3 ^= rk[3]
            for rnd in range(1, nr):
                o = 4 * rnd
                s0, s1, s2, s3 = (
                    t0[s0 >> 24] ^ t1[(s1 >> 16) & 0xff] ^ t2[(s2 >> 8) & 0xff] ^ t3[s3 & 0xff] ^ rk[o],
                    t0[s1 >> 24] ^ t1[(s2 >> 16) & 0xff] ^ t2[(s3 >> 8) & 0xff] ^ t3[s0 & 0xff] ^ rk[o + 1],
                    t0[s2 >> 24] ^ t1[(s3 >> 16) & 0xff] ^ t2[(s0 >> 8) & 0xff] ^ t3[s1 & 0xff] ^ rk[o + 2],
                    t0[s3 >> 24] ^ t1[(s0 >> 16) & 0xff] ^ t2[(s1 >> 8) & 0xff] ^ t3[s2 & 0xff] ^ rk[o + 3])
            o = 4 * nr
            box = _SBOX
            f0 = (((box[s0 >> 24] << 24) | (box[(s1 >> 16) & 0xff] << 16)
                   | (box[(s2 >> 8) & 0xff] << 8) | box[s3 & 0xff]) ^ rk[o])
            f1 = (((box[s1 >> 24] << 24) | (box[(s2 >> 16) & 0xff] << 16)
                   | (box[(s3 >> 8) & 0xff] << 8) | box[s0 & 0xff]) ^ rk[o + 1])
            f2 = (((box[s2 >> 24] << 24) | (box[(s3 >> 16) & 0xff] << 16)
                   | (box[(s0 >> 8) & 0xff] << 8) | box[s1 & 0xff]) ^ rk[o + 2])
            f3 = (((box[s3 >> 24] << 24) | (box[(s0 >> 16) & 0xff] << 16)
                   | (box[(s1 >> 8) & 0xff] << 8) | box[s2 & 0xff]) ^ rk[o + 3])
        else:
            t0, t1, t2, t3 = _TD
            rk = self.drk
            o = 4 * nr
            s0 ^= self.rk[o]
            s1 ^= self.rk[o + 1]
            s2 ^= self.rk[o + 2]
            s3 ^= self.rk[o + 3]
            for rnd in range(nr - 1, 0, -1):
                o = 4 * rnd
                s0, s1, s2, s3 = (
                    t0[s0 >> 24] ^ t1[(s3 >> 16) & 0xff] ^ t2[(s2 >> 8) & 0xff] ^ t3[s1 & 0xff] ^ rk[o],
                    t0[s1 >> 24] ^ t1[(s0 >> 16) & 0xff] ^ t2[(s3 >> 8) & 0xff] ^ t3[s2 & 0xff] ^ rk[o + 1],
                    t0[s2 >> 24] ^ t1[(s1 >> 16) & 0xff] ^ t2[(s0 >> 8) & 0xff] ^ t3[s3 & 0xff] ^ rk[o + 2],
                    t0[s3 >> 24] ^ t1[(s2 >> 16) & 0xff] ^ t2[(s1 >> 8) & 0xff] ^ t3[s0 & 0xff] ^ rk[o + 3])
            box = _INV_SBOX
            f0 = (((box[s0 >> 24] << 24) | (box[(s3 >> 16) & 0xff] << 16)
                   | (box[(s2 >> 8) & 0xff] << 8) | box[s1 & 0xff]) ^ rk[0])
            f1 = (((box[s1 >> 24] << 24) | (box[(s0 >> 16) & 0xff] << 16)
                   | (box[(s3 >> 8) & 0xff] << 8) | box[s2 & 0xff]) ^ rk[1])
            f2 = (((box[s2 >> 24] << 24) | (box[(s1 >> 16) & 0xff] << 16)
                   | (box[(s0 >> 8) & 0xff] << 8) | box[s3 & 0xff]) ^ rk[2])
            f3 = (((box[s3 >> 24] << 24) | (box[(s2 >> 16) & 0xff] << 16)
                   | (box[(s1 >> 8) & 0xff] << 8) | box[s0 & 0xff]) ^ rk[3])
        return (f0.to_bytes(4, "big") + f1.to_bytes(4, "big")
                + f2.to_bytes(4, "big") + f3.to_bytes(4, "big"))


_IMG_KEY = b'f5d965df75336270'
_IMG_IV = b'97b60394abc2fbe1'
_IMG_AES = _AES(_IMG_KEY)


def _img_decrypt(data):
    """封面 AES-128-CBC/NoPadding 整文件解密。"""
    if not data or len(data) % 16:
        return None
    out = bytearray()
    prev = _IMG_IV
    for i in range(0, len(data), 16):
        blk = data[i:i + 16]
        dec = _IMG_AES._block(blk, True)
        out += bytes(dec[j] ^ prev[j] for j in range(16))
        prev = blk
    return bytes(out)

_BASE = 'https://huangguoai.com'
_FALLBACK_BASE = 'https://huangguoai.ai'
_PIC = 'https://pic.qnlycc.cn'
_UA = ('Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 '
       '(KHTML, like Gecko) Chrome/120.0 Mobile Safari/537.36')
_TIMEOUT = 15

# 首页分类：前 6 个走 API，后 18 个走标签页 HTML（/tag/{slug}/?page=N）
_CLASSES = [
    ('rec', '推荐', '/api/feed/recommend'),
    ('new', '最新', '/api/videos'),
    ('today', '今日', '/api/feed/today'),
    ('orig', '黄果原创', '/api/videos?is_original=1'),
    ('duanju', '短剧', '/api/videos?cate_id=24'),
    ('manju', '漫剧', '/api/videos?cate_id=25'),
]
_TAGS = [
    ('dushi', '都市'), ('xiaoyuan', '校园'), ('gufeng', '古风'),
    ('hougong', '后宫'), ('luanlun', '乱伦'), ('muzi', '母子'),
    ('ntr', 'NTR'), ('qihuan', '奇幻'), ('wuxia', '武侠'),
    ('xianxia', '仙侠'), ('xingzhuan', '性转'), ('xitong', '系统'),
    ('dananzhu', '大男主'), ('nixi', '逆袭'), ('naodong', '脑洞'),
    ('shunv', '熟女'), ('lvmao', '绿帽'), ('xiandai', '现代'),
]

_CARD_RE = re.compile(
    r'hg-drama-card__cover-link" href="/video/(\d+)/">'
    r'<img[^>]*?data-src="([^"]+)" alt="([^"]*)"',
    re.S)
_CARD_META_RE = re.compile(
    r'hg-drama-card__score">([^<]*)</span>.*?'
    r'hg-drama-card__episode">([^<]*)</span>',
    re.S)


def _fix_cover(url):
    if not url:
        return ''
    if url.startswith('//'):
        return 'https:' + url
    if url.startswith('/'):
        return _PIC + url
    return url


def _pic_url(url):
    """封面一律走 localProxy 解密（站方图片为 AES 加密，TVBox 无法直显）。"""
    url = _fix_cover(url)
    if not url:
        return ''
    return ('http://127.0.0.1:9978/proxy?do=py&from=%s&type=pic&u=%s'
            % (urllib.parse.quote('HGhubX', safe=''),
               urllib.parse.quote(url, safe='')))


def _vod(item):
    vid = item.get('id') or ''
    title = item.get('title') or ''
    cover = _pic_url(item.get('cover') or '')
    if not vid and not title:
        return None
    ep = item.get('episode_count') or item.get('total_episodes') or 0
    fin = item.get('is_finished')
    remarks = ''
    if ep:
        remarks = '全%s集' % ep if fin else '更新至%s集' % ep
    elif item.get('score'):
        remarks = '%s分' % item.get('score')
    return {
        'vod_id': str(vid),
        'vod_name': title,
        'vod_pic': cover,
        'vod_remarks': remarks,
    }


class Spider(object):
    def __init__(self, ext=''):
        self._ext = ext

    # ---------------- HTTP ----------------

    def _http(self, url, data=None, headers=None, _retry=3):
        req_headers = {'User-Agent': _UA}
        if headers:
            req_headers.update(headers)
        body = None
        if data is not None:
            body = json.dumps(data).encode('utf-8') if not isinstance(data, (bytes, str)) else (
                data if isinstance(data, bytes) else data.encode('utf-8'))
            req_headers['Content-Type'] = 'application/json'
        for attempt in range(_retry):
            try:
                req = urllib.request.Request(url, data=body, headers=req_headers)
                with urllib.request.urlopen(req, timeout=_TIMEOUT) as resp:
                    raw = resp.read()
                    return raw.decode('utf-8', 'replace')
            except Exception:
                # IncompleteRead / RemoteDisconnected 等传输层异常：一律丢弃重发，
                # 不返回残缺内容（残缺 JSON 无法解析，残缺 HTML 也会丢卡片）
                if attempt < _retry - 1:
                    time.sleep(1.0 * (attempt + 1))
        return None

    def _api(self, path):
        for base in (_BASE, _FALLBACK_BASE):
            text = self._http(base + path)
            if text:
                try:
                    obj = json.loads(text)
                except Exception:
                    continue
                if isinstance(obj, dict) and 'data' in obj:
                    return obj['data']
                return obj
        return None

    def _api_post(self, path, data=None):
        for base in (_BASE, _FALLBACK_BASE):
            text = self._http(base + path, data=data if data is not None else {})
            if text:
                try:
                    obj = json.loads(text)
                except Exception:
                    continue
                if isinstance(obj, dict) and 'data' in obj:
                    return obj['data']
                return obj
        return None

    # ---------------- T4 ----------------

    def homeContent(self, filter=False):
        classes = [{'type_id': tid, 'type_name': name} for tid, name, _ in _CLASSES]
        classes += [{'type_id': 'tag:' + slug, 'type_name': name} for slug, name in _TAGS]
        return {'class': classes}

    def homeVideoContent(self):
        data = self._api('/api/feed/recommend?page=1&size=20')
        items = (data or {}).get('items') or [] if isinstance(data, dict) else []
        vods = []
        for it in items:
            v = _vod(it)
            if v:
                vods.append(v)
        return {'list': vods}

    def categoryContent(self, tid, pg, filter=False, extend=None):
        pg = int(pg or 1)
        if tid.startswith('tag:'):
            slug = tid[4:]
            html = self._http('%s/tag/%s/?page=%d' % (_BASE, slug, pg))
            vods = []
            if html:
                cards = _CARD_RE.findall(html)
                metas = _CARD_META_RE.findall(html)
                for i, (vid, cover, title) in enumerate(cards):
                    remarks = ''
                    if i < len(metas):
                        score, ep = metas[i]
                        remarks = (score + ' ' + ep).strip()
                    vods.append({
                        'vod_id': vid,
                        'vod_name': title,
                        'vod_pic': _pic_url(cover),
                        'vod_remarks': remarks,
                    })
            return {'list': vods, 'page': pg,
                    'pagecount': 999 if vods else pg, 'limit': 20,
                    'total': 999 if vods else 0}
        path = None
        for cid, _name, p in _CLASSES:
            if cid == tid:
                path = p
                break
        if path is None:
            path = '/api/videos'
        sep = '&' if '?' in path else '?'
        data = self._api('%s%spage=%d&size=20' % (path, sep, pg))
        items, pages = [], 1
        if isinstance(data, dict):
            items = data.get('items') or []
            pag = data.get('pagination') or {}
            pages = int(pag.get('pages') or 1)
            total = int(pag.get('total') or len(items))
        else:
            total = len(items)
        vods = []
        for it in items:
            v = _vod(it)
            if v:
                vods.append(v)
        return {'list': vods, 'page': pg, 'pagecount': pages,
                'limit': 20, 'total': total}

    def detailContent(self, ids):
        vid = str(ids[0]) if ids else ''
        data = self._api('/api/videos/%s' % vid)
        if not isinstance(data, dict):
            return {'list': []}
        eps = data.get('episodes') or []
        plays = []
        for ep in eps:
            n = ep.get('ep_num')
            t = ep.get('title') or ('第%s集' % n)
            if n is None:
                continue
            plays.append('%s$%s@%s' % (t, vid, n))
        if not plays:
            plays = ['正片$%s@1' % vid]
        tags = data.get('tags') or []
        tag_links = data.get('tag_links') or []
        vod = {
            'vod_id': vid,
            'vod_name': data.get('title') or '',
            'vod_pic': _pic_url(data.get('cover') or ''),
            'vod_content': (data.get('description') or '').strip(),
            'vod_tag': ','.join(tags) if tags else '',
            'vod_year': str(data.get('created_at') or '')[:4],
            'vod_score': str(data.get('score') or ''),
            'vod_actor': ','.join(
                [a.get('name') for a in (data.get('actors') or []) if a.get('name')]),
            'vod_director': ((data.get('author') or {}).get('name') or ''),
            'vod_remarks': ('全%s集' % data.get('episode_count')
                            if data.get('is_finished') and data.get('episode_count')
                            else '更新至%s集' % data.get('episode_count')
                            if data.get('episode_count') else ''),
            'vod_play_from': '黄果',
            'vod_play_url': '#'.join(plays),
        }
        return {'list': [vod]}

    def searchContent(self, key, quick=False, pg=1):
        pg = int(pg or 1)
        q = urllib.parse.quote(key)
        data = self._api('/api/search?q=%s&page=%d' % (q, pg))
        items, pages, total = [], 1, 0
        if isinstance(data, dict):
            items = data.get('items') or []
            pag = data.get('pagination') or {}
            pages = int(pag.get('pages') or 1)
            total = int(pag.get('total') or len(items))
        vods = []
        for it in items:
            v = _vod(it)
            if v:
                vods.append(v)
        return {'list': vods, 'page': pg, 'pagecount': pages,
                'limit': 20, 'total': total}

    def playerContent(self, flag, id, vipFlags):
        # id 格式：vid@ep
        if '@' in str(id):
            vid, ep = str(id).split('@', 1)
        else:
            vid, ep = str(id), '1'
        path = '/api/videos/%s/episodes/%s/playback' % (vid, ep)
        data = self._api_post(path, {})
        if not isinstance(data, dict) or not (data.get('streams') or {}).get('main'):
            # 兜底：不带集数的 playback
            data = self._api_post('/api/videos/%s/playback' % vid, {})
        if not isinstance(data, dict):
            return {'parse': 0, 'url': '', 'header': {}}
        streams = data.get('streams') or {}
        url = streams.get('main') or streams.get('preview') or ''
        header = {'User-Agent': _UA, 'Referer': _BASE + '/'}
        cdn = data.get('cdn') or {}
        if cdn.get('m3u8Enabled') and cdn.get('authKey') and cdn.get('authValue'):
            header[cdn['authKey']] = cdn['authValue']
            if cdn.get('app'):
                header['x-cdn-app'] = cdn['app']
        return {'parse': 0, 'url': url, 'header': header}

    def localProxy(self, param):
        # 封面解密：TVBox 调 localProxy 时传参 {type: pic, u: 原图 URL}
        if isinstance(param, str):
            try:
                param = json.loads(param)
            except Exception:
                param = {}
        if not isinstance(param, dict):
            param = {}
        url = param.get('u') or param.get('url') or param.get('src') or ''
        url = urllib.parse.unquote(str(url))
        if not url or url.startswith('http://127.0.0.1'):
            return [404, 'text/plain', b'']
        try:
            req = urllib.request.Request(url, headers={
                'User-Agent': _UA, 'Referer': _BASE + '/'})
            with urllib.request.urlopen(req, timeout=_TIMEOUT) as resp:
                body = resp.read()
        except Exception:
            return [404, 'text/plain', b'']
        if not body:
            return [404, 'text/plain', b'']
        # 已是明文图片则直回，否则 AES-128-CBC 解密
        if body[:3] == b'\xff\xd8\xff':
            return [200, 'image/jpeg', body]
        if body[:8] == b'\x89PNG\r\n\x1a\n':
            return [200, 'image/png', body]
        if body[:4] == b'RIFF' and body[8:12] == b'WEBP':
            return [200, 'image/webp', body]
        plain = _img_decrypt(body)
        if plain and plain[:3] == b'\xff\xd8\xff':
            return [200, 'image/jpeg', plain]
        if plain and plain[:8] == b'\x89PNG\r\n\x1a\n':
            return [200, 'image/png', plain]
        if plain and plain[:4] == b'RIFF' and plain[8:12] == b'WEBP':
            return [200, 'image/webp', plain]
        return [200, 'image/jpeg', plain if plain else body]
