İçeriğe geç
TR
API anahtarı al
Belgeleri incele

Kılavuzlar

Bir medya teslimat boru hattı inşa edin

Bir MP4'ü özel S3 depolamasına indirin, bir yeniden başlayın ve uygulama erişiminizi doğrulanan dosyaya verin.

Bu sayfada

Ne inşa edeceksin

Bir dayanıklı öğe bir video ID'dan bir uygulama hazır dosyasına taşınır. Disk üzerinde her aşamayı tutun, böylece yeni bir süreç son doğrulanan sonuçtan devam edebilir.

Boru Hattı ve Kurtarılan Kayıtlar
item.json
  → bir kez gönderin → iş + iş ID
  → İşi Kurtarın → delivery.json
  → S3 bytes → media.mp4 + ready.json
  → Uygulama kullanıcısını yazar → kısa ömürlü indirme URL

Başlamadan önce başlamadan önce

Tüm altı adım için bir örnek yol seçin. Her ikisi de yüklü bir FlashData CLI'u kurtardı bir sahibi profili ve youtube_download izni ile, özel S3 storage.json yüklemeler için ve teslim edilen nesneyi okuyabilen bir AWS kimliği kullanır.

Python 3.10+'nızı Python ortamınızda kullanın. Senaryolar, CLI'u işletme kitabını korumak için çağırır ve S3'u okumak ve bağlantıları imzalamak için Boto3. Bash, jq, Node.js ve AWS CLI gerekli değildir. Aşağıdaki komutları python ile çalıştırın veya python3 eğer bu sizin tercüman adınızsa.

Python bağımlılık
python --version
flashdata --version
python -m pip install boto3

runtime ayarlarını kurtarın

Kaynak kontrolü dışındaki özel bir öğe klasörü oluşturun. Seçilen yolunuz için ayarları kurtarın ve mutlak yolları ve profil adını düzenler. Her işlem, hesabı kaydedilen ve yayınlayan bir dergi kullanır. Depolama bilgileri özel storage.json'da kalır. Bir seferde bir öğe için bir işlem yapın.

pipeline.json'u kurtarın. Windows, C:/private/flashdata-state'de C:JSON gibi ileri giden yollarda.

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

1. Bir dayanıklı öğeyi Kurtarın

item.json'u bu klasörde kurtarın. Video ve S3 hedefini değiştirin; bu örnek bir MP4'ü 720p'e kadar talep eder. runId'u yeniden ziyaret etmek için tut. Farklı planlı bir çıktının yeni bir runId'ya ihtiyacı vardır ve nesne önyükleme.

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. Senaryoyu kurtarın ve erişim kontrol edin

Kontrolleri çalıştırmadan önce aşağıdaki dosyayı oluşturun. S3 hedefini doğrular ve her bir teslim girişimi için bir makbul tutar.

Boru hattı senaryoyu oluşturun

Create Create CreateCreate Create Create pipeline.py Aynı klasörü aynı klasörde pipeline.json Ve ve item.json. Bu dosyaya aşağıdaki tam kodu kopyalayın ve onu kurtarın. Bunu kontroller, teslimiyet ve kurtarma için 2–4'un adımlarında tekrarlayabilirsiniz.

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)

Kurtarılan hesabınızı kontrol edin

Bu ücretsiz check from the item klasör after saving the script. Kayıp sahibi erişim veya youtube_download izni kontrolü durdurur. Hesap ID, denge, per-TB oranı ve sınırları onaylayın. Nihai şarj, yüklenenlere bağlıdır.

Çevreyi kontrol edin ve hesaplayın
python pipeline.py check

Bir indirme olmadan doğrulama

Yardımı kurtardıktan sonra, kuru çalışmasını çalıştırın. Python baskıları ok: true ve dryRun: true; Bash baskıları true. Bu, medya işlerini sunmadan veya rezerve etme kredilerini doğrulamadan giriş ve erişimi doğrulamaktadır.

Ücretsiz kuru koşmak
python pipeline.py dry-run

3. İşi ID'u gönderin ve korur

Bu, bir ücretli arka yükleme gönderir. status: accepted ve bir jobId yerel koşuda bekleyin. Profili, eyalet rehberi ve item.json'u kurtarma için tut. Medya sadece 5 adımdan sonra hazır.

Bir kez gönder
python pipeline.py submit
Inspect yerel devlet · yeni bir sorgu yok
python pipeline.py inspect

Eğer koşma zaten kurtarılır veya belirsiz

CLI eyaletAction Action Action
accepted + jobIdBu işlemi 4'un adımını yeniden keşfedin. Süreç durursa işi ID’u tut.
succeededRecover/export, kurtarılan cevabı, sonra depolamayı doğrulayın. Yeni bir öğe göndermeyin.
Bilinmeyen sonuç / doğrulanmamış iş IDrun, makbuz ve hata tutun. Inspect History veya aday IDs başka bir teklife karar vermeden önce.

4. Teslimat kayıtlarını yeniden keşfedin

Yeni bir terminaldeki öğe klasöründen hareket edin. Kurtarma orijinal iş için bekler ve delivery.json, run.json ve makbuz içeren bir dizi baskı yapar. A 10- dakikalık bir süre yerel beklemeyi durdurur; aynı işi yeniden başlatmak için kurtarmayı tekrarlayın.

Kurtarılan işi yeniden yapılandırın

Reuse pipeline.py, 2'un adımında kurtarıldı. Hiçbir ek senaryoya ihtiyaç yoktur.

Mevcut işi yeniden keşfedin · yeni bir gönderim yok
python pipeline.py recover

Teslim edilen nesneyi Müfettiş

