SkilVaultSign inStart free

Catalogue / video-download-playbook

video-download-playbook

Older skill: source not recordedSignedDownloads authorized video from supported public/share pages using a verified browser capture or yt-dlp path, with explicit login, output, and media checks. Use for a requested local copy of content the user may download. Do not use to bypass access controls, DRM, geography restrictions, or collect…
---
name: video-download-playbook
description: >-
  Downloads authorized video from supported public/share pages using a verified
  browser capture or yt-dlp path, with explicit login, output, and media checks.
  Use for a requested local copy of content the user may download. Do not use to
  bypass access controls, DRM, geography restrictions, or collect account cookies.
---

Establish rights, URL, engine, and output

First, extract the actual video URL from the supplied share text and confirm the user may access and download it — a link alone is not authorization to fetch. Then resolve:

  • Platform and content type (some pages are images-only, not video)
  • Whether authentication is needed, and the requested quality
  • Exact output folder and file name

Respect site policies and creator rights. Do not promise support for a fixed number of sites: coverage depends on the installed extractor/version and current page structures. Images-only notes, subscription-only material, and protected/DRM content are not silently turned into downloadable video.

Engine choices, selected explicitly after inspecting capabilities — no hidden fallback expands network scope without approval:

  • Browser capture can support Douyin video/short/modal-ID pages, Xiaohongshu

discovery/explore/short-link notes, and Bilibili BV/short pages where normal authorized playback exposes streams.

  • yt-dlp (locally verified) covers supported sites such as YouTube watch/short

URLs, Twitter/X status pages, Instagram reel/post pages, and other supported extractors.

Confirmation

Before download, confirm URL/platform, redirect and browsing scope, account context, requested quality, output and disk budget, possible cost, and expected writes. Confirm separately — each on its own: external login checks, visible login browsing, reference network requests, retries, proxy use, installations, configuration changes, file cleanup, playback, and sharing.

  • Never disable TLS verification or bypass site restrictions.
  • Never change package mirrors or settings automatically.
  • Never read, export, or store authentication cookies, and never expose signed

stream URLs in logs.

User-managed login and session continuity

Before a Bilibili download, establish authorized login status through the user's existing browser or client. An unauthenticated result may offer lower quality — do not promise a fixed resolution; offer the choice between completing login and deliberately using the accessible lower quality. Douyin/Xiaohongshu may also need login depending on the page. Missing or expired session evidence is distinct from a successful page fetch.

During login:

  • The user opens an approved visible browser page and enters credentials

independently. Wait for explicit completion or a skip choice.

  • Never fill credentials, read cookie values, or treat a closed window as proof

of login success.

  • Recheck the site's non-secret authenticated UI within the approved scope.
  • If the runtime offers an approved signal file or UI completion event, confirm

its exact path, write, and lifecycle — a stale signal must not approve a new login.

  • On skip or cancel, stop only the owned login session after confirmation and

proceed solely with authorized public access.

User-controlled browser/session persistence replaces raw cookie-file serialization. Never claim every stored session is valid because one cookie has an unexpired timestamp.

Complete original extraction and transfer core

The code below uses Python's standard library and accepts an already authorized Playwright-style page for browser discovery. The page/context is user-managed and must be inspected/approved before use; no absent cookie helper is implied. Network and file actions require a real approved=True human scope. URL predicates are historical platform assumptions, not current-site guarantees. Stop on schema mismatch. Save helper code only after confirmation.

from pathlib import Path
import json
import os
import re
import subprocess
import tempfile
from urllib.parse import urlsplit, parse_qs
from urllib.request import Request, urlopen

def share_url(text):
    matches = re.findall(r'https?://[^\s\"<>]+', text)
    if not matches:
        raise ValueError('HTTP(S) share URL required')
    url = matches[0].rstrip('.,;!?)]')
    parsed = urlsplit(url)
    if parsed.scheme not in ('http', 'https') or not parsed.hostname or parsed.username or parsed.password:
        raise ValueError('uncredentialed web URL required')
    return url

def platform_of(url):
    host = (urlsplit(url).hostname or '').lower()
    for platform, domains in [('douyin', ('douyin.com',)),
                              ('xiaohongshu', ('xiaohongshu.com', 'xhslink.com')),
                              ('bilibili', ('bilibili.com', 'b23.tv'))]:
        if any(host == domain or host.endswith('.' + domain) for domain in domains):
            return platform
    return 'yt-dlp'

def filename(title, fallback='authorized-video'):
    clean = re.sub(r'[\x00-\x1f/\\:*?"<>|]+', '-', str(title))
    clean = re.sub(r'\s+', '-', clean).strip(' .-')
    while len(clean.encode('utf-8')) > 160:
        clean = clean[:-1]
    if not clean or clean.upper().split('.')[0] in {'CON', 'PRN', 'AUX', 'NUL', 'COM1', 'LPT1'}:
        clean = fallback
    return clean + '.mp4'

