跳转到正文
中文
获取 API 密钥
浏览文档

指南

构建媒体交付流水线

将 MP4 下载到私有 S3 存储,在重启后恢复任务,并让应用访问已验证的文件。

本页内容

你将构建什么

将一项持久任务从视频 ID 转为应用可用的文件。把每个阶段保存在磁盘上,使新进程能从最后确认的结果继续。

流水线及保存记录
item.json
  → 提交一次       → 保存运行记录及任务 ID
  → 恢复任务       → delivery.json
  → 验证 S3 文件   → media.mp4 + ready.json
  → 确认用户权限   → 短期下载 URL

开始前准备

为全部六步选择同一示例方式。两种方式都需要已安装的 FlashData CLI、具有 youtube_download 权限的已保存所有者配置档、用于上传的私有 S3 storage.json,以及可读取交付对象的 AWS 身份。

在 Python 环境中使用 Python 3.10+。脚本通过 CLI 保留运行日志,通过 Boto3 读取 S3 并签名链接,无需 Bash、jq、Node.js 或 AWS CLI。下方命令使用 python;若解释器名为 python3,请相应替换。

安装 Python 依赖
python --version
flashdata --version
python -m pip install boto3

保存运行环境设置

在版本控制之外创建私有任务目录。保存所选方式的设置,修改绝对路径及配置档名。每个进程使用相同账户及运行日志,存储凭据保留在私有 storage.json 中。每项任务同时只运行一个进程。

保存 pipeline.json。Windows 可在 JSON 中使用 C:/private/flashdata-state 这样的正斜杠路径。

pipeline.json
{
  "stateDir": "/absolute/path/to/flashdata-state",
  "storageConfig": "/absolute/path/to/private/storage.json",
  "profile": "default"
}

1. 保存一项持久任务

在任务目录保存 item.json,替换视频及 S3 目标。此示例请求一个最高 720p 的 MP4。重试使用同一 runId;不同预期输出使用新的 runId 及对象前缀。

item.json
{
  "runId": "media:clip-001:720p:v1",
  "request": {
    "source": "youtube_download",
    "video_id": "jNQXAC9IVRw",
    "params": {
      "download_type": "audio_video",
      "video_quality": "<=720",
      "output_format": "mp4"
    }
  },
  "destination": {
    "bucket": "your-media-bucket",
    "region": "us-east-1",
    "prefix": "media/clip-001-v1"
  }
}

2. 保存脚本并检查访问

先创建下方文件,再运行检查。脚本验证 S3 目标,并为每次提交尝试保留回执。

创建流水线脚本

在 pipeline.json 及 item.json 所在目录创建 pipeline.py。将下方完整代码复制到文件中并保存。第 2–4 步复用此文件进行检查、提交及恢复。

pipeline.py
# pipeline.py — Python 3.10+ and the FlashData CLI on PATH.
import argparse
import json
import os
import subprocess
import sys
import tempfile
from pathlib import Path

ROOT = Path(__file__).resolve().parent


def read_json(path):
    return json.loads(Path(path).read_text(encoding='utf-8-sig'))


def delivery_directory():
    # Recovery updates this pointer only after the delivery is saved successfully.
    return ROOT / (ROOT / 'delivery-dir.txt').read_text(encoding='utf-8').strip()