Bir S3 nesne URL, pozitif bir dosya boyutu ve bir MD5. Özel nesneler AWS okuma kimliğinize ihtiyaç duyar. Python, daha sonra senaryolar için delivery-dir.txt'daki başarılı diziyi kurtarır. Bash, DELIVERY_DIR'u tutar; yeni bir terminalde, basılı bir diziye yerleştirin.

Teslimat kayıt kaydı
python pipeline.py delivery

5. Hazırlanmadan önce

Verilendirici orijinal girişini kontrol eder, S3 kova ve eki, özel nesneyi diske yönlendirir ve kendi sayılarını ve MD5 ile karşılaştırır. Sadece eşleşen dosyalar verified/ready.json. Python, delivery-dir.txt okur; Node DELIVERY_DIR'u kullanır. Ne bir FlashData sorgu göndermiyor.

Doğrulama senaryoyu kurtarın

Bu doğrulayıcı standart Amazon S3 object URLs. Özel uç noktaları veya başka bir sağlayıcı için, asıllı nesnesini okuyun ve aynı varış noktasını, aste-count ve checksum kontrollerini kullanın.

verify-media.py'un yanında pipeline.py oluşturun ve aşağıdaki tam kodu kopyalayın. Her iki dosyayı öğe klasöründe kurtarın.

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)

doğrulamayı çalıştırın

Senaryoyu kurtardıktan sonra, onu öğe klasöründen çalıştırın.

Verify ve handoff rekorunu okuyun
python verify-media.py

ready.json'dan uygulamanıza

run/job IDs, kova, bölge, nesne anahtarı, doğrulanmış boyut ve MD5 içeren bir kayıt. Bu, uygulamanızın kaydıdır, senaryo tarafından yaratılan. delivery.json ve orijinal eşya ile Archive; API sonucun tutma penceresinin hayatta kalması.

Transkript için, indeksleme veya diğer işleme için, doğrulanan localFile'yu işçinize geç. Bir kullanıcı arayüzü indirme için, 6 adımla devam edin.

6. Uygulama kontrollü erişiminizi verin

Arkanızda, kullanıcıyı yazar ve bu kullanıcının kendi mağazanızda hazır rekorunu görün. Sonra kısa ömürlü bir S3 indir URL. Kurtarılan varış noktasını kullanın; tarayıcı tarafından sağlanan bir kova veya nesne anahtarını kabul etmeyin.

SDK, arka uçun AWS'nin kimliklerini kullanır. FlashData sorgu gönderilir.

URL, S3 sürümlemenin bir tane sağladığı doğrulanmış nesne sürümünü adlandırıyor. Bir sürüm olmadan ID, doğrulamadan sonra her bir çıkış anahtarını mümkün tut. Belirli bir versiyonda okuyan bir kimlik s3'e ihtiyaç duyar:GetObjectVersion; bir ters olmayan okuma s3:GetObject.

create-download-link.py'un yanında pipeline.py oluşturun ve aşağıdaki tam kodu kopyalayın. Başlangıçta yüklenen Boto3 paketi kullanır.

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 ve expiresInSeconds içeren özel bir access.json: 300. Geri dönüşünüz yalnızca URL'yu yetkili kullanıcıya döndürür. Dosyayı beş dakikaya kadar indirmeye çalışan herkes; imza bildirimleri ile daha önce sona erebilir.

Kullanıcının bir sonraki istekleri erişim olduğunda kaydedilen hazır kayıttan yeni bir bağlantı oluşturun. Veritabanınızda nesne anahtarını ve versiyonunu tutun, çünkü URL'u varlık adresi olarak depolamak yerine. Bu yerel örnek, access.json'un zaten var olup olmadığını durdurur.

Beş dakikalık bir bağlantı oluşturun
python create-download-link.py

Son doğrulanan sahneden yeniden başlayın

Durum durumuSonraki eylem
Kabul edilen iş / yerel bekleme süresiTekrar runs recover ile aynı runId ile taze bir deneme rehberine.
S3 erişim inkar veya kesinti okumaAWS'nin kimlik veya bağlantı okumasını düzeltin. Taze bir diziyi yeniden keşfedin ve tekrar doğrulayın; önceki kısmi dosyayı saklayın.
Byte count / MD5 / destinasyon yanlışDur. Açık, nesne versiyonuyla karşılaştırın ve medyayı kullanmadan önce hedef planlayın.
Doğrulanmış / zaten varready.json'unu okuyun veya eksik doğrulamasını kontrol edin. Senaryo bunu yazmayacak.
Uygulama indir URL expiredTekrar erişim ve kaydedilen object/version.'u imzalamak. Başka bir FlashData indir göndermeyin.
run_id_input_conflictİstek değişti. Orijinali keşfedin; yeni bir runId kullanın sadece bir niyet yeni çıktı için.
401 / 403 / 402 / 429Fix access, permissions veya denge; Retry-After'yu takip edin. Inspect, bir gönderimi yeniden denemeden önce çalışmayı kurtardı.

Aynı aşamaları bir kuyruka uygulayın

  1. Bir in-flight item ile başlayın. Geçerli sınırları giderek artan uygulama koncurrency'i okuyun.
  2. Her video/output versiyonu için dayanıklı bir runId sürüm tutun, ayrı bir varış noktası ekle. Hesap, iş ID ve uygulama veritabanınızda son sonuç.
  3. Süreç boyunca CLI eyalet rehberi yeniden başlar. Ayrı makineler ortak uygulama koordinasyonuna ihtiyaç duyar; yerel bir işletme dergisi bağımsız devlet müdürlerini deşifre etmez.
  4. ready.json'u alt işlemeye devre dışı bırakmak olarak kullanın. Retain başarısız öğeleri bireysel olarak bu kadar başarılı teslimatlar yeniden kullanılabilir.