# Xây dựng một đường ống giao hàng phương tiện

Tải một MP4 về riêng S3 lưu trữ, phục hồi sau khi khởi chạy lại và cho phép truy cập vào tập tin đã kiểm tra.

Tài liệu tham khảo chính điển: https://flashdata.dev/vi/docs/guides/media-delivery-pipeline
Xem lại: 2026-11-05 by FlashData

<a id="prepare"></a>

## Những gì bạn sẽ xây dựng

Một vật bền vững di chuyển từ video ID trong tập tin đã có sẵn. Giữ mỗi giai đoạn trên đĩa để có thể tiếp tục quá trình mới từ kết quả được xác nhận cuối cùng.

### Đường ống và lưu hồ sơ

```text
item.json
  Đang đệ lại _một lần lưu lưu chạy + công việc ID
  ▪ Phục hồi công việc delivery.json
  Xác nhận S3 byte  tôm media.mp4 + ready.json
  Trình tải về ngắn nhất cho phép người dùng ứng dụng hợp lệ URL
```

- [Chọn âm thanh, phim ảnh hay clip](https://flashdata.dev/vi/docs/guides/youtube-download-guide/reference.md#formats)

<a id="requirements"></a>

### Trước khi bắt đầu

Chọn một đường dẫn cho cả sáu bước. Cả hai đều dùng một cài đặt FlashData CLI với hồ sơ người sở hữu đã lưu và youtube_download cho phép, riêng tư S3 storage.json để tải lên, và một danh tính của AWS có thể đọc được đối tượng được giao.

#### Python

Dùng Python 3.10+ trong của bạn Python môi trường. Văn lệnh gọi là CLI để giữ quyển nhật ký chạy của nó, và Boto3 để đọc S3 và ký tên vào liên kết. Bash, jq, Node.js và AWS CLI không cần thiết. Chạy lệnh bên dưới với python, hoặc python3 nếu đó là tên bộ giải thích của bạn.

##### Cài đặt phụ thuộc Python

```bash
python --version
flashdata --version
python -m pip install boto3
```


#### Bash / Node.js

Cài đặt Bash, jq, Node.js 22+ và AWS CLI v2. Vào WindowsChạy đi Bash lệnh vào Git Bash. Cài đặt nút S3 Ký các gói trong bước 6.


- [Tải về](https://flashdata.dev/vi/docs/guides/download-video-recipe/reference.md)
- [Thiết lập storage.json riêng](https://flashdata.dev/vi/docs/guides/cli-automation/reference.md#storage)
- [Lưu hồ sơ](https://flashdata.dev/vi/docs/guides/cli-automation/reference.md#profiles)
- [Thông tin về Boto3 AWS](https://docs.aws.amazon.com/boto3/latest/guide/credentials.html)

<a id="environment"></a>

### Lưu thiết lập thời gian chạy

Tạo một thư mục riêng bên ngoài điều khiển nguồn. Lưu thiết lập cho đường dẫn đã chọn và sửa đổi các đường dẫn và tên hồ sơ tuyệt đối. Mỗi tiến trình sử dụng để lưu tài khoản và chạy tạp chí. Giấy phép lưu trữ sẽ được giữ kín. storage.json. Chạy một quá trình cho mỗi món đồ một lần.

#### Python

Cứu pipeline.json. Vào Windows, các con đường chớp phía trước như C:/private/flashdata-state làm việc trong JSON.

##### pipeline.json

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


#### Bash

##### pipeline.env

```bash
# pipeline.env — edit these paths for your existing installation.
export FLASHDATA_STATE_DIR='/absolute/path/to/flashdata-state'
export FLASHDATA_STORAGE_CONFIG='/absolute/path/to/private/storage.json'
export FLASHDATA_PROFILE='default'
# Use the saved profile for every process.
unset FLASHDATA_API_KEY
```



<a id="design"></a>

## 1. Lưu một mục bền bỉ

Lưu item.json trong thư mục đó. Thay thế đoạn video và S3; ví dụ này yêu cầu một MP4 ở mức 720p. Giữ nó runId Để trả đũa. Một kết xuất đã lên kế hoạch khác cần một kết xuất mới runId và đối tượng tiền tố.

### item.json

```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"
  }
}
```


<a id="check"></a>

## 2. Lưu văn lệnh và kiểm tra truy cập

Tạo tập tin bên dưới trước khi kiểm tra. Nó xác nhận S3 Nơi đến và giữ biên lai cho mỗi lần nộp đơn.


<a id="request-script"></a>

### Tạo văn lệnh đường ống

#### Python

Tạo pipeline.py trong cùng thư mục như pipeline.json và item.json. Sao chép toàn bộ mã lệnh bên dưới vào tập tin đó và lưu nó. Bạn sẽ tái sử dụng nó để kiểm tra, nộp và phục hồi trong bước 2–4.

##### pipeline.py

```python
# 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)
```


#### Bash

Tạo request-media.sh trong cùng thư mục như pipeline.env và item.json. Sao chép toàn bộ mã lệnh bên dưới vào tập tin đó và lưu nó.

##### request-media.sh

```bash
#!/usr/bin/env bash
set -euo pipefail
umask 077
cd -- "$(dirname -- "$0")"
. ./pipeline.env
: "${FLASHDATA_STATE_DIR:?Set your existing absolute CLI state directory}"
: "${FLASHDATA_STORAGE_CONFIG:?Set the absolute path to private storage.json}"
action=${1:-dry-run}
[[ "$action" == dry-run || "$action" == submit ]] || exit 2
run_id=$(jq -er '.runId | select(type == "string" and length > 0)' item.json)
request() {
  jq -en --slurpfile item item.json --slurpfile storage "$FLASHDATA_STORAGE_CONFIG" '
    $item[0] as $i | $storage[0] as $s
    | if $i.request.source != "youtube_download"
        or $s.storage_type != "s3" or $s.storage_url != $i.destination.bucket
        or $s.region != $i.destination.region
      then error("Check item.json and the S3 destination in storage.json")
      else $i.request | .params.storage = ($s + {object_prefix: $i.destination.prefix}) end'
}
args=(query --input - --mode async --run-id "$run_id"
  --profile "${FLASHDATA_PROFILE:-default}" --state-dir "$FLASHDATA_STATE_DIR"
  --json --non-interactive)
if [[ "$action" == dry-run ]]; then
  request | flashdata "${args[@]}" --dry-run
else
  mkdir -p attempts
  attempt=$(mktemp -d attempts/submit.XXXXXX)
  if ! request | flashdata "${args[@]}" --output "$attempt/submission.json" \
    > "$attempt/receipt.json" 2> "$attempt/error.json"; then
    cat "$attempt/error.json" >&2
    printf 'Keep %s; inspect the saved run before retrying.\n' "$attempt" >&2
    exit 1
  fi
  jq '{runId, cached, data}' "$attempt/receipt.json"
  printf 'Saved receipt: %s/submission.json\n' "$attempt"
fi
```



<a id="access-check"></a>

### Kiểm tra tài khoản đã lưu của bạn

Chạy tùy chọn này từ thư mục sau khi lưu tập lệnh. Thiếu quyền truy cập chủ sở hữu hoặc youtube_download quyền hạn sẽ ngăn chặn việc kiểm tra. Xác nhận tài khoản ID, số dư, tốc độ và giới hạn. Tội danh cuối cùng phụ thuộc vào các byte được tải lên.

#### Python

##### Kiểm tra môi trường và tài khoản

```bash
python pipeline.py check
```


#### Bash

##### Kiểm tra môi trường và tài khoản

```bash
set -euo pipefail
. ./pipeline.env
: "${FLASHDATA_STATE_DIR:?Set your existing absolute CLI state directory}"
: "${FLASHDATA_STORAGE_CONFIG:?Set the absolute path to private storage.json}"
flashdata --version
jq --version
node --version
aws --version
flashdata auth status --profile "${FLASHDATA_PROFILE:-default}" \
  --state-dir "$FLASHDATA_STATE_DIR" --json --non-interactive |
  jq -e 'if .ok and .data.accessVerified
    and (.data.identity.identity.recurringAllowed == true)
    and (.data.identity.permittedSources | index("youtube_download") != null)
    then {accountId: .data.identity.identity.accountId,
          permittedSources: .data.identity.permittedSources}
    else error("Owner access with youtube_download is required.") end'
flashdata account balance --profile "${FLASHDATA_PROFILE:-default}" \
  --state-dir "$FLASHDATA_STATE_DIR" --json --non-interactive
flashdata account pricing --source youtube_download --request-count 1 \
  --profile "${FLASHDATA_PROFILE:-default}" --state-dir "$FLASHDATA_STATE_DIR" --json --non-interactive
flashdata account limits --profile "${FLASHDATA_PROFILE:-default}" \
  --state-dir "$FLASHDATA_STATE_DIR" --json --non-interactive
```


- [Trở về nguồn văn lệnh](https://flashdata.dev/vi/docs/guides/media-delivery-pipeline/reference.md#request-script)

<a id="dry-run"></a>

### Kiểm tra lại mà không tải xuống

Sau khi cứu người giúp việc, hãy chạy hết sức mình. Python In ấn ok: true và dryRun: true; Bash In ấn true. Điều này xác nhận nhập và truy cập mà không cần gửi tín dụng phương tiện truyền thông.

#### Python

##### Chạy tự do

```bash
python pipeline.py dry-run
```


#### Bash

##### Chạy tự do

```bash
set -euo pipefail
bash request-media.sh dry-run | jq -e '.ok and .data.dryRun'
```



<a id="dispatch"></a>

## 3. Phục tùng và giữ lại công việc ID

Đây là một bản tải về được trả tiền. Mong đợi status: accepted và a jobId trong cuộc điều hành địa phương. Giữ hồ sơ, thư mục chính và item.json để hồi phục. Truyền thông đã sẵn sàng chỉ sau bước 5.

### Python

#### Phục tùng một lần

```bash
python pipeline.py submit
```

#### Kiểm tra tình trạng cục bộ # không có truy vấn mới

```bash
python pipeline.py inspect
```


### Bash

#### Phục tùng một lần

```bash
bash request-media.sh submit
```

#### Kiểm tra tình trạng cục bộ # không có truy vấn mới

```bash
set -euo pipefail
. ./pipeline.env
RUN_ID=$(jq -er '.runId' item.json)
flashdata runs show "$RUN_ID" --profile "${FLASHDATA_PROFILE:-default}" \
  --state-dir "$FLASHDATA_STATE_DIR" --json --non-interactive |
  jq '{runId, status: .data.status, jobId: .data.remoteId,
       errorCode: .data.errorCode, candidateJobIds: .data.candidateRemoteIds}'
```



<a id="job-state"></a>

### Nếu chạy bộ đã lưu hay không chắc chắn

| Trạng thái CLI | Hành động |
| --- | --- |
| accepted + jobId | Phục hồi điều này chạy trong bước 4. Giữ công việc ID nếu quá trình dừng lại. |
| succeeded | Recover/export nó đã được cứu, sau đó xác nhận lưu trữ. Đừng gửi một món đồ mới. |
| Không rõ kết quả / không xác nhận công việc ID | Giữ tốc độ, biên lai và sai sót. Kiểm tra History hoặc ứng cử viên IDs Trước khi quyết định nộp đơn. |

- [Yêu cầu lịch sử](https://flashdata.dev/app/jobs)
- [Phục hồi những sự phục tùng không chắc chắn](https://flashdata.dev/vi/docs/guides/agent-recovery/reference.md)

<a id="recover"></a>

## 4. Tìm lại hồ sơ giao hàng

Chạy từ thư mục trong thiết bị cuối mới. Phục hồi lại chờ công việc gốc và in một thư mục chứa delivery.json, run.json và biên lai. A 10- thời gian tạm dừng chờ đợi địa phương; lặp lại việc phục hồi để tiếp tục công việc.


<a id="recovery-script"></a>

### Tiếp tục công việc đã lưu

#### Python

Dùng lại pipeline.py đã lưu trong bước 2. Không cần thêm văn lệnh.

##### Phục hồi lại công việc hiện có, không có phục tùng mới

```bash
python pipeline.py recover
```


#### Bash

Tạo đầu tiên recover-media.sh bên cạnh item.json và dán vào mã dưới đây. Lưu tập tin, rồi chạy lệnh phục hồi bên dưới nó.

##### recover-media.sh

```bash
#!/usr/bin/env bash
set -euo pipefail
umask 077
cd -- "$(dirname -- "$0")"
. ./pipeline.env
: "${FLASHDATA_STATE_DIR:?Set your existing absolute CLI state directory}"
RUN_ID=$(jq -er '.runId' item.json)
mkdir -p attempts
DELIVERY_DIR=$(mktemp -d attempts/recover.XXXXXX)
if ! flashdata runs recover "$RUN_ID" --timeout 10m \
  --profile "${FLASHDATA_PROFILE:-default}" --state-dir "$FLASHDATA_STATE_DIR" \
  --output "$DELIVERY_DIR/delivery.json" --json --non-interactive \
  > "$DELIVERY_DIR/receipt.json" 2> "$DELIVERY_DIR/error.json"; then
  cat "$DELIVERY_DIR/error.json" >&2
  printf 'Keep %s; recover the same run after resolving the error.\n' "$DELIVERY_DIR" >&2
  exit 1
fi
flashdata runs show "$RUN_ID" --profile "${FLASHDATA_PROFILE:-default}" \
  --state-dir "$FLASHDATA_STATE_DIR" --json --non-interactive > "$DELIVERY_DIR/run.json"
jq -e '.source == "youtube_download" and .status == "done"' \
  "$DELIVERY_DIR/delivery.json" >/dev/null
printf '%s\n' "$DELIVERY_DIR"
```

##### Phục hồi lại công việc hiện có, không có phục tùng mới

```bash
set -euo pipefail
DELIVERY_DIR=$(bash recover-media.sh)
printf 'Delivery files: %s\n' "$DELIVERY_DIR"
```



<a id="delivery-record"></a>

### Kiểm tra đối tượng đã được chuyển tới

Mong đợi một S3 đối tượng URLkích cỡ tập tin dương và a MD5. Vật dụng cá nhân cần biết danh tính của anh. Python lưu thư mục thành công vào delivery-dir.txt cho kịch bản mới. Bash giữ DELIVERY_DIR; trong một thiết bị cuối mới, hãy đặt nó vào thư mục in.

#### Python

##### Hồ sơ giao hàng

```bash
python pipeline.py delivery
```


#### Bash

##### Hồ sơ giao hàng

```bash
jq '{status, file: .results[0], usage}' "$DELIVERY_DIR/delivery.json"
```



<a id="verify"></a>

## 5. Kiểm tra byte trước khi đánh dấu sẵn sàng

Các verifier kiểm tra các đầu vào ban đầu, S3 xô và tiền tố, luồng các đối tượng cá nhân vào đĩa, và so sánh byte của nó đếm và MD5. Chỉ các tập tin khớp sản xuất verified/ready.json. Python đọc delivery-dir.txt; Node sử dụng DELIVERY_DIR. Không gửi một yêu cầu FlashData.


<a id="verify-script"></a>

### Lưu văn lệnh xác thực

Bộ xem đồ thị KDE Amazon S3 đối tượng URLs. Đối với điểm kết thúc tự chọn hoặc một nhà cung cấp khác, sử dụng đối tượng xác thực của nó đọc và giữ cùng một đích, đích, đích danhte và kiểm tra checksum.

#### Python

Tạo verify-media.py bên cạnh pipeline.py và sao chép toàn bộ mã lệnh bên dưới vào nó. Lưu cả hai tập tin vào thư mục.

##### verify-media.py

```python
# 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)
```


#### Node.js

Tạo verify-media.mjs bên cạnh item.json và sao chép toàn bộ mã lệnh bên dưới vào nó.

##### verify-media.mjs

```javascript
import { readFile, mkdir, writeFile } from 'node:fs/promises';
import { createReadStream } from 'node:fs';
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import { resolve, join } from 'node:path';

try {
  const directory = process.argv[2];
  if (!directory) throw new Error('Pass the directory printed by the recovery step.');
  const readJson = async path => JSON.parse(await readFile(path, 'utf8'));
  const item = await readJson('item.json');
  const run = await readJson(join(directory, 'run.json'));
  const raw = await readFile(join(directory, 'delivery.json'));
  const delivery = JSON.parse(raw);
  if (!run.ok || run.data?.id !== item.runId || run.data?.status !== 'succeeded'
      || !run.data?.remoteId || delivery.source !== 'youtube_download'
      || delivery.status !== 'done' || delivery.results?.length !== 1) {
    throw new Error('Inspect the saved run and completed delivery before verifying.');
  }
  const file = delivery.results[0];
  const { bucket, region, prefix } = item.destination;
  const input = run.data.input;
  const storage = input?.params?.storage;
  if (input?.source !== 'youtube_download' || input.video_id !== item.request.video_id
      || ['download_type', 'video_quality', 'output_format'].some(
        key => input.params?.[key] !== item.request.params[key])
      || storage?.storage_url !== bucket || storage.region !== region
      || storage.object_prefix !== prefix) {
    throw new Error('item.json changed after submission. Inspect the original run.');
  }
  const url = new URL(file.file_url);
  const hosts = [bucket + '.s3.' + region + '.amazonaws.com', bucket + '.s3.amazonaws.com'];
  const objectKey = decodeURIComponent(url.pathname.slice(1));
  if (url.protocol !== 'https:' || !hosts.includes(url.host) || url.username
      || url.password || url.search || url.hash || !prefix
      || !objectKey.startsWith(prefix + '/')) {
    throw new Error('The delivery does not match the planned Amazon S3 destination.');
  }
  if (!Number.isSafeInteger(file.file_size) || file.file_size <= 0
      || !/^[a-f0-9]{32}$/i.test(file.md5 ?? '')) {
    throw new Error('A positive file_size and MD5 are required. Keep the manifest.');
  }
  const verification = join(directory, 'verified');
  await mkdir(verification, { mode: 0o700 }); // Existing attempt: stop without overwriting.
  const localFile = join(verification, 'media.mp4');
  let metadata;
  try {
    metadata = JSON.parse(execFileSync('aws', ['s3api', 'get-object',
      '--bucket', bucket, '--key', objectKey, '--region', region,
      '--output', 'json', '--no-cli-pager', '--no-cli-auto-prompt', localFile],
      { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }));
  } catch {
    throw new Error('S3 read failed. Keep this attempt and check the AWS read identity.');
  }
  let bytes = 0;
  const hash = createHash('md5');
  for await (const chunk of createReadStream(localFile)) {
    bytes += chunk.length;
    hash.update(chunk);
  }
  const md5 = hash.digest('hex');
  if (bytes !== file.file_size || md5 !== file.md5.toLowerCase()) {
    throw new Error('Byte count or MD5 mismatch. Keep the file; do not mark it ready.');
  }
  const ready = { runId: item.runId, jobId: run.data.remoteId,
    videoId: item.request.video_id, bucket, region, objectKey, storageVersionId: metadata.VersionId ?? null,
    bytes, md5, verifiedAt: new Date().toISOString(), localFile: resolve(localFile),
    deliverySha256: createHash('sha256').update(raw).digest('hex'), usage: delivery.usage };
  const readyFile = join(verification, 'ready.json');
  await writeFile(readyFile, JSON.stringify(ready, null, 2), { flag: 'wx', mode: 0o600 });
  console.log('Delivery verified:', readyFile);
} catch (error) {
  console.error(error instanceof Error ? error.message : 'Inspect the saved attempt.');
  process.exitCode = 1;
}
```


- [Boto3 GetObject](https://docs.aws.amazon.com/boto3/latest/reference/services/s3/client/get_object.html)
- [Lệnh bắt đầu](https://docs.aws.amazon.com/cli/latest/reference/s3api/get-object.html)

<a id="verify-file"></a>

### Chạy kiểm tra xem

Sau khi lưu tập lệnh, hãy chạy nó từ thư mục đó.

#### Python

##### Kiểm tra và đọc hồ sơ bỏ tay

```bash
python verify-media.py
```


#### Node.js + AWS CLI

##### Kiểm tra và đọc hồ sơ bỏ tay

```bash
set -euo pipefail
: "${DELIVERY_DIR:?Set the directory printed by recovery}"
node verify-media.mjs "$DELIVERY_DIR"
jq '{runId, jobId, bucket, region, objectKey, bytes, md5, storageVersionId}' \
  "$DELIVERY_DIR/verified/ready.json"
```



<a id="ready"></a>

### Đưa ready.json cho ứng dụng của bạn

Mong đợi giao hàng được xác nhận và một ghi chép chứa run/job IDs, xô, khu vực, khóa đối tượng, đã xác nhận kích cỡ và MD5. Đây là hồ sơ ứng dụng của bạn, do kịch bản tạo ra. Lưu trữ nó với delivery.json và vật gốc; nó tồn tại API Kết quả là cửa sổ được giữ kín.

Để chuyển đổi, chỉ mục hay xử lý khác, hãy thông qua việc kiểm tra localFile cho công nhân của anh. Để tải về, hãy tiếp tục với bước 6.

- [Kết quả lưu trữ và lưu trữ phương tiện](https://flashdata.dev/vi/docs/guides/save-results/reference.md#media)

<a id="serve"></a>

## 6. Cung cấp quyền truy cập điều khiển ứng dụng của bạn

Ở backend, hãy cho phép người dùng và tra xem hồ sơ sẵn sàng của người dùng đó trong cửa hàng của bạn. Sau đó tạo ra một cuộc sống ngắn ngủi. S3 tải về URL. Dùng đích đã lưu; không chấp nhận một xô hay phím đối tượng do trình duyệt cung cấp.


<a id="link-script"></a>

### Lưu văn lệnh tải về

SDK sử dụng backend của AWS đọc danh tính. Không có yêu cầu FlashData nào được gửi.

Hạt URL tên phiên bản đối tượng đã kiểm tra khi nào S3 phiên bản cung cấp một. Không có phiên bản ID, giữ mỗi phím xuất không thể thay đổi sau khi thẩm tra. Một danh tính đọc một phiên bản đặc biệt cần s3: getObjectVersion; đọc không được mã hóa cần thiết s3: getObjct.

#### Python

Tạo create-download-link.py bên cạnh pipeline.py và sao chép toàn bộ mã lệnh bên dưới vào nó. Nó sử dụng gói Boto3 được cài đặt vào lúc bắt đầu.

##### create-download-link.py

```python
# 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)
```


#### Node.js

Cài đặt các gói ký trong thư mục mục, rồi lưu nguồn bên dưới là create-download-link.mjs trong thư mục đó.

##### Cài đặt S3 Trình khách ký

```bash
test -f package.json || npm init -y
npm install @aws-sdk/client-s3 @aws-sdk/s3-request-presigner
```

##### create-download-link.mjs

```javascript
// create-download-link.mjs — run in your backend with its AWS read identity.
import { readFile } from 'node:fs/promises';
import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';

try {
  const path = process.argv[2];
  if (!path) throw new Error('Pass the verified ready.json file.');
  const ready = JSON.parse(await readFile(path, 'utf8'));
  if (['bucket', 'region', 'objectKey', 'verifiedAt'].some(
    key => typeof ready[key] !== 'string' || !ready[key])) {
    throw new Error('Use the ready.json produced by the verification step.');
  }
  // Load this record from your own store after authorizing the requesting user.
  const version = ready.storageVersionId;
  const command = new GetObjectCommand({
    Bucket: ready.bucket, Key: ready.objectKey,
    ...(version && version !== 'null' ? { VersionId: version } : {}),
  });
  const client = new S3Client({ region: ready.region });
  const url = await getSignedUrl(client, command, { expiresIn: 300 });
  console.log(JSON.stringify({ url, expiresInSeconds: 300 }, null, 2));
} catch (error) {
  console.error(error instanceof Error ? error.message : 'Could not create a download link.');
  process.exitCode = 1;
}
```


- [Boto3 sẵn ký URL ví dụ](https://docs.aws.amazon.com/boto3/latest/guide/s3-presigned-urls.html)
- [AWS JavaScript Trước ký URL ví dụ](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_s3_code_examples.html)
- [S3 truy cập và URL expiry](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html)

<a id="download-link"></a>

### Trả lại liên kết cho người dùng có thẩm quyền

Mong đợi một nơi kín đáo access.json có chứa rel và expiresInSeconds: 300. backend của bạn chỉ trở lại URL cho người dùng có thẩm quyền. Bất cứ ai đang cầm nó có thể tải tập tin lên đến năm phút; nó có thể hết hạn sớm hơn với giấy phép ký.

Tạo một liên kết mới từ hồ sơ đã sẵn sàng khi người dùng tiếp tục truy cập. Giữ phím đối tượng và phiên bản trong cơ sở dữ liệu của bạn, thay vì cất giữ các phím expiring URL như là địa chỉ tài sản. Ví dụ này dừng lại nếu access.json Đã tồn tại.

#### Python

##### Tạo liên kết 5 phút

```bash
python create-download-link.py
```


#### Node.js

##### Tạo liên kết 5 phút

```bash
(
set -euo pipefail
umask 077
: "${DELIVERY_DIR:?Set the directory printed by recovery}"
# Keep the signed link in a private file; do not log it or paste it into chat.
set -C
node create-download-link.mjs "$DELIVERY_DIR/verified/ready.json" \
  > "$DELIVERY_DIR/verified/access.json"
)
```



<a id="restart"></a>

## Khởi động lại từ giai đoạn được xác nhận cuối cùng

| Tình trạng | Hành động tiếp theo |
| --- | --- |
| Công việc / Chờ cục bộ quá giờ | Lặp lại runs recover với cùng một runId vào một thư mục mới. |
| S3 Truy cập bị từ chối hoặc bị ngắt quãng trong việc đọc | Sửa lại danh tính hay kết nối của AWS. Phục hồi vào một thư mục mới và kiểm tra lại; giữ tập tin bộ phận trước. |
| Số đếm byte / MD5 / đích không đúng | Dừng lại. Hãy so sánh bản kê khai, phiên bản vật thể và đích đến trước khi sử dụng phương tiện truyền thông. |
| Đã kiểm tra/ đã tồn tại | Hãy đọc ready.json của nó, hoặc kiểm tra sự xác thực không đầy đủ của nó. Văn lệnh sẽ không ghi đè lên nó. |
| Tải về ứng dụng URL hết hạn | Cho phép truy cập lại và ký tên đã lưu object/version. Không được tải xuống FlashData nữa. |
| run_id_input_conflict | Yêu cầu đã thay đổi. Phục hồi lại chạy gốc; sử dụng một điều mới runId Chỉ cho đầu ra có chủ đích mới. |
| 401 / 403 / 402 / 429 | Truy cập sửa chữa, cho phép hoặc số dư; theo Retry-After. Xem xét công việc đã lưu trước khi thử lại việc phục tùng. |


<a id="scale"></a>

## Áp dụng các giai đoạn giống nhau cho hàng đợi

1. Bắt đầu với một món đồ bay. Đọc các giới hạn hiện tại trước khi tăng sự đồng thuận của ứng dụng.
2. Giữ một cái bền runId cho mỗi video/output phiên bản, với một tiền tố đích rõ ràng. Lưu tài khoản, công việc ID và kết quả cuối cùng trong cơ sở dữ liệu ứng dụng của bạn.
3. Kiên trì CLI thư mục trong tiến trình khởi chạy lại. Các máy riêng rẽ cần sự phối hợp ứng dụng; một tạp chí chạy bộ không phân cách thư mục quốc gia độc lập.
4. Dùng ready.json như là bàn tay để xử lý xuôi dòng. Việc tái sử dụng các mặt hàng thất bại cá nhân đến nỗi việc giao hàng thành công được tái sử dụng.

- [Giới hạn tài khoản](https://flashdata.dev/vi/docs/guides/usage-and-limits/reference.md)
- [Máy phục vụ và chứng nhận hộp](https://flashdata.dev/vi/docs/guides/production-deployment/reference.md)
- [Đang đệ lại kế hoạch tác vụ](https://flashdata.dev/vi/docs/guides/recurring-tasks/reference.md)