def capture(page, url, platform, approved=False, wait_ms=7000):
    if not approved:
        raise PermissionError('human browser/network approval required')
    if platform not in ('douyin', 'xiaohongshu', 'bilibili'):
        raise ValueError('unsupported browser platform')
    found = []
    def observe(response):
        host = (urlsplit(response.url).hostname or '').lower()
        media = response.headers.get('content-type', '').lower()
        douyin = (host == 'douyinvod.com' or host.endswith('.douyinvod.com')) and 'video_mp4' in response.url
        xhs = (host == 'xhscdn.com' or host.endswith('.xhscdn.com')) and ('video' in media or '.mp4' in urlsplit(response.url).path)
        if (platform == 'douyin' and douyin) or (platform == 'xiaohongshu' and xhs):
            found.append(response.url)
    page.on('response', observe)
    try:
        parsed = urlsplit(url)
        if platform == 'douyin':
            modal = parse_qs(parsed.query).get('modal_id')
            if modal and modal[0].isdigit():
                url = 'https://www.douyin.com/video/' + modal[0]
        page.goto(url, wait_until='domcontentloaded', timeout=30000)
        page.wait_for_timeout(wait_ms)
        title = page.title()
        if platform == 'bilibili':
            info = page.evaluate('() => window.__playinfo__ || null')
            return {'title': title, 'playinfo': info, 'page_url': page.url}
        if not found:
            page.wait_for_timeout(wait_ms)
        if not found:
            raise ValueError('no authorized video stream observed; inspect content/login/version')
        return {'title': title, 'streams': [found[0]], 'page_url': page.url}
    finally:
        page.remove_listener('response', observe)

def bili_streams(info):
    data = (info or {}).get('data') or {}
    dash = data.get('dash')
    if dash:
        videos = dash.get('video') or []
        audio = dash.get('audio') or []
        if not videos:
            raise ValueError('no available DASH video')
        video = max(videos, key=lambda x: x.get('bandwidth', 0))
        sound = max(audio, key=lambda x: x.get('bandwidth', 0)) if audio else None
        def address(row):
            url = row.get('baseUrl') or row.get('base_url')
            if not url:
                raise ValueError('stream URL missing')
            return url
        return {'kind': 'dash', 'urls': [address(video)] + ([address(sound)] if sound else []),
                'video_dimensions': [video.get('width'), video.get('height')],
                'video_codec': video.get('codecs'), 'audio_codec': sound.get('codecs') if sound else None}
    segments = [row['url'] for row in data.get('durl', []) if row.get('url')]
    if not segments:
        raise ValueError('playback metadata lacks downloadable streams')
    return {'kind': 'segments', 'urls': segments}

def public_stream(url, referer):
    # Default TLS verification remains enabled; no cookie/auth headers are added.
    request = Request(url, headers={'Referer': referer, 'Origin': urlsplit(referer).scheme + '://' + urlsplit(referer).netloc})
    return urlopen(request, timeout=30)

def stream_to(url, destination, referer, approved=False, max_bytes=2_000_000_000, open_stream=public_stream):
    if not approved:
        raise PermissionError('human stream request/output approval required')
    if not urlsplit(url).hostname or urlsplit(url).scheme not in ('http', 'https'):
        raise ValueError('web stream URL required')
    total = 0
    with open_stream(url, referer) as response, Path(destination).open('xb') as handle:
        while True:
            block = response.read(1024 * 1024)
            if not block:
                break
            total += len(block)
            if total > max_bytes:
                raise ValueError('approved byte budget exceeded; partial output retained')
            handle.write(block)
    if not total:
        raise ValueError('empty stream output')
    return total

def browser_download(plan, output, referer, approved=False, open_stream=public_stream, run=subprocess.run):
    if not approved:
        raise PermissionError('human download/temporary/merge approval required')
    output = Path(output)
    if output.exists() or not output.parent.is_dir():
        raise ValueError('fresh approved output in existing directory required')
    if not plan.get('urls'):
        raise ValueError('stream plan required')
    # The unique work folder is intentionally retained until explicit cleanup approval.
    work = Path(tempfile.mkdtemp(prefix='video-work-', dir=output.parent))
    files = []
    for index, url in enumerate(plan['urls']):
        target = work / f'part-{index}.media'
        stream_to(url, target, referer, True, open_stream=open_stream)
        files.append(target)
    merged = work / 'completed.mp4'
    if len(files) == 1:
        os.link(files[0], output)
    else:
        if plan.get('kind') == 'dash':
            argv = ['ffmpeg', '-n', '-i', str(files[0]), '-i', str(files[1]), '-c', 'copy', str(merged)]
        else:
            listing = work / 'segments.txt'
            listing.write_text(''.join("file '" + f.name + "'\n" for f in files), encoding='utf-8')
            argv = ['ffmpeg', '-n', '-f', 'concat', '-safe', '1', '-i', str(listing), '-c', 'copy', str(merged)]
        result = run(argv, cwd=work, check=False, timeout=300)
        if result.returncode or not merged.is_file() or not merged.stat().st_size:
            raise ValueError('merge failed; parts retained for diagnosis')
        os.link(merged, output)
    return {'path': str(output), 'bytes': output.stat().st_size, 'work_directory': str(work)}

def generic_command(url, output_directory, output_name=None):
    directory = Path(output_directory)
    if not directory.is_dir():
        raise ValueError('existing approved output directory required')
    template = str(directory / '%(title).80s.%(ext)s')
    if output_name:
        if Path(output_name).name != output_name:
            raise ValueError('filename must not escape output directory')
        template = str(directory / (output_name if output_name.endswith('.mp4') else output_name + '.mp4'))
    return ['yt-dlp', '--no-playlist', '--no-overwrites', '--progress', '--newline',
            '-f', 'bv*+ba/b', '--merge-output-format', 'mp4', '-o', template, '--', url]

Notes on the code above:

  • The default public transport is for already accessible media. If a request

needs account authorization, use the user's established secure integration — never collect or export cookies.

  • Approve the actual redirect/CDN host scope and validate it stays

Preview shortened. The full SKILL.md is in the pack.