def main(action):
    os.umask(0o077)
    settings = read_json(ROOT / 'pipeline.json')
    for name in ['stateDir', 'storageConfig']:
        if not Path(settings[name]).is_absolute():
            raise ValueError('Set an absolute path for ' + name)
    item = read_json(ROOT / 'item.json')
    run_id = item['runId']
    env = dict(os.environ)
    env.pop('FLASHDATA_API_KEY', None)  # Reuse the saved owner profile.
    flags = ['--profile', settings['profile'], '--state-dir', settings['stateDir'],
             '--json', '--non-interactive']

    def cli(*args, payload=None, attempt=None):
        result = subprocess.run(['flashdata', *args, *flags], cwd=ROOT, env=env,
                                input=json.dumps(payload) if payload is not None else None,
                                capture_output=True, text=True, encoding='utf-8')
        if attempt:
            (attempt / 'receipt.json').write_text(result.stdout, encoding='utf-8')
            (attempt / 'error.json').write_text(result.stderr, encoding='utf-8')
        if result.returncode:
            if attempt:
                raise RuntimeError('Keep ' + str(attempt) + '; inspect its error and saved run.')
            raise RuntimeError(result.stderr.strip() or 'FlashData command failed.')
        response = json.loads(result.stdout)
        if not response.get('ok'):
            raise RuntimeError('Inspect the CLI response before continuing.')
        return response

    def new_attempt(stage):
        attempts = ROOT / 'attempts'
        attempts.mkdir(exist_ok=True)
        return Path(tempfile.mkdtemp(prefix=stage + '.', dir=attempts))

    if action == 'check':
        access = cli('auth', 'status')['data']
        identity = access['identity']
        if (not access.get('accessVerified')
                or identity['identity'].get('recurringAllowed') is not True
                or 'youtube_download' not in identity.get('permittedSources', [])):
            raise ValueError('Owner access with youtube_download is required.')
        print(json.dumps({'accountId': identity['identity']['accountId'],
                          'permittedSources': identity['permittedSources']}, indent=2))
        for args in [('account', 'balance'),
                     ('account', 'pricing', '--source', 'youtube_download', '--request-count', '1'),
                     ('account', 'limits')]:
            print(json.dumps(cli(*args)['data'], indent=2))
    elif action in ['dry-run', 'submit']:
        storage = read_json(settings['storageConfig'])
        destination = item['destination']
        if (item['request']['source'] != 'youtube_download'
                or storage.get('storage_type') != 's3'
                or storage.get('storage_url') != destination['bucket']
                or storage.get('region') != destination['region']):
            raise ValueError('Check item.json and the S3 destination in storage.json.')
        request = item['request']
        request['params']['storage'] = {**storage, 'object_prefix': destination['prefix']}
        args = ['query', '--input', '-', '--mode', 'async', '--run-id', run_id]
        if action == 'dry-run':
            response = cli(*args, '--dry-run', payload=request)
            if response['data'].get('dryRun') is not True:
                raise ValueError('Expected a dry-run result.')
            print(json.dumps({'ok': True, 'dryRun': True}))
        else:
            attempt = new_attempt('submit')
            response = cli(*args, '--output', str(attempt / 'submission.json'),
                           payload=request, attempt=attempt)
            print(json.dumps({'runId': run_id, 'cached': response.get('cached'),
                              'receipt': str(attempt / 'submission.json')}, indent=2))
    elif action == 'inspect':
        run = cli('runs', 'show', run_id)['data']
        print(json.dumps({'runId': run_id, 'status': run['status'], 'jobId': run.get('remoteId'),
                          'errorCode': run.get('errorCode'),
                          'candidateJobIds': run.get('candidateRemoteIds')}, indent=2))
    elif action == 'recover':
        attempt = new_attempt('recover')
        cli('runs', 'recover', run_id, '--timeout', '10m',
            '--output', str(attempt / 'delivery.json'), attempt=attempt)
        run = cli('runs', 'show', run_id)
        (attempt / 'run.json').write_text(json.dumps(run, indent=2), encoding='utf-8')
        delivery = read_json(attempt / 'delivery.json')
        if delivery.get('source') != 'youtube_download' or delivery.get('status') != 'done':
            raise ValueError('Inspect the saved delivery before verifying.')
        pointer = ROOT / 'delivery-dir.next'
        pointer.write_text(attempt.relative_to(ROOT).as_posix(), encoding='utf-8')
        pointer.replace(ROOT / 'delivery-dir.txt')
        print('Delivery files:', attempt)
    elif action == 'delivery':
        delivery = read_json(delivery_directory() / 'delivery.json')
        print(json.dumps({'status': delivery['status'], 'file': delivery['results'][0],
                          'usage': delivery.get('usage')}, indent=2))


