#!/usr/bin/env python3 """Generic local downloader for a remote MCP manifest; no signing or account code. This file is deliberately standalone and uses only the Python standard library. The remote server resolves metadata. This process transfers media directly from official CDNs and writes it to the user's computer. """ from __future__ import annotations import argparse from contextlib import contextmanager import json import os from pathlib import Path import re import secrets import shutil import stat import sys import tempfile import unicodedata from urllib.error import HTTPError from urllib.parse import urljoin, urlsplit from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener import zipfile MAX_MANIFEST_BYTES = 2 * 1024 * 1024 MAX_IMAGE_BYTES = 20 * 1024 * 1024 MAX_VIDEO_BYTES = 512 * 1024 * 1024 ORIGINS = {'cn': 'https://www.xiaohongshu.com/', 'rednote': 'https://www.rednote.com/'} MIME_TYPES = {'image/jpeg': 'jpg', 'image/jpg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'image/avif': 'avif', 'image/gif': 'gif', 'video/mp4': 'mp4', 'application/mp4': 'mp4', 'video/webm': 'webm'} MP4_BRANDS = {b'isom', b'iso2', b'iso3', b'iso4', b'iso5', b'iso6', b'mp41', b'mp42', b'avc1', b'dash', b'M4V ', b'MSNV'} GENERIC_UA = 'Mozilla/5.0 (compatible; LocalMaterialDownloader/1.0)' _USE_DIR_FD = os.name != 'nt' class DownloadError(ValueError): """A safe diagnostic that never includes a URL, token, or raw exception.""" def _cdn_url(value): if (not isinstance(value, str) or not value or len(value) > 8192 or re.search(r'[\x00-\x20\x7f\\]', value) or '#' in value): raise DownloadError('素材地址格式无效。') try: parsed = urlsplit(value) host = parsed.hostname if (parsed.scheme != 'https' or not host or parsed.username is not None or parsed.password is not None or parsed.port is not None or parsed.netloc.lower() != host or not all(re.fullmatch(r'[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?', label) for label in host.split('.')) or not any(host.endswith('.' + suffix) for suffix in ('xhscdn.com', 'rednotecdn.com'))): raise ValueError except ValueError: raise DownloadError('素材地址不属于允许的官方 CDN。') from None return value def _component(value): text = unicodedata.normalize('NFKC', value) text = ''.join(' ' if unicodedata.category(char).startswith('C') or char in '/\\:*?"<>|' else char for char in text) text = re.sub(r'\s+', ' ', text).strip(' ._-') return text.encode('utf-8')[:100].decode('utf-8', errors='ignore').strip(' ._-') or '未命名笔记' def _validate_manifest(manifest): if (not isinstance(manifest, dict) or type(manifest.get('schema_version')) is not int or manifest.get('schema_version') != 1 or manifest.get('status') != 'resolved' or manifest.get('client_download_required') is not True or not isinstance(manifest.get('site'), str) or manifest.get('site') not in ORIGINS or not isinstance(manifest.get('note_id'), str) or not re.fullmatch(r'[0-9a-fA-F]{24}', manifest['note_id']) or manifest.get('note_type') not in ('normal', 'video')): raise DownloadError('下载清单格式无效,请重新解析笔记。') for key in ('title', 'description', 'content'): try: valid = isinstance(manifest.get(key), str) and len(manifest[key].encode('utf-8')) <= 1024 * 1024 except UnicodeError: valid = False if not valid: raise DownloadError('下载清单正文格式无效。') headers = manifest.get('headers') if (not isinstance(headers, dict) or set(headers) - {'User-Agent', 'Referer', 'Accept-Encoding'} or headers.get('Referer') != ORIGINS[manifest['site']] or headers.get('Accept-Encoding', 'identity') != 'identity'): raise DownloadError('下载清单包含不允许的请求头。') user_agent = headers.get('User-Agent', GENERIC_UA) if (not isinstance(user_agent, str) or not user_agent or len(user_agent) > 512 or re.search(r'[\x00-\x1f\x7f]', user_agent)): raise DownloadError('下载清单浏览器标识无效。') normalized = {'User-Agent': user_agent, 'Referer': ORIGINS[manifest['site']], 'Accept-Encoding': 'identity'} for key, limit in (('images', 128), ('videos', 8)): entries = manifest.get(key) if not isinstance(entries, list) or len(entries) > limit: raise DownloadError('下载清单素材数量无效。') for entry in entries: if not isinstance(entry, dict) or type(entry.get('available')) is not bool: raise DownloadError('下载清单素材条目无效。') # Validate every supplied URL before creating files or starting any transfer. if entry.get('url') is not None: _cdn_url(entry['url']) if entry['available'] and entry.get('url') is None: raise DownloadError('下载清单缺少素材地址。') return normalized @contextmanager def _directory_fd(directory): descriptor = None try: descriptor = os.open(directory, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) yield descriptor except OSError: raise DownloadError('本机素材目录无法访问或包含不安全的链接。') from None finally: if descriptor is not None: os.close(descriptor) def _child_directory(parent, name): if not _USE_DIR_FD: _plain_parents(parent) if _is_link(parent / name): raise DownloadError('本机素材目录包含不安全的链接。') child = parent / name child.mkdir(mode=0o700, exist_ok=True) if not child.is_dir() or child.resolve().parent != parent.resolve(): raise DownloadError('本机素材目录超出允许的位置。') return child with _directory_fd(parent) as descriptor: try: os.mkdir(name, 0o700, dir_fd=descriptor) except FileExistsError: pass child = parent / name with _directory_fd(child): pass if child.resolve().parent != parent.resolve(): raise DownloadError('本机素材目录超出允许的位置。') return child def _is_link(path): if path.is_symlink() or getattr(path, 'is_junction', lambda: False)(): return True try: info = path.lstat() except FileNotFoundError: return False # Python versions without Path.is_junction still expose the Windows # reparse-point file attribute through lstat(). return bool(getattr(info, 'st_file_attributes', 0) & getattr(stat, 'FILE_ATTRIBUTE_REPARSE_POINT', 0x400)) def _plain_parents(directory): for candidate in (directory, *directory.parents): if _is_link(candidate): raise DownloadError('本机素材目录包含不安全的链接。') def _check_target(descriptor, name): try: existing = os.stat(name, dir_fd=descriptor, follow_symlinks=False) except FileNotFoundError: return if not stat.S_ISREG(existing.st_mode): raise DownloadError('本机目标文件不是普通文件,未覆盖。') def _publish(directory, writer, filename): """Write through a pinned directory descriptor, then atomically publish.""" if not _USE_DIR_FD: return _publish_portable(directory, writer, filename) temporary = '.download-' + secrets.token_hex(16) with _directory_fd(directory) as descriptor: try: handle_fd = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_RDWR | os.O_NOFOLLOW, 0o600, dir_fd=descriptor) with os.fdopen(handle_fd, 'w+b') as handle: outcome = writer(handle) handle.flush() os.fsync(handle.fileno()) name = filename(outcome) if callable(filename) else filename if not isinstance(name, str) or Path(name).name != name or name in ('.', '..'): raise DownloadError('本机目标文件名无效。') _check_target(descriptor, name) os.replace(temporary, name, src_dir_fd=descriptor, dst_dir_fd=descriptor) return directory / name, outcome finally: try: os.unlink(temporary, dir_fd=descriptor) except FileNotFoundError: pass def _publish_portable(directory, writer, filename): """Windows fallback; reject symlinks and junctions before publishing.""" _plain_parents(directory) if not directory.is_dir(): raise DownloadError('本机素材目录包含不安全的链接。') temporary = None try: with tempfile.NamedTemporaryFile('w+b', prefix='.download-', dir=directory, delete=False) as handle: temporary = Path(handle.name) temporary.chmod(0o600) outcome = writer(handle) handle.flush() os.fsync(handle.fileno()) name = filename(outcome) if callable(filename) else filename if not isinstance(name, str) or Path(name).name != name or name in ('.', '..'): raise DownloadError('本机目标文件名无效。') target = directory / name _plain_parents(directory) if (_is_link(target) or target.exists() and not target.is_file() or temporary.resolve().parent != directory.resolve()): raise DownloadError('本机目标文件位置不安全,未覆盖。') os.replace(temporary, target) temporary = None return target, outcome finally: if temporary is not None: temporary.unlink(missing_ok=True) class _NoRedirect(HTTPRedirectHandler): def redirect_request(self, request, fp, code, message, headers, newurl): return None def _response(opener, address, headers): current = _cdn_url(address) for attempt in range(4): request = Request(current, headers=headers, method='GET') try: response = opener.open(request, timeout=45) except HTTPError as error: response = error except Exception: raise DownloadError('本机连接素材 CDN 失败,请稍后重新解析再下载。') from None code = getattr(response, 'status', None) or response.getcode() if code in (301, 302, 303, 307, 308): try: location = response.headers.get('Location') if attempt == 3 or not isinstance(location, str) or not location: raise DownloadError('素材重定向缺失或超过限制。') current = _cdn_url(urljoin(current, location)) finally: response.close() continue if code != 200: response.close() raise DownloadError('素材 CDN 未返回完整文件,请重新解析笔记后重试。') return response raise DownloadError('素材重定向超过限制。') def _avif_header(prefix, size): if len(prefix) < 16 or prefix[4:8] != b'ftyp': return False box_size = int.from_bytes(prefix[:4], 'big') brand_offset = 8 if box_size == 1: if len(prefix) < 24: return False box_size = int.from_bytes(prefix[8:16], 'big') brand_offset = 16 # ftyp contains a four-byte major brand, four-byte minor version and zero # or more complete compatible brands. Never scan arbitrary bytes after it # or mistake a minor-version word for a compatible brand. if (box_size < brand_offset + 8 or box_size > size or (box_size - brand_offset - 8) % 4): return False brands = [prefix[brand_offset:brand_offset + 4]] brands.extend(prefix[index:index + 4] for index in range(brand_offset + 8, min(box_size, len(prefix)) - 3, 4)) return any(brand in (b'avif', b'avis') for brand in brands) def _kind(prefix, size, media_kind, tail=b''): if media_kind == 'image': if prefix.startswith(b'\xff\xd8\xff') and size >= 4: return 'jpg' if prefix.startswith(b'\x89PNG\r\n\x1a\n') and size >= 24: return 'png' if prefix[:4] == b'RIFF' and prefix[8:12] == b'WEBP' and size >= 12: if int.from_bytes(prefix[4:8], 'little') + 8 == size: return 'webp' if _avif_header(prefix, size): return 'avif' if (prefix.startswith((b'GIF87a', b'GIF89a')) and size >= 14 and int.from_bytes(prefix[6:8], 'little') > 0 and int.from_bytes(prefix[8:10], 'little') > 0 and tail.endswith(b';')): return 'gif' else: if prefix.startswith(b'\x1aE\xdf\xa3') and size >= 8: return 'webm' if len(prefix) >= 16 and prefix[4:8] == b'ftyp': box_size = int.from_bytes(prefix[:4], 'big') brands = [prefix[8:12], *(prefix[i:i + 4] for i in range(16, min(box_size, len(prefix)), 4))] if 16 <= box_size <= size and any(brand in MP4_BRANDS for brand in brands): return 'mp4' raise DownloadError('素材响应不是受支持的图片或视频文件。') def _download(opener, entry, directory, index, headers, media_kind): response = _response(opener, entry['url'], headers) try: mime = response.headers.get('Content-Type', '').split(';', 1)[0].strip().lower() expected = MIME_TYPES.get(mime) allowed = ('jpg', 'png', 'webp', 'avif', 'gif') if media_kind == 'image' else ('mp4', 'webm') if expected not in allowed or response.headers.get('Content-Encoding', 'identity') != 'identity': raise DownloadError('素材响应类型不受支持。') length = response.headers.get('Content-Length') if length is not None and (not isinstance(length, str) or not re.fullmatch(r'[0-9]{1,12}', length)): raise DownloadError('素材响应长度无效。') declared = int(length) if length is not None else None limit = MAX_IMAGE_BYTES if media_kind == 'image' else MAX_VIDEO_BYTES if declared is not None and declared > limit: raise DownloadError('素材超过本机下载大小限制。') def write(handle): size, prefix, tail = 0, b'', b'' try: while chunk := response.read(65536): size += len(chunk) if size > limit: raise DownloadError('素材超过本机下载大小限制。') prefix += chunk[:max(0, 1024 - len(prefix))] tail = (tail + chunk)[-16:] handle.write(chunk) except DownloadError: raise except Exception: raise DownloadError('素材传输中断,未保存不完整文件。') from None if declared is not None and size != declared: raise DownloadError('素材响应不完整,未替换已有文件。') kind = _kind(prefix, size, media_kind, tail) if kind != expected: raise DownloadError('素材响应类型与实际文件不一致。') return kind, size path, (_, size) = _publish(directory, write, lambda outcome: f'{index:02d}.{outcome[0]}') return {'kind': media_kind, 'path': str(path), 'bytes': size} finally: response.close() def download_manifest(manifest, downloads_root=None, opener=None): """Download directly to this machine and return only paths and safe status.""" headers = _validate_manifest(manifest) # A clean opener intentionally has no cookie jar, authentication handler, # .netrc integration or environment proxy credentials. transport = opener if opener is not None else build_opener(ProxyHandler({}), _NoRedirect()) try: root = Path(downloads_root or Path.home() / 'Downloads' / '小红书素材库').expanduser().resolve() root.mkdir(parents=True, exist_ok=True, mode=0o700) output = _child_directory(root, _component(manifest['title']) + '_' + manifest['note_id'].lower()) images_dir = _child_directory(output, 'images') videos_dir = _child_directory(output, 'videos') text, _ = _publish(output, lambda handle: handle.write(manifest['content'].encode('utf-8')), 'content.txt') files = [{'kind': 'text', 'path': str(text), 'bytes': text.stat().st_size}] errors = [] counts = {'image': 0, 'video': 0} for key, kind, directory in (('images', 'image', images_dir), ('videos', 'video', videos_dir)): for index, entry in enumerate(manifest[key], 1): try: if not entry['available']: raise DownloadError('该素材尚未返回可下载地址。') saved = _download(transport, entry, directory, index, headers, kind) files.append(saved) counts[kind] += 1 except DownloadError as error: errors.append({'kind': kind, 'index': index, 'message': str(error)}) except OSError: errors.append({'kind': kind, 'index': index, 'message': '本机素材文件保存失败。'}) if manifest['note_type'] == 'video' and not manifest['videos']: errors.append({'kind': 'video', 'index': 1, 'message': '视频地址缺失,视频尚未下载。'}) def write_archive(handle): with zipfile.ZipFile(handle, 'w', compression=zipfile.ZIP_DEFLATED) as archive: for saved in files: path = Path(saved['path']) # Never enumerate the directory: old files, manifests and # credentials cannot enter the archive accidentally. if _is_link(path) or not path.resolve().is_relative_to(output.resolve()): raise DownloadError('本机素材文件位置已变化,资料包未生成。') relative = str(path.relative_to(output)).replace('\\', '/') flags = os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0) | getattr(os, 'O_BINARY', 0) with os.fdopen(os.open(path, flags), 'rb') as source: if not stat.S_ISREG(os.fstat(source.fileno()).st_mode): raise DownloadError('本机素材文件不是普通文件,资料包未生成。') with archive.open(relative, 'w') as destination: shutil.copyfileobj(source, destination, length=65536) try: archive, _ = _publish(output, write_archive, 'assets.zip') files.append({'kind': 'archive', 'path': str(archive), 'bytes': archive.stat().st_size}) except (OSError, zipfile.BadZipFile, DownloadError): errors.append({'kind': 'archive', 'message': '本机资料包生成失败,已保留成功下载的素材。'}) complete = not errors return {'status': 'complete' if complete else 'partial', 'download_complete': complete, 'output_dir': str(output), 'downloaded_images': counts['image'], 'downloaded_videos': counts['video'], 'files': files, 'errors': errors} except DownloadError: raise except (OSError, ValueError, RuntimeError): raise DownloadError('本机下载目录无法使用,请检查目录和权限。') from None def main(argv=None): parser = argparse.ArgumentParser(description='把远程 MCP 的素材清单直接下载到本机(不含账号或签名逻辑)') parser.add_argument('manifest', type=Path, help='resolve_note 返回的 JSON 清单文件') parser.add_argument('--downloads-root', type=Path, help='本机下载根目录') args = parser.parse_args(argv) try: if args.manifest.stat().st_size > MAX_MANIFEST_BYTES: raise DownloadError('下载清单过大。') manifest = json.loads(args.manifest.read_text(encoding='utf-8')) result = download_manifest(manifest, downloads_root=args.downloads_root) print(json.dumps(result, ensure_ascii=False, indent=2)) return 0 if result['download_complete'] else 2 except (DownloadError, OSError, ValueError, UnicodeError): print('下载未完成,请检查清单格式、目录权限,或重新解析笔记。', file=sys.stderr) return 1 if __name__ == '__main__': raise SystemExit(main())