コンテンツへスキップ
JA
APIキーを取得する
ドキュメントを探す

ガイド

メディア配信パイプラインの構築

MP4をプライベートS3ストレージにダウンロードし、再起動後に再開し、確認されたファイルへのアプリケーションアクセスを与えます。

このページの内容

ビルドする

耐久性のあるアイテムは、IDからアプリケーション対応のファイルに移動します。 各ステージをディスクに保存することで、最終確認結果から新しいプロセスが続行できます。

パイプラインと保存されたレコード
item.jsonの特長
  → 一度送信 → 保存実行 + ジョブ ID
  → ジョブを回復 → delivery.json
  → S3バイト → media.mp4 + ready.json
  → アプリのユーザーを承認 → 短命ダウンロード URL

はじめる前に

6つのステップで1つの例のパスを選択します。 FlashData CLIは、保存された所有者プロファイルとyoutube_downloadのパーミッション、アップロード用のプライベートS3 storage.json、および配信されたオブジェクトを読むことができるAWS IDを使用します。

Python 3.10+をPython環境で使用して下さい。 スクリプトは、CLI を呼び出して、実行ジャーナルを保存し、Bto3 は S3 を読み込み、リンクを署名します。 Bash、jq、Node.js、AWS CLIは必要ありません。 python で以下のコマンドを実行するか、 python3 は、通訳者名である場合は python3 を実行します。

Pythonの依存性をインストール
python --version
flashdata --version
python -m pip install boto3

実行時間の設定を保存

ソースコントロールの外部のプライベートアイテムフォルダを作成します。 選択したパスの設定を保存し、絶対パスとプロファイル名を編集します。 各工程では、保存したアカウントとジャーナルの実行が使用されます。 ストレージの資格情報は、プライベートstorage.jsonにとどまります。 一度に1つの項目ごとの1つのプロセスを実行して下さい。

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. 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、残高、1TB当たりのレートと制限を確認します。 最終手数料はアップロードされたバイトによって異なります。

環境・アカウントの確認
python pipeline.py check

ダウンロードなしで検証

ヘルパーを保存した後、ドライランを実行します。 Pythonはok: trueおよびdryRun: trueを印刷します; Bashはtrueを印刷します。 これにより、メディアの作業やクレジットの保存をすることなく、入力とアクセスを検証します。

無料ドライラン
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をキープします。
succeededRecover/exportは保存された応答を、そして貯蔵を確かめます。 新規登録は行いません。
不明な結果/確認されていない仕事ID実行、レシート、エラーをキープします。 History または別の投稿を決定する前に IDs を調べます。

4. 配達記録を回復して下さい

任意の新しいターミナルの項目フォルダから実行します。 復元は、元のジョブを待って、delivery.json、run.json、レシートを含むディレクトリを印刷します。 10-minuteのタイムアウトはローカルの待機を停止します;同じ仕事を再開するために回復を繰り返して下さい。

保存したジョブを再開

リユース pipeline.py ステップで保存 2. 追加のスクリプトは必要ありません。

既存のジョブを回復する · 新規投稿なし
python pipeline.py recover

納品されたオブジェクトの特定

S3オブジェクトURL、正なファイルサイズ、MD5を期待してください。 プライベートオブジェクトは、AWS の読み取り ID が必要です。 Python は、delivery-dir.txt の成功ディレクトリを後でスクリプトに保存します。 Bash は DELIVERY_DIR を保持します。新しいターミナルでは、印刷されたディレクトリに設定します。

配達記録
python pipeline.py delivery

5. 既定のマークを付ける前にバイトを検証

バリファイアーは、元の入力、S3バケットとプレフィックスをチェックし、プライベートオブジェクトをディスクにストリームし、バイト数とMD5を比較します。 マッチングファイルのみがverified/ready.json.を生成 Pythonはdelivery-dir.txtを読みました; NodeはDELIVERY_DIRを使用します。 FlashData クエリを提出する。

検証スクリプトを保存

この頂点は標準のAmazon S3オブジェクトURLsを扱います。 カスタムエンドポイントまたは別のプロバイダーでは、認証されたオブジェクトを読み取り、同じ宛先、バイトカウント、チェックサムチェックを保持します。

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をアプリケーションにオフ

run/job IDs、バケット、地域、オブジェクトキー、検証済みサイズ、MD5を含むレコードを期待してください。 これは、スクリプトによって作成されたアプリケーションのレコードです。 delivery.jsonと元のアイテムでアーカイブします。 APIの結果の保持ウィンドウを存続させます。

トランスクリプション、インデックス作成、またはその他の処理のために、検証済みのlocalFileをワーカーに渡します。 ユーザ向けダウンロードでは、6のステップを続けてください。

6. アプリケーション管理されたアクセスを与える

バックエンドでは、ユーザを承認し、自分のストアでユーザーの既定のレコードを調べます。 その後、短命のS3のダウンロードURLを作成します。 保存先を使用して下さい。ブラウザが供給する Bucket や object キーは受け付けません。

SDK はバックエンドの AWS 読み取り ID を使用します。 FlashDataのクエリは送信されません。

URL は、S3 のバージョンアップ時に検証されたオブジェクトバージョンの名前を 1 つ付けます。 バージョンIDがなければ、各出力キーのimmutableを点検の後で保って下さい。 特定のバージョンを読み込みる ID は 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のみを認証されたユーザーに返します。 ファイルを最大5分間ダウンロードすることができます。 署名の資格情報で以前の期限が切れる可能性があります。

ユーザの次のリクエストアクセス時に保存された既定のレコードから新しいリンクを作成します。 URLをアセットアドレスとして拡張するのではなく、オブジェクトキーとバージョンをデータベースに保存します。 access.json が既に存在していると、このローカルの例は止まります。

5分のリンクを作成
python create-download-link.py

最終確認段階から再スタート

投稿ナビゲーション次のアクション
受入ジョブ / ローカル待機タイムアウトruns recover を同じ runId で新しい試みのディレクトリに繰り返します。
S3アクセス拒否または中断された読み取りAWS の読み取り ID または接続を修正します。 新規ディレクトリに復元し、再度確認します。以前の部分的なファイルを保持します。
バイト数 / MD5 / 目的地の不一致ストップ。 メディアを使用する前に、マニフェスト、オブジェクトバージョン、および計画された目的地を比較します。
検証済み/既に存在するready.json を読んで、または不完全な検証を検査してください。 スクリプトは上書きしません。
アプリケーションのダウンロード URL 期限切れアクセスを再度承認し、保存されたobject/version.に署名して下さい 別のFlashDataのダウンロードを提出しないでください。
run_id_input_conflictリクエストが変更されました。 元の実行を回復する。意図的な新しい出力のためにだけ新しいrunIdを使用して下さい。
401 / 403 / 402 / 429アクセス、アクセス許可、残高の修正、Retry-Afterのフォロー 投稿を再試行する前に保存した作業を点検します。

同じステージをキューに入れる

  1. 1つの機内アイテムから始めましょう。 アプリケーションの通貨を増やす前に、現在の制限値を読みます。
  2. video/outputバージョンごとに耐久性のあるrunIdを1つ保存し、異なる宛先プレフィックスで保存します。 アプリケーションデータベースのアカウント、ジョブID、最終結果を保存します。
  3. プロセスの再起動を渡る CLI 状態のディレクトリを永続化します。 別々のマシンは、共有アプリケーション協調を必要としています。ローカルランジャーナルは独立した州のディレクトリを複製しません。
  4. ready.jsonは、下流処理へのハンドオフとして使用します。 失敗したアイテムを個々に保持し、配送が成功する。