if __name__ == '__main__':
    sys.stdout.reconfigure(encoding='utf-8')
    sys.stderr.reconfigure(encoding='utf-8')
    parser = argparse.ArgumentParser()
    parser.add_argument('action', choices=['check', 'dry-run', 'submit', 'inspect', 'recover', 'delivery'])
    try:
        main(parser.parse_args().action)
    except (OSError, ValueError, KeyError, RuntimeError) as error:
        print(str(error), file=sys.stderr)
        sys.exit(1)

检查已保存的账户

保存脚本后,在任务目录运行此免费检查。缺少所有者访问或 youtube_download 权限时会停止。确认账户 ID、余额、每 TB 费率及限额。最终费用取决于上传字节数。

检查环境与账户
python pipeline.py check

验证而不下载

保存辅助脚本后执行预检查。Python 输出 ok: true 及 dryRun: true;Bash 输出 true。此步骤验证输入及访问,不提交媒体任务,也不预留 Credits。

免费预检查
python pipeline.py dry-run

3. 提交并保留任务 ID

此步骤提交一次付费后台下载。本地运行中应出现 status: accepted 及 jobId。保留配置档、状态目录及 item.json,以便恢复。第 5 步完成后媒体才可供应用使用。

提交一次
python pipeline.py submit
检查本地状态 · 不发送新查询
python pipeline.py inspect

运行已保存或结果不确定时

CLI 状态操作
accepted + jobId在第 4 步恢复此运行。进程停止时保留任务 ID。
succeeded恢复或导出保存的响应,再验证存储。不要提交新任务。
结果未知 / 无已确认任务 ID保留运行、回执及错误。决定再次提交前,检查历史或候选任务 ID。

4. 恢复交付记录

在任意新终端进入任务目录后执行。恢复流程等待原始任务,输出包含 delivery.json、run.json 及回执的目录。10 分钟超时仅停止本地等待,重复恢复即可继续相同任务。

继续已保存的任务

复用第 2 步保存的 pipeline.py,无需创建其他脚本。

恢复已有任务 · 不重新提交
python pipeline.py recover

检查交付对象

预期得到一个 S3 对象 URL、正的文件大小及 MD5,私有对象需 AWS 读取身份。Python 将成功目录保存到 delivery-dir.txt,供后续脚本使用。Bash 保留 DELIVERY_DIR,换用新终端时将它设为刚输出的目录。

交付记录
python pipeline.py delivery

5. 标记就绪前验证文件

验证脚本检查原输入、S3 Bucket 及前缀,将私有对象流式写入磁盘,再比对字节数及 MD5。只有匹配文件才生成 verified/ready.json。Python 读取 delivery-dir.txt,Node 使用 DELIVERY_DIR。两者都不提交 FlashData 查询。

保存验证脚本

此验证器处理标准 Amazon S3 对象 URL。自定义端点或其他提供商应使用相应的认证对象读取,并保留相同的目标、字节数及校验和检查。

在 pipeline.py 旁创建 verify-media.py,复制下方完整代码。将两个文件保存在任务目录。

verify-media.py
# verify-media.py — uses Boto3's configured AWS read identity.
import hashlib
import json
import os
import re
import sys
from contextlib import closing
from datetime import datetime, timezone
from urllib.parse import unquote, urlsplit

import boto3
from pipeline import ROOT, delivery_directory, read_json


def main():
    os.umask(0o077)
    directory = delivery_directory()
    item = read_json(ROOT / 'item.json')
    saved = read_json(directory / 'run.json')
    raw = (directory / 'delivery.json').read_bytes()
    delivery = json.loads(raw)
    run = saved.get('data', {})
    if (not saved.get('ok') or run.get('id') != item['runId']
            or run.get('status') != 'succeeded' or not run.get('remoteId')
            or delivery.get('source') != 'youtube_download' or delivery.get('status') != 'done'
            or not isinstance(delivery.get('results'), list) or len(delivery['results']) != 1):
        raise ValueError('Inspect the saved run and completed delivery before verifying.')
    file = delivery['results'][0]
    bucket, region, prefix = (item['destination'][key] for key in ['bucket', 'region', 'prefix'])
    original = run.get('input', {})
    storage = original.get('params', {}).get('storage', {})
    if (original.get('source') != 'youtube_download' or original.get('video_id') != item['request']['video_id']
            or any(original.get('params', {}).get(key) != item['request']['params'][key]
                   for key in ['download_type', 'video_quality', 'output_format'])
            or storage.get('storage_url') != bucket or storage.get('region') != region
            or storage.get('object_prefix') != prefix):
        raise ValueError('item.json changed after submission. Inspect the original run.')
    url = urlsplit(file['file_url'])
    hosts = [bucket + '.s3.' + region + '.amazonaws.com', bucket + '.s3.amazonaws.com']
    key = unquote(url.path[1:], errors='strict')
    if (url.scheme != 'https' or url.netloc not in hosts or url.query or url.fragment
            or not prefix or not key.startswith(prefix + '/')):
        raise ValueError('The delivery does not match the planned Amazon S3 destination.')
    if (type(file.get('file_size')) is not int or file['file_size'] <= 0
            or not re.fullmatch(r'[a-fA-F0-9]{32}', file.get('md5', ''))):
        raise ValueError('A positive file_size and MD5 are required. Keep the manifest.')
    verification = directory / 'verified'
    verification.mkdir(mode=0o700)  # Stop if an earlier verification already exists.
    local_file = verification / 'media.mp4'
    s3 = boto3.client('s3', region_name=region)
    response = s3.get_object(Bucket=bucket, Key=key)
    size, digest = 0, hashlib.md5(usedforsecurity=False)
    with closing(response['Body']) as stream, local_file.open('xb') as output:
        while chunk := stream.read(1024 * 1024):
            output.write(chunk)
            size += len(chunk)
            digest.update(chunk)
    md5 = digest.hexdigest()
    if size != file['file_size'] or md5 != file['md5'].lower():
        raise ValueError('Byte count or MD5 mismatch. Keep the file; do not mark it ready.')
    ready = {'runId': item['runId'], 'jobId': run['remoteId'], 'videoId': item['request']['video_id'],
             'bucket': bucket, 'region': region, 'objectKey': key,
             'storageVersionId': response.get('VersionId'), 'bytes': size, 'md5': md5,
             'verifiedAt': datetime.now(timezone.utc).isoformat(), 'localFile': str(local_file.resolve()),
             'deliverySha256': hashlib.sha256(raw).hexdigest(), 'usage': delivery.get('usage')}
    with (verification / 'ready.json').open('x', encoding='utf-8') as output:
        json.dump(ready, output, indent=2)
    print('Delivery verified:', verification / 'ready.json')
    print(json.dumps(ready, indent=2))


if __name__ == '__main__':
    sys.stdout.reconfigure(encoding='utf-8')
    sys.stderr.reconfigure(encoding='utf-8')
    try:
        main()
    except Exception as error:
        print(str(error), file=sys.stderr)
        sys.exit(1)

运行文件验证

保存脚本后,在任务目录运行。

验证并读取交接记录
python verify-media.py

将 ready.json 交给应用

预期输出 Delivery verified,以及包含运行及任务 ID、Bucket、区域、对象 Key、已验证大小和 MD5 的记录。这是脚本创建的应用记录。将它与 delivery.json 及原始任务一同归档;API 结果过期后仍可保留。

转录、索引或其他处理任务可将已验证的 localFile 交给应用的处理进程。若需供用户下载,继续第 6 步。

6. 让应用受控访问文件

在后端确认用户有权访问,再从自己的存储读取该用户对应的 ready 记录,随后创建短期 S3 下载 URL。使用已保存的目标,不接受浏览器提供的 Bucket 或对象 Key。

