본문으로 건너뛰기
KO
API 키 받기
문서 둘러보기

가이드

미디어 납품 파이프라인 구축

MP4를 개인 S3 저장소에 다운로드하고 재시작 후 등록하고 확인된 파일에 응용 프로그램을 제공합니다.

이 페이지의 내용

당신이 빌드 할 것

하나의 튼튼한 항목은 비디오 ID에서 응용 프로그램 읽기 파일로 이동합니다. 디스크에 각 단계를 유지하므로 새로운 프로세스는 마지막 확인 된 결과에서 계속 될 수 있습니다.

Pipeline 및 저장된 기록
item.json
  → 한 번 제출 → 저장된 실행 + 작업 ID
  → 작업 복구 → delivery.json
  → S3 바이트를 확인 → media.mp4 + ready.json
  → 앱 사용자 승인 → 짧은 라이브 다운로드 URL

시작하기 전에

모든 6단계를 위한 1개의 예 경로 선택. 둘 다 설치했습니다 FlashData CLI 저장된 소유자 프로필과 함께 youtube_download 권한, 개인 S3 storage.json 업로드 및 전달된 객체를 읽을 수 있는 AWS 정체성을 위해.

Python 3.10+를 Python 환경에서 사용하십시오. 스크립트는 CLI를 호출하여 실행 저널을 보존하고 Boto3는 S3 및 서명 링크를 읽습니다. Bash, jq, Node.js 및 AWS CLI는 필요하지 않습니다. 아래 명령어를 python, 또는 python3로 실행하면 해석자명입니다.

Python 의존성 설치
python --version
flashdata --version
python -m pip install boto3

runtime 설정 저장

외부 소스 컨트롤을 사용하여 개인 아이템 폴더를 만듭니다. 선택된 경로에 대한 설정을 저장하고 절대 경로와 프로필 이름을 편집합니다. 각 프로세스는 저장된 계정 및 실행 저널을 사용합니다. 저장 자격은 개인 storage.json에 머물. 한 번에 아이템당 하나의 프로세스를 실행합니다.

pipeline.json를 저장하십시오. Windows에서 C:/private/flashdata-state와 같은 앞으로 슬래시 경로는 JSON에서 작동합니다.

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

1. 1개의 튼튼한 품목을 저장하십시오

그 폴더에 item.json를 저장합니다. 비디오 및 S3 목적지를 대체하십시오. 이 예는 최대 720p의 MP4를 요청합니다. retries에 대한 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 timeout는 국부적으로 대기를 멈추고; 동일한 일을 재개하는 반복 회복.

저장된 일을 재량

재사용 pipeline.py는 단계 2에서 저장했습니다. 추가 스크립트가 필요하지 않습니다.

기존의 작업을 복구 · 새로운 제출 없음
python pipeline.py recover

전달된 객체를 검사

S3 객체 URL, 긍정적인 파일 크기 및 MD5를 기대합니다. 개인 객체는 AWS 읽기 ID가 필요합니다. Python는 나중에 스크립트에 delivery-dir.txt의 성공적인 디렉토리를 저장합니다. Bash는 DELIVERY_DIR를 유지합니다; 새로운 맨끝에서, 인쇄한 디렉토리에 그것을 놓으십시오.

납품 기록
python pipeline.py delivery

5. 표시하기 전에 바이트를 검증

Verifier는 원래 입력, S3 버킷 및 접두사를 확인하고 디스크에 개인 객체를 스트림하고 바이트 수와 MD5를 비교합니다. 만 일치 파일 생성 verified/ready.json. Python는 delivery-dir.txt를 읽습니다; 노드는 DELIVERY_DIR를 사용합니다. Neither는 FlashData 쿼리를 제출합니다.

인증 스크립트 저장

이 verifier는 표준 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)

확인을 실행

스크립트를 저장한 후, 아이템 폴더에서 실행합니다.

Handoff 기록 확인 및 읽기
python verify-media.py

ready.json에서 응용 프로그램으로 손

run/job IDs, 버킷, 지역, 객체 키, 확인된 크기 및 MD5를 포함하는 예상 납품 및 기록. 이것은 스크립트에 의해 생성 된 응용 프로그램의 기록입니다. delivery.json 및 원래 아이템으로 보관하십시오. API 결과의 보존 창을 생존합니다.

비문, 색인 또는 기타 처리의 경우 확인된 localFile를 작업자에게 전달합니다. 사용자 인터페이스 다운로드를 위해, 단계 6로 계속.

6. 당신의 응용 프로그램 제어 액세스

귀하의 백엔드에서 사용자를 승인하고 자신의 상점에서 사용자의 준비 기록을 찾습니다. 그런 다음 S3 다운로드 URL를 단축했습니다. 저장된 목적지를 사용; 브라우저에 의해 공급된 물통 또는 물체 열쇠를 받아들이지 마십시오.

SDK는 백엔드의 AWS 읽기 정체성을 사용합니다. FlashData 쿼리가 전송되지 않습니다.

URL는 S3 버전을 사용할 때 확인된 객체 버전을 이름을 지정합니다. 버전 없이 ID는, 각 산출 열쇠를 확인 후에 immutable 지킵니다. 특정 버전이 s3:GetObjectVersion을 읽는 ID; unversioned read needs 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)

url 및 expiresInSeconds를 포함하는 개인 access.json를 기대하십시오: 300. 귀하의 백엔드는 URL만 승인된 사용자에 반환합니다. 누구나 최대 5 분 동안 파일을 다운로드 할 수 있습니다. 서명 자격 증명과 함께 일찍 만료 될 수 있습니다.

사용자의 다음 요청 액세스를 요청할 때 저장된 Ready 레코드에서 새로운 링크를 만듭니다. 자산 주소로 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개의 in-flight 품목으로 시작하십시오. Application concurrency를 증가하기 전에 현재 제한을 읽으십시오.
  2. 각 video/output 버전에 대한 하나의 내구성 runId를 유지, 특정 목적지 접두사와. 계정 저장, 작업 ID 및 응용 데이터베이스에서 최종 결과.
  3. 프로세스 재시작을 통해 CLI state 디렉토리를 Persist합니다. 별도의 기계가 공유 응용 프로그램 조정 필요; 로컬 실행 저널은 독립적 인 국가 감독을 파괴하지 않습니다.
  4. ready.json를 다운스트림 처리로 사용하십시오. Retain failed items 개별적으로 그래서 성공적인 배송은 재사용됩니다.