Spaces:
Running
Running
Download mc_patch.py from langhua1998/douyin-proxy: direct link, hf CLI and curl.
- Browser
- Download file 30 kB
-
https://huggingface.co/spaces/langhua1998/douyin-proxy/resolve/main/mc_patch.py
- Command line
-
hf download hf://spaces/langhua1998/douyin-proxy/mc_patch.py
-
curl -L -o mc_patch.py https://huggingface.co/spaces/langhua1998/douyin-proxy/resolve/main/mc_patch.py
30 kB
| """改 MediaCrawler(参数是它的目录): | |
| 1. config/base_config.py:不连本机 Chrome(CDP),用 Playwright 自带的 Chromium;有界面(服务器上跑在 Xvfb 虚拟屏幕里, | |
| 云电脑上跑在网页桌面里);不抓评论;保存登录状态。 | |
| 2. media_platform/douyin/core.py:打开抖音首页只等页面骨架出来(domcontentloaded),最多 60 秒。默认等整页 load, | |
| 抖音首页一直在加载视频,30 秒等不到就超时退出(关键词搜索第一次就死在这)。 | |
| 3. main.py 最前面 import xiaoju_retry(这里写进去的):页面在跳转时读页面(page.evaluate)会报「Execution context was | |
| destroyed」直接退出——抖音首页打开后自己还会再跳一次,MediaCrawler 读 localStorage、算签名的地方都会撞上。改成等新页面出来再读。 | |
| 打开网页(page.goto)连不上也等一会儿再打开,最多 3 次。 | |
| 4. media_platform/douyin/core.py:用 cookie 登录时,打开抖音之前先把 cookie 放进浏览器。它原来是发现没登录才去点页面上的 | |
| 「登录」按钮、弹出登录框后再塞 cookie;Space 重启后浏览器档案是空的,页面上又找不到那个按钮,等 30 秒就退出了。 | |
| media_platform/douyin/login.py:点不到「登录」按钮不再直接退出(cookie 已经放进去了)。 | |
| client.py、login.py 判断「已登录」:有 sessionid cookie 也算(它只认 LOGIN_STATUS=1 和 localStorage, | |
| 扫码登录存下的 cookie 里没有 LOGIN_STATUS,空的浏览器档案里也没有 localStorage)。 | |
| 5. store/douyin/__init__.py:作品记录里多存作者的 sec_uid 和昵称(它默认把昵称打码、作者只存散列)—— | |
| 关键词搜索出来的作品要交频道主审核,他得认得出是不是自己小号发的。 | |
| 6. media_platform/douyin/media.py:视频地址挑最高清的一档。它原来先拿 play_addr_h264(默认播放档,常常不是最高清), | |
| bit_rate(各档清晰度的列表)只在前面都没有时才兜底。改成先从 bit_rate 里挑:分辨率最高;一样高的先要 H.264 | |
| (哪里都能播),再比码率。bit_rate 里没有能用的再按它原来的顺序。 | |
| 7. 快手(store/kuaishou/__init__.py):作品记录里多存作者 id、昵称(认小号用),和最高清那档的视频地址 best_play_url | |
| (它原来只存 photoUrl,默认档)——从 videoResource.h264/hevc、manifest 的各档里挑分辨率最高的,一样高先要 H.264。 | |
| media_platform/kuaishou/core.py:打开快手首页只等页面骨架(domcontentloaded),最多 60 秒,免得一直加载视频等到超时; | |
| 启动浏览器不指定 channel="chrome"(要装谷歌 Chrome,云电脑上没有),和抖音一样用 Playwright 自带的 Chromium。 | |
| 8. main.py 最前面 import xiaoju_net(这里写进去的):环境变量 XIAOJU_TCP_MSS 有值时,新建的 TCP 连接在连之前说好 | |
| 每个包最多这么多字节(TCP MSS)。从美国的 Codespace 连快手,服务器发回来的大包在路上被丢、加密握手超时, | |
| 说好了包小服务器就只发小包。包小了偶尔还是会卡(四次里一次),XIAOJU_CONNECT_RETRIES 有值时 httpx | |
| 连不上(建连接、加密握手超时)就换个连接重连这么多次——MediaCrawler 自己一个请求失败整个就退出了。 | |
| 浏览器是另一个程序,这两样管不到:XIAOJU_BROWSER_RELAY=1 时浏览器的 https 连接交给本进程里的中转站, | |
| 中转站限包大小、对方没回音就换连接重发(详见 NET_MODULE)。streamer/ks_login.py 也 import 它。 | |
| cloud/run.sh ks 设成 536、5、1;都没设就什么都不改。 | |
| 9. 只抓最近几天(media_platform/douyin/client.py、media_platform/kuaishou/client.py):环境变量 XIAOJU_SINCE(秒) | |
| 有值时,翻主页只要那之后发的;主页按发布时间从新到旧排(置顶的在最前面),一页最后一条已经比界限早就不再往下翻。 | |
| 同步小号、每天的自动同步只要最近 7 天的,不再把每个小号整个主页从头翻一遍。 | |
| 10. 搜索排序(media_platform/douyin/core.py):环境变量 XIAOJU_SORT(0 综合、1 最多赞、2 最新发布)、XIAOJU_PUBLISH_TIME | |
| (0 不限、1 一天内、7 一周内、180 半年内)有值时按它搜。它原来只认配置里的发布时间、排序写死综合; | |
| 每天的关键词自动搜索要「最新发布、一周内」,不然天天搜到的都是同一批热门的。 | |
| python mc_patch.py <MediaCrawler 目录> | |
| """ | |
| import os | |
| import re | |
| import sys | |
| SETTINGS = {'ENABLE_CDP_MODE': 'False', 'HEADLESS': 'False', 'ENABLE_GET_COMMENTS': 'False', 'SAVE_LOGIN_STATE': 'True'} | |
| STORE_ANCHOR = '"source_keyword": source_keyword_var.get(),' | |
| STORE_EXTRA = ('"author_sec_uid": user_info.get("sec_uid", ""), # 小橘视频:审核时认账号\n' | |
| ' "author_nickname": user_info.get("nickname", ""),') | |
| def patch(text): | |
| for k, v in SETTINGS.items(): | |
| text, n = re.subn(rf'^{k} = .*$', f'{k} = {v}', text, flags=re.M) | |
| if n != 1: | |
| raise SystemExit(f'MediaCrawler 配置里找不到 {k}(上游改了格式?)') | |
| return text | |
| MEDIA_ANCHOR = ' for key in _VIDEO_ADDR_KEYS:\n' | |
| MEDIA_FUNC_ANCHOR = 'def extract_video_urls(' | |
| MEDIA_BEST = '''def _xiaoju_best(video_item): | |
| """小橘视频:bit_rate 里挑最高清的一档——分辨率最高;一样高的先要 H.264(哪里都能播),再比码率""" | |
| best, best_key = [], None | |
| for entry in video_item.get("bit_rate") or []: | |
| if not isinstance(entry, dict): | |
| continue | |
| addr = entry.get("play_addr") if isinstance(entry.get("play_addr"), dict) else {} | |
| urls = _url_list_of(addr) | |
| if not urls or str(entry.get("format") or "mp4").lower() != "mp4": | |
| continue | |
| try: | |
| pixels = int(addr.get("width") or 0) * int(addr.get("height") or 0) | |
| rate = int(entry.get("bit_rate") or 0) | |
| except (TypeError, ValueError): | |
| continue | |
| h265 = bool(entry.get("is_h265") or entry.get("is_bytevc1")) | |
| key = (pixels, not h265, rate) | |
| if best_key is None or key > best_key: | |
| best, best_key = list(reversed(urls)), key | |
| return best | |
| ''' | |
| MEDIA_USE = (' best = _xiaoju_best(video_item) # 小橘视频:先挑最高清的一档\n' | |
| ' if best:\n' | |
| ' return best\n\n') | |
| def patch_media(text): | |
| if '_xiaoju_best' in text: | |
| return text | |
| if text.count(MEDIA_ANCHOR) != 1 or text.count(MEDIA_FUNC_ANCHOR) != 1: | |
| raise SystemExit('MediaCrawler 的抖音 media.py 里找不到挑视频地址的地方(上游改了格式?)') | |
| text = text.replace(MEDIA_FUNC_ANCHOR, MEDIA_BEST + MEDIA_FUNC_ANCHOR) | |
| return text.replace(MEDIA_ANCHOR, MEDIA_USE + MEDIA_ANCHOR) | |
| KS_STORE_ANCHOR = '"source_keyword": source_keyword_var.get(),' | |
| KS_STORE_EXTRA = ('"author_id": str(user_info.get("id", "")), # 小橘视频:认小号\n' | |
| ' "author_nickname": user_info.get("name", ""),\n' | |
| ' "best_play_url": _xiaoju_best_url(photo_info),') | |
| KS_IMPORT_ANCHOR = 'from ._store_impl import *\n' | |
| KS_BEST = ''' | |
| def _xiaoju_best_url(photo): | |
| """小橘视频:快手作品各档清晰度里挑最高的——分辨率最高;一样高先要 H.264(哪里都能播),再比码率""" | |
| if not isinstance(photo, dict): | |
| return "" | |
| best, best_key = "", None | |
| resource = photo.get("videoResource") if isinstance(photo.get("videoResource"), dict) else {} | |
| sets = [(resource.get("h264"), False), (resource.get("hevc"), True), (photo.get("manifest"), None)] | |
| for res, hevc in sets: | |
| if not isinstance(res, dict): | |
| continue | |
| for adaptation in res.get("adaptationSet") or []: | |
| if not isinstance(adaptation, dict): | |
| continue | |
| codec = str(adaptation.get("codecs") or "").lower() | |
| is_hevc = hevc if hevc is not None else ("hev" in codec or "hvc" in codec) | |
| for rep in adaptation.get("representation") or []: | |
| if not isinstance(rep, dict) or not isinstance(rep.get("url"), str) or not rep["url"]: | |
| continue | |
| try: | |
| pixels = int(rep.get("width") or 0) * int(rep.get("height") or 0) | |
| rate = int(rep.get("avgBitrate") or rep.get("maxBitrate") or 0) | |
| except (TypeError, ValueError): | |
| continue | |
| key = (pixels, not is_hevc, rate) | |
| if best_key is None or key > best_key: | |
| best, best_key = rep["url"], key | |
| return best or photo.get("photoUrl") or photo.get("photoH265Url") or "" | |
| ''' | |
| KS_GOTO_OLD = 'await self.context_page.goto(f"{self.index_url}?isHome=1")' | |
| KS_GOTO_NEW = 'await self.context_page.goto(f"{self.index_url}?isHome=1", wait_until="domcontentloaded", timeout=60000)' | |
| def patch_ks_store(text): | |
| if '_xiaoju_best_url' in text: | |
| return text | |
| if text.count(KS_STORE_ANCHOR) != 1 or text.count(KS_IMPORT_ANCHOR) != 1: | |
| raise SystemExit('MediaCrawler 的快手存储里找不到要改的地方(上游改了格式?)') | |
| text = text.replace(KS_IMPORT_ANCHOR, KS_IMPORT_ANCHOR + KS_BEST) | |
| return text.replace(KS_STORE_ANCHOR, KS_STORE_ANCHOR + '\n ' + KS_STORE_EXTRA) | |
| def patch_ks_goto(text): | |
| if KS_GOTO_NEW in text: | |
| return text | |
| if KS_GOTO_OLD not in text: | |
| raise SystemExit('MediaCrawler 的快手 core.py 里找不到打开首页那一行(上游改了格式?)') | |
| return text.replace(KS_GOTO_OLD, KS_GOTO_NEW) | |
| def patch_store(text): | |
| if 'author_sec_uid' in text: | |
| return text | |
| if text.count(STORE_ANCHOR) != 1: | |
| raise SystemExit('MediaCrawler 的抖音存储里找不到 source_keyword 那一行(上游改了格式?)') | |
| return text.replace(STORE_ANCHOR, STORE_ANCHOR + '\n ' + STORE_EXTRA) | |
| GOTO_OLD = 'await self.context_page.goto(self.index_url)' | |
| GOTO_NEW = 'await self.context_page.goto(self.index_url, wait_until="domcontentloaded", timeout=60000)' | |
| NEW_PAGE = ' self.context_page = await self.browser_context.new_page()\n' | |
| COOKIES_FIRST = ( | |
| ' if config.LOGIN_TYPE == "cookie" and config.COOKIES: # 小橘视频:先把存着的登录 cookie 放进浏览器\n' | |
| ' await self.browser_context.add_cookies([\n' | |
| ' {"name": k, "value": v, "domain": ".douyin.com", "path": "/"}\n' | |
| ' for k, v in utils.convert_str_cookie_to_dict(config.COOKIES).items()])\n') | |
| CLICK_OLD = ' await login_button_ele.click()\n' | |
| CLICK_NEW = (' try: # 小橘视频:点不到也不退出(用 cookie 登录时 cookie 已经放进去了)\n' | |
| ' await login_button_ele.click(timeout=5000)\n' | |
| ' except Exception as e:\n' | |
| ' utils.logger.error(f"[DouYinLogin.popup_login_dialog] no login button: {e}")\n') | |
| def patch_login_click(text): | |
| if 'click(timeout=5000)' in text: | |
| return text | |
| if text.count(CLICK_OLD) != 1: | |
| raise SystemExit('MediaCrawler 抖音 login.py 里找不到点「登录」那一行(上游改了格式?)') | |
| return text.replace(CLICK_OLD, CLICK_NEW) | |
| def patch_login_state(text): | |
| """client.py 的 pong 和 login.py 的 check_login_state:有 sessionid 也算登录了""" | |
| if 'xiaoju: sessionid' in text: | |
| return text | |
| cond = 'cookie_dict.get("LOGIN_STATUS") == "1"' | |
| wider = '(cookie_dict.get("LOGIN_STATUS") == "1" or bool(cookie_dict.get("sessionid")))' | |
| n = 0 | |
| for old, new in ((f'return {cond}', f'return {wider} # xiaoju: sessionid'), | |
| (f'if {cond}:', f'if {wider}: # xiaoju: sessionid')): | |
| if old in text: | |
| text = text.replace(old, new) | |
| n += 1 | |
| if not n: | |
| raise SystemExit('MediaCrawler 里找不到判断 LOGIN_STATUS 那一行(上游改了格式?)') | |
| return text | |
| def patch_goto(text): | |
| if GOTO_NEW not in text: | |
| if text.count(GOTO_OLD) != 1: | |
| raise SystemExit('MediaCrawler 抖音 core.py 里找不到打开首页那一行(上游改了格式?)') | |
| text = text.replace(GOTO_OLD, GOTO_NEW) | |
| if COOKIES_FIRST not in text: | |
| if text.count(NEW_PAGE) != 1: | |
| raise SystemExit('MediaCrawler 抖音 core.py 里找不到新开页面那一行(上游改了格式?)') | |
| text = text.replace(NEW_PAGE, COOKIES_FIRST + NEW_PAGE) | |
| return text | |
| RETRY_MODULE = '''"""小橘视频加的:页面在跳转时 page.evaluate 等新页面出来再试(最多 5 次),不直接退出; | |
| 打开网页(page.goto)连不上(net::ERR_…、超时)等一会儿再打开,最多 3 次——云电脑连快手偶尔还是会卡, | |
| MediaCrawler 自己只打开一次,打不开整个就退出了。net::ERR_ABORTED 不算(是页面自己又跳走了)""" | |
| import asyncio | |
| from playwright.async_api import Page | |
| _evaluate = Page.evaluate | |
| GONE = ('Execution context was destroyed', 'Cannot find context', 'navigation') | |
| async def evaluate(self, expression, arg=None): | |
| for i in range(6): | |
| try: | |
| return await _evaluate(self, expression, arg) | |
| except Exception as e: # noqa: BLE001 | |
| if i == 5 or not any(g in str(e) for g in GONE): | |
| raise | |
| try: | |
| await self.wait_for_load_state('domcontentloaded', timeout=15000) | |
| except Exception: # noqa: BLE001 | |
| pass | |
| await asyncio.sleep(1) | |
| Page.evaluate = evaluate | |
| _goto = Page.goto | |
| NET_DOWN = ('net::ERR_', 'Timeout ') | |
| async def goto(self, url, **kwargs): | |
| for i in range(3): | |
| try: | |
| return await _goto(self, url, **kwargs) | |
| except Exception as e: # noqa: BLE001 | |
| text = str(e) | |
| if i == 2 or 'net::ERR_ABORTED' in text or not any(w in text for w in NET_DOWN): | |
| raise | |
| print(f'[小橘视频] 打开网页失败({text.splitlines()[0][:120]}),{5 * (i + 1)} 秒后再试', flush=True) | |
| await asyncio.sleep(5 * (i + 1)) | |
| Page.goto = goto | |
| ''' | |
| NET_MODULE = '''\"\"\"小橘视频加的,三样,都是环境变量设了才生效(cloud/run.sh ks 设;都没设就什么都不改): | |
| XIAOJU_TCP_MSS:这个进程新建的 TCP 连接在连之前说好每个包最多这么多字节。连接建好以后再设没用 | |
| (建连接时已经告诉服务器了),所以挂在 socket.connect 上:asyncio(httpx 走它)建连接也是调它。 | |
| XIAOJU_CONNECT_RETRIES:httpx 建连接或加密握手失败就重连这么多次(httpx 自己支持,默认 0 次); | |
| 回复半路卡住(ReadTimeout)或断掉,整个请求也重发这么多次。 | |
| XIAOJU_BROWSER_RELAY=1:浏览器是另一个程序,上面两样管不到它。Playwright 启动浏览器时让它的 https 连接 | |
| 都交给这里开的中转站(本机的 HTTP 代理,CONNECT 隧道):中转站替它去连,连接照样限包大小; | |
| 把浏览器发的转过去以后 XIAOJU_RELAY_WAIT 秒(默认 4)对方一个字节都没回,就换个新连接(轮到下一个地址) | |
| 把浏览器发过的全部重发一遍,最多 RELAY_TRIES 次。对方回过话就不能重发了(浏览器那头的加密握手已经往前走了), | |
| 之后只管原样转。 | |
| \"\"\" | |
| import os | |
| import socket | |
| MSS = int(os.environ.get('XIAOJU_TCP_MSS') or 0) | |
| RETRIES = int(os.environ.get('XIAOJU_CONNECT_RETRIES') or 0) | |
| RELAY = os.environ.get('XIAOJU_BROWSER_RELAY') == '1' | |
| def small(sock): | |
| if MSS > 0 and sock.type == socket.SOCK_STREAM and sock.family in (socket.AF_INET, socket.AF_INET6): | |
| try: | |
| sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_MAXSEG, MSS) | |
| except OSError: | |
| pass | |
| if MSS > 0: | |
| _connect = socket.socket.connect | |
| def connect(self, address): | |
| small(self) | |
| return _connect(self, address) | |
| socket.socket.connect = connect | |
| if RETRIES > 0: | |
| import httpx | |
| def with_retries(init): | |
| def __init__(self, *args, **kwargs): | |
| if not kwargs.get('retries'): | |
| kwargs['retries'] = RETRIES | |
| init(self, *args, **kwargs) | |
| return __init__ | |
| for transport in (httpx.AsyncHTTPTransport, httpx.HTTPTransport): | |
| transport.__init__ = with_retries(transport.__init__) | |
| # 连上了、请求也发了,回复却在半路卡住(ReadTimeout)或断掉:上面的重连管不到,整个请求换个连接再发一遍。 | |
| # MediaCrawler 抓快手发的都是查询(读作品列表、主页),重发没有副作用 | |
| _send = httpx.AsyncClient.send | |
| async def send(self, request, **kwargs): | |
| for i in range(RETRIES + 1): | |
| try: | |
| return await _send(self, request, **kwargs) | |
| except (httpx.ReadTimeout, httpx.ReadError, httpx.RemoteProtocolError): | |
| if i == RETRIES: | |
| raise | |
| print(f'[小橘视频] 等回复超时或断了,第 {i + 2} 次重发 {request.url.host}', flush=True) | |
| httpx.AsyncClient.send = send | |
| if RELAY: | |
| import asyncio | |
| import threading | |
| RELAY_WAIT = float(os.environ.get('XIAOJU_RELAY_WAIT') or 4) | |
| RELAY_TRIES = 4 | |
| _relay = {} | |
| _relay_lock = threading.Lock() | |
| async def _resolve(host, port): | |
| infos = await asyncio.get_running_loop().getaddrinfo(host, port, type=socket.SOCK_STREAM) | |
| return sorted(infos, key=lambda a: a[0] != socket.AF_INET) # IPv4 在前(Codespace 连不了 IPv6) | |
| async def _upstream(addrs, start): | |
| \"\"\"从第 start 个地址起轮着连(建连接限包大小),返回 (reader, writer);都连不上返回 None\"\"\" | |
| loop = asyncio.get_running_loop() | |
| for i in range(start, start + RELAY_TRIES): | |
| family, type_, proto, _, addr = addrs[i % len(addrs)] | |
| sock = socket.socket(family, type_, proto) | |
| small(sock) | |
| sock.setblocking(False) | |
| try: | |
| await asyncio.wait_for(loop.sock_connect(sock, addr), 6) | |
| return await asyncio.open_connection(sock=sock) | |
| except (OSError, asyncio.TimeoutError): | |
| sock.close() | |
| return None | |
| async def _first_reply(reader, up, addrs): | |
| \"\"\"把浏览器发的转过去,等对方回第一块数据;等不到就换新连接重发。 | |
| 返回 (对方的 reader、writer、第一块数据、浏览器那头还在读的任务);浏览器走了返回 'gone',重连够了返回 'silent'\"\"\" | |
| loop = asyncio.get_running_loop() | |
| (up_r, up_w), tries, sent, deadline = up, 1, bytearray(), None | |
| read_c = asyncio.ensure_future(reader.read(65536)) | |
| read_u = asyncio.ensure_future(up_r.read(65536)) | |
| ok = False | |
| try: | |
| while True: | |
| wait = None if deadline is None else max(0.0, deadline - loop.time()) | |
| done, _ = await asyncio.wait({read_c, read_u}, timeout=wait, return_when=asyncio.FIRST_COMPLETED) | |
| if read_c in done: | |
| data = read_c.result() | |
| if not data: | |
| return 'gone' | |
| sent += data | |
| up_w.write(data) | |
| deadline = deadline or loop.time() + RELAY_WAIT | |
| read_c = asyncio.ensure_future(reader.read(65536)) | |
| continue | |
| if read_u in done and not read_u.exception() and read_u.result(): | |
| ok = True | |
| return up_r, up_w, read_u.result(), read_c | |
| # 等了 RELAY_WAIT 秒没回音,或者对方一声不吭就断了:换个新连接,把浏览器发过的重发一遍 | |
| if tries >= RELAY_TRIES: | |
| return 'silent' | |
| read_u.cancel() | |
| up_w.close() | |
| up = await _upstream(addrs, tries) | |
| if up is None: | |
| return 'silent' | |
| (up_r, up_w), tries = up, tries + 1 | |
| if sent: | |
| up_w.write(bytes(sent)) | |
| deadline = loop.time() + RELAY_WAIT if sent else None | |
| read_u = asyncio.ensure_future(up_r.read(65536)) | |
| finally: | |
| if not ok: | |
| read_c.cancel() | |
| read_u.cancel() | |
| up_w.close() | |
| async def _pump(src, dst, pending=None): | |
| try: | |
| while True: | |
| data = await pending if pending is not None else await src.read(65536) | |
| pending = None | |
| if not data: | |
| break | |
| dst.write(data) | |
| await dst.drain() | |
| except OSError: | |
| pass | |
| finally: | |
| try: | |
| dst.write_eof() | |
| except (OSError, RuntimeError): | |
| pass | |
| async def _client(reader, writer): | |
| up_w = None | |
| try: | |
| head = await asyncio.wait_for(reader.readuntil(b'\\r\\n\\r\\n'), 30) | |
| method, target = (head.split(b'\\r\\n', 1)[0].decode('latin1').split() + ['', ''])[:2] | |
| host, _, port = target.rpartition(':') | |
| if method.upper() != 'CONNECT' or not host or not port.isdigit(): | |
| writer.write(b'HTTP/1.1 405 Method Not Allowed\\r\\nContent-Length: 0\\r\\n\\r\\n') | |
| return | |
| host = host.strip('[]') | |
| try: | |
| addrs = await _resolve(host, int(port)) | |
| up = await _upstream(addrs, 0) | |
| except OSError: | |
| up = None | |
| if up is None: | |
| print(f'[小橘视频] 中转站连 {host}:{port} 失败:连接建不起来', flush=True) | |
| writer.write(b'HTTP/1.1 502 Bad Gateway\\r\\nContent-Length: 0\\r\\n\\r\\n') | |
| return | |
| writer.write(b'HTTP/1.1 200 Connection Established\\r\\n\\r\\n') | |
| got = await _first_reply(reader, up, addrs) | |
| if got == 'silent': | |
| print(f'[小橘视频] 中转站连 {host}:{port} 失败:换了 {RELAY_TRIES} 个连接对方都没回音', flush=True) | |
| if isinstance(got, str): | |
| return | |
| up_r, up_w, first, pending = got | |
| writer.write(first) | |
| await asyncio.gather(_pump(reader, up_w, pending), _pump(up_r, writer)) | |
| except (OSError, asyncio.TimeoutError, asyncio.IncompleteReadError, asyncio.LimitOverrunError): | |
| pass | |
| finally: | |
| for w in (writer, up_w): | |
| if w is not None: | |
| w.close() | |
| def relay_port(): | |
| \"\"\"中转站的端口:第一次用的时候在后台线程里开起来(自己的事件循环,不占 MediaCrawler 的);开不起来返回 None\"\"\" | |
| with _relay_lock: | |
| if 'port' not in _relay: | |
| ready = threading.Event() | |
| def run(): | |
| try: | |
| loop = asyncio.new_event_loop() | |
| # 进程退出时中转站里还开着的连接会打「Task was destroyed but it is pending!」,没用还吓人; | |
| # 中转站连不上会自己打一行「失败」 | |
| loop.set_exception_handler(lambda loop, context: None) | |
| server = loop.run_until_complete(asyncio.start_server(_client, '127.0.0.1', 0)) | |
| _relay['port'] = server.sockets[0].getsockname()[1] | |
| except Exception: # noqa: BLE001 开不起来就不走中转站 | |
| return | |
| finally: | |
| ready.set() | |
| loop.run_forever() | |
| threading.Thread(target=run, name='xiaoju-relay', daemon=True).start() | |
| ready.wait(10) | |
| _relay.setdefault('port', None) | |
| return _relay['port'] | |
| def relay_args(kwargs): | |
| \"\"\"Playwright 启动浏览器的参数:加上 https 走中转站;自己配了代理(proxy / --proxy-server)的不动\"\"\" | |
| args = list(kwargs.get('args') or []) | |
| if kwargs.get('proxy') or any(a.startswith('--proxy-server') for a in args): | |
| return kwargs | |
| port = relay_port() | |
| return {**kwargs, 'args': args + [f'--proxy-server=https=127.0.0.1:{port}']} if port else kwargs | |
| try: | |
| from playwright.async_api import BrowserType | |
| except ImportError: | |
| BrowserType = None | |
| if BrowserType is not None: | |
| def with_relay(launch): | |
| async def wrapper(self, *args, **kwargs): | |
| return await launch(self, *args, **relay_args(kwargs)) | |
| return wrapper | |
| BrowserType.launch = with_relay(BrowserType.launch) | |
| BrowserType.launch_persistent_context = with_relay(BrowserType.launch_persistent_context) | |
| ''' | |
| MAIN_IMPORTS = ('import xiaoju_retry # noqa: F401 小橘视频:页面跳转时读页面重试\n', | |
| 'import xiaoju_net # noqa: F401 小橘视频:XIAOJU_TCP_MSS 限制连接的包大小\n') | |
| SINCE_FUNC = ''' | |
| def _xiaoju_recent(items, key, photo=False): | |
| # 小橘视频:XIAOJU_SINCE(秒)设了就只要那之后发的作品。主页从新到旧排(置顶的在最前面), | |
| # 这一页最后一条已经比界限早,后面的只会更早:第二个返回值告诉调用的别再往下翻 | |
| import os | |
| since = int(os.environ.get("XIAOJU_SINCE") or 0) | |
| if not since or not items: | |
| return items, False | |
| def at(x): | |
| v = (x.get("photo") or {}).get(key) if photo else x.get(key) | |
| try: | |
| v = int(v or 0) | |
| except (TypeError, ValueError): | |
| return 0 | |
| return v // 1000 if v > 10 ** 12 else v | |
| return [x for x in items if at(x) >= since], at(items[-1]) < since | |
| ''' | |
| DY_SINCE_ANCHOR = ' aweme_list = aweme_post_res.get("aweme_list") if aweme_post_res.get("aweme_list") else []\n' | |
| DY_SINCE_USE = (' aweme_list, _xiaoju_stop = _xiaoju_recent(aweme_list, "create_time") # 小橘视频:只要最近几天的\n' | |
| ' if _xiaoju_stop:\n' | |
| ' posts_has_more = 0\n') | |
| KS_SINCE_ANCHOR = ' videos = videos_res.get("feeds", [])\n' | |
| KS_SINCE_USE = (' videos, _xiaoju_stop = _xiaoju_recent(videos, "timestamp", photo=True) # 小橘视频:只要最近几天的\n' | |
| ' if _xiaoju_stop:\n' | |
| ' pcursor = "no_more"\n') | |
| SEARCH_OLD = ' publish_time=PublishTimeType(config.PUBLISH_TIME_TYPE),\n' | |
| SEARCH_NEW = (' publish_time=PublishTimeType(int(os.environ.get("XIAOJU_PUBLISH_TIME") or config.PUBLISH_TIME_TYPE)),' | |
| ' # 小橘视频:自动搜索要最新的\n' | |
| ' sort_type=SearchSortType(int(os.environ.get("XIAOJU_SORT") or 0)),\n') | |
| FIELD_OLD = 'from .field import PublishTimeType\n' | |
| FIELD_NEW = 'from .field import PublishTimeType, SearchSortType\n' | |
| def patch_dy_search(text): | |
| if 'XIAOJU_SORT' in text: | |
| return text | |
| if text.count(SEARCH_OLD) != 1 or text.count(FIELD_OLD) != 1: | |
| raise SystemExit('MediaCrawler 抖音 core.py 里找不到关键词搜索那几行(上游改了格式?)') | |
| return text.replace(FIELD_OLD, FIELD_NEW).replace(SEARCH_OLD, SEARCH_NEW) | |
| def _patch_since(text, anchor, use, where): | |
| if '_xiaoju_recent' in text: | |
| return text | |
| if text.count(anchor) != 1: | |
| raise SystemExit(f'MediaCrawler 的{where}里找不到翻主页的地方(上游改了格式?)') | |
| return text.replace(anchor, anchor + use) + SINCE_FUNC | |
| def patch_dy_since(text): | |
| return _patch_since(text, DY_SINCE_ANCHOR, DY_SINCE_USE, '抖音 client.py') | |
| def patch_ks_since(text): | |
| return _patch_since(text, KS_SINCE_ANCHOR, KS_SINCE_USE, '快手 client.py') | |
| def patch_main(text): | |
| for line in reversed(MAIN_IMPORTS): | |
| if line not in text: | |
| text = line + text | |
| return text | |
| KS_CHROME = re.compile(r',?\s*channel="chrome",?(?:[ \t]*#[^\n]*)?') | |
| def patch_ks_chrome(text): | |
| """快手启动浏览器时去掉 channel="chrome":没有它就是 Playwright 自带的 Chromium""" | |
| return KS_CHROME.sub(lambda m: ',' if m.group(0).rstrip().endswith(',') and not m.group(0).lstrip().startswith(',') else '', text) | |
| def apply(mc_dir): | |
| for name, module in (('xiaoju_retry.py', RETRY_MODULE), ('xiaoju_net.py', NET_MODULE)): | |
| with open(os.path.join(mc_dir, name), 'w', encoding='utf-8') as f: | |
| f.write(module) | |
| for rel, fn in (('config/base_config.py', patch), ('media_platform/douyin/core.py', patch_goto), ('main.py', patch_main), | |
| ('media_platform/douyin/login.py', patch_login_click), | |
| ('media_platform/douyin/login.py', patch_login_state), ('media_platform/douyin/client.py', patch_login_state), | |
| ('store/douyin/__init__.py', patch_store), ('media_platform/douyin/media.py', patch_media), | |
| ('store/kuaishou/__init__.py', patch_ks_store), ('media_platform/kuaishou/core.py', patch_ks_goto), | |
| ('media_platform/kuaishou/core.py', patch_ks_chrome), | |
| ('media_platform/douyin/client.py', patch_dy_since), ('media_platform/kuaishou/client.py', patch_ks_since), | |
| ('media_platform/douyin/core.py', patch_dy_search)): | |
| path = os.path.join(mc_dir, rel) | |
| with open(path, encoding='utf-8') as f: | |
| text = f.read() | |
| with open(path, 'w', encoding='utf-8') as f: | |
| f.write(fn(text)) | |
| if __name__ == '__main__': | |
| apply(sys.argv[1]) | |