SDK 使用后端的 AWS 读取身份,不会发送 FlashData 查询。

S3 版本控制提供版本 ID 时,URL 指向已验证的对象版本。没有版本 ID 时,验证后不要覆盖输出 Key。读取指定版本的身份需要 s3:GetObjectVersion;无版本读取需要 s3:GetObject。

在 pipeline.py 旁创建 create-download-link.py,复制下方完整代码并保存。使用开始时安装的 Boto3。

create-download-link.py
# create-download-link.py — run in your backend after authorizing the user.
import json
import os
import sys

import boto3
from botocore.config import Config
from pipeline import delivery_directory, read_json


def main():
    os.umask(0o077)
    # In an app, load this user's verified ready record from your own store.
    directory = delivery_directory() / 'verified'
    ready = read_json(directory / 'ready.json')
    if any(not isinstance(ready.get(key), str) or not ready[key]
           for key in ['bucket', 'region', 'objectKey', 'verifiedAt']):
        raise ValueError('Use the ready.json produced by the verification step.')
    destination = directory / 'access.json'
    if destination.exists():
        raise FileExistsError('Keep the existing access.json or choose a new output filename.')
    params = {'Bucket': ready['bucket'], 'Key': ready['objectKey']}
    version = ready.get('storageVersionId')
    if version and version != 'null':
        params['VersionId'] = version
    s3 = boto3.client('s3', region_name=ready['region'], config=Config(signature_version='s3v4'))
    url = s3.generate_presigned_url('get_object', Params=params, ExpiresIn=300, HttpMethod='GET')
    with destination.open('x', encoding='utf-8') as output:
        json.dump({'url': url, 'expiresInSeconds': 300}, output, indent=2)
    # Do not log the signed URL; return it only to the authorized user.
    print('Access record saved:', destination)


if __name__ == '__main__':
    sys.stdout.reconfigure(encoding='utf-8')
    sys.stderr.reconfigure(encoding='utf-8')
    try:
        main()
    except Exception as error:
        print(str(error), file=sys.stderr)
        sys.exit(1)

预期生成私有 access.json,包含 url 及 expiresInSeconds: 300。后端仅向有权访问的用户返回 URL。持有者最多可在五分钟内下载文件;签名凭据提前过期时,链接也会提前失效。

用户下次请求访问时,从保存的 ready 记录创建新链接。在数据库保存对象 Key 及版本,不把会过期的 URL 当作永久资产地址。本地示例在 access.json 已存在时会停止。

创建五分钟有效链接
python create-download-link.py

从最后确认的阶段重启

情况后续操作
任务已接纳 / 本地等待超时使用同一 runId 再次 runs recover,写入新的尝试目录。
S3 拒绝访问或读取中断修复 AWS 读取身份或连接。恢复到新目录后再验证,保留之前的不完整文件。
字节数 / MD5 / 目标不匹配停止。使用媒体前,核对交付记录、对象版本及预期目标。
verified/ 已存在读取其中的 ready.json,或检查未完成验证。脚本不会覆盖现有目录。
应用下载 URL 已过期再次确认访问权限,为已保存的对象及版本签名。无需再次提交 FlashData 下载。
run_id_input_conflict请求已变化。恢复原运行;仅在明确创建新输出时使用新 runId。
401 / 403 / 402 / 429修复访问、权限或余额;遵循 Retry-After。重试提交前检查已有工作。

将相同阶段用于队列

  1. 从一个正在处理的任务开始。提高应用并发前读取当前限额。
  2. 为每个视频及输出版本保留一个持久 runId,并使用不同目标前缀。在应用数据库中保存账户、任务 ID 及最终结果。
  3. 跨进程重启持久化 CLI 状态目录。不同机器需要共享应用协调;本地运行日志不对独立状态目录去重。
  4. 通过 ready.json 将任务交给后续处理。逐项保留失败记录,以复用成功交付。