ข้ามไปยังเนื้อหา
TH
รับคีย์ API
เรียกดูเอกสาร

ตัวอย่าง

ดาวน์โหลดวิดีโอไปยังที่เก็บข้อมูลของคุณ

ส่ง MP4 หนึ่งไฟล์ไปยัง bucket Amazon S3 ของคุณ แล้วดึงและตรวจสอบไฟล์ด้วย Python หรือ Bash

ในหน้านี้

ก่อนจะเริ่ม

ใช้สิทธิ์ของเจ้าของแบบ youtube_download และการใช้เครดิตที่มีอยู่ ดาวน์โหลดไม่ได้รวมไว้ในการเข้าถึงการทดลองของสายลับชั่วคราว คุณจําเป็นต้องมีอยู่แล้ว Amazon S3 ถังและวิดีโอที่คุณได้รับอนุญาตให้ดาวน์โหลด

เลือก Python 3.10+ ด้วยคําร้อง และ โบโต้3 หรือ Bash ด้วย cURL, jqแบบ OpenSSL และ AWS CLI v2 เปิด Windowsใช้ Git Bash สําหรับ Bash เวอร์ชั่น

แปรงทาสีใช้สําหรับ
FLASHDATA_API_KEYส่งงานแล้วเอาสถานะและบันทึกการส่งมอบ
FLASHDATA_STORAGE_ACCESS_KEY / FLASHDATA_STORAGE_SECRET_KEYขนาด S3 กําลังอัปโหลดการแสดงตัวไปยัง FlashData ที่เขียนถึงถังที่คัดเลือกแล้ว และคํานําหน้าของคุณ
โพรไฟล์หรือบทบาทของ AWS ภายในเครื่องของคุณอ่านวัตถุส่วนตัวด้วย BOTO3 หรือ AWS CLI ในขั้นตอน 4. มันต้องการ s3: GetObject เข้าถึง

1. เลือกวิดีโอและปลายทาง

สร้างโฟลเดอร์สําหรับดาวน์โหลดข้อมูลส่วนตัวที่อยู่นอกคลังแพกเกจของคุณ บันทึก request.json มีและเปิดเทอร์มินัลในโฟลเดอร์ที่ แทนที่ storage_url ด้วยชื่อถังและเขตของคุณกับพื้นที่ AWS ของมัน; ใช้ 11- วิดีโอคาหนังคาทอลิก ID.

สูตรนี้จะส่งวิดีโอด้วยเสียงเป็น MP4, ที่ถึง 720p, ภายใต้ recipes/clip-001/. เก็บถังไว้เป็นส่วนตัว ใช้คํานําหน้าใหม่สําหรับการดาวน์โหลดแยก เพื่อให้งานอื่นไม่สามารถเขียนทับพาธของออบเจกต์นี้ได้

download-video/request.json
{
  "source": "youtube_download",
  "video_id": "jNQXAC9IVRw",
  "params": {
    "download_type": "audio_video",
    "video_quality": "<=720",
    "output_format": "mp4",
    "storage": {
      "storage_type": "s3",
      "storage_url": "your-media-bucket",
      "region": "us-east-1",
      "object_prefix": "recipes/clip-001"
    }
  }
}

2. ส่งงานดาวน์โหลดหนึ่งงาน

เลือกหนึ่งรุ่นและบันทึกสคริปต์ไว้ด้านข้าง request.json ก่อนที่จะดําเนินการมัน บทนี้อ่านตัวแปร 3 สภาวะแวดล้อมด้านบน หรือร้องขอพวกเขาที่สัญญาณที่ซ่อนอยู่ เจ้าหน้าที่ควรจะจัดหาพวกเขา จากร้านลับของพวกเขา อย่าใส่คีย์ใน request.json

โฟลเดอร์ใหม่- 001 ที่ส่งการร้องขอแบบ Aync มันบันทึกการร้องขอโดยไม่ต้องอัปโหลดเอกสารกํากับเวลา HTTP การตอบรับและงาน ID. การใช้โฟลเดอร์นี้ หยุดการส่งข้อมูล มันไม่ได้สร้างงานที่สอง

ติดตั้งในของคุณ Python สภาพแวดล้อมName
python -m pip install requests boto3
download-video/submit.py
# Save as download-video/submit.py.
import getpass
import json
import os
import re
import sys
from datetime import datetime, timezone
from pathlib import Path

import requests

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


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


def secret(name):
    value = os.environ.get(name) or getpass.getpass(name + ": ")
    if not value.strip():
        raise ValueError("Missing " + name)
    return value


def main():
    os.umask(0o077)
    folder = sys.argv[1]
    if not re.fullmatch(r"[A-Za-z0-9_-]+", folder):
        raise ValueError("Use a simple output folder name, such as job-001.")
    directory = ROOT / folder
    if directory.exists():
        raise ValueError("Keep this attempt. Run collect.py with the same folder.")
    request = read_json(ROOT / "request.json")
    storage = request["params"]["storage"]
    if (request["source"] != "youtube_download"
            or not re.fullmatch(r"[A-Za-z0-9_-]{11}", request["video_id"])
            or request["params"]["download_type"] != "audio_video"
            or request["params"]["output_format"] != "mp4"
            or storage["storage_type"] != "s3"
            or set(storage) != {"storage_type", "storage_url", "region", "object_prefix"}
            or not re.fullmatch(r"[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]", storage["storage_url"])
            or not re.fullmatch(r"[a-z0-9-]+", storage["region"])
            or not re.fullmatch(r"[A-Za-z0-9_-]+(/[A-Za-z0-9_-]+)*", storage["object_prefix"])):
        raise ValueError("Check the video, MP4 options and Amazon S3 destination.")
    key = secret("FLASHDATA_API_KEY")
    access = secret("FLASHDATA_STORAGE_ACCESS_KEY")
    secret_key = secret("FLASHDATA_STORAGE_SECRET_KEY")
    directory.mkdir(mode=0o700)
    # Save the plan BEFORE sending. Keep upload credentials out of this file.
    (directory / "request.json").write_text(json.dumps(request, indent=2), encoding="utf-8")
    (directory / "submitted-at.txt").write_text(
        datetime.now(timezone.utc).isoformat(), encoding="utf-8")
    storage.update(access_key=access, secret_key=secret_key)
    response = requests.post(
        "https://data.flashdata.dev/v1/queries", json=request,
        headers={"X-API-Key": key, "Accept": "application/json"},
        timeout=(10, 120), allow_redirects=False)
    (directory / "submission.json").write_bytes(response.content)
    (directory / "submission-headers.txt").write_text(
        "\n".join(f"{k}: {v}" for k, v in response.headers.items()), encoding="utf-8")
    (directory / "submission-http.txt").write_text(str(response.status_code))
    if response.status_code not in (200, 201, 202):
        raise ValueError(f"HTTP {response.status_code}. Inspect the saved attempt.")
    receipt = response.json()
    if (receipt.get("source") != "youtube_download"
            or not re.fullmatch(r"[A-Za-z0-9_-]+", receipt.get("id", ""))):
        raise ValueError("Missing job ID. Check History before submitting again.")
    print("Submitted:", receipt["id"], "— keep", directory)


if __name__ == "__main__":
    try:
        main()
    except (IndexError, KeyError, OSError, ValueError, requests.RequestException) as error:
        print("Network request failed. Keep this attempt and inspect its saved files."
              if isinstance(error, requests.RequestException) else str(error), file=sys.stderr)
        sys.exit(1)
ประมวลผลจากดาวน์โหลดวีดิโอ/
python submit.py job-001

ใบเสร็จที่คาดหวัง

ลายนิ้วมือที่ประสบความสําเร็จ มอบหมาย: งาน _... และบันทึก submission.json ใบ เสร็จ นั้น ยืน ยัน ว่า งาน ได้ รับ การ ยอม รับ; นั่น ไม่ ใช่ เงิน ที่ ส่ง เสร็จ หรือ ข้อ เรียก ร้อง สุด ท้าย.

job-001/submission.json ย่อคํา
{
  "id": "job_example",
  "source": "youtube_download",
  "status": "pending",
  "usage": {
    "credits": 0
  }
}

3. รอคอยการส่งมอบและบันทึก

บันทึก collect.py ข้าง submit.pyหรือ collect.sh ข้าง submit.sh. ประมวลผลด้วยโฟลเดอร์เดียวกันกับงาน - 001 มันตรวจสอบงานที่บันทึกไว้ครั้งเดียว เพื่อรอการประมวลผล โปรดรอสักครู่ 10 วินาทีและเรียกใช้คําสั่งเดียวกันอีกครั้ง

เมื่อเสร็จสมบูรณ์แล้ว มันจะบันทึก delivery.json ลายเซ็นเปลี่ยนเส้นทางที่นี่เอา JSON บันทึกการส่งมอบ, ไม่ใช่ MP4; สคริปต์ต่อไปนี้โดยไม่ส่งต่อ FlashData กุญแจ บันทึก delivery.json ถูกสร้างขึ้นใหม่โดยไม่มีคนอื่น API ขอล่ะ

download-video/collect.py
# Save as download-video/collect.py, beside submit.py.
import os
import re
import sys
from urllib.parse import urlsplit

import requests
from submit import ROOT, read_json, secret


def main():
    os.umask(0o077)
    folder = sys.argv[1]
    if not re.fullmatch(r"[A-Za-z0-9_-]+", folder):
        raise ValueError("Use the saved output folder name.")
    directory = ROOT / folder
    if (directory / "delivery.json").exists():
        print("Already saved:", directory / "delivery.json")
        return
    receipt = read_json(directory / "submission.json")
    job_id = receipt["id"]
    if receipt["source"] != "youtube_download" or not re.fullmatch(r"[A-Za-z0-9_-]+", job_id):
        raise ValueError("Inspect submission.json before continuing.")
    headers = {"X-API-Key": secret("FLASHDATA_API_KEY"), "Accept": "application/json"}
    url = "https://api.flashdata.dev/v2/jobs/" + job_id

    def get(url, name, headers):
        response = requests.get(url, headers=headers, timeout=(10, 120), allow_redirects=False)
        (directory / name).write_bytes(response.content)
        (directory / (name + ".headers")).write_text(
            "\n".join(f"{k}: {v}" for k, v in response.headers.items()), encoding="utf-8")
        (directory / (name + ".http")).write_text(str(response.status_code))
        return response

    status = get(url, "job-status.json", headers)
    if status.status_code != 200:
        raise ValueError(f"HTTP {status.status_code}. Inspect job-status.json and its headers.")
    job = status.json()["job"]
    if job["id"] != job_id or job["source"] != "youtube_download":
        raise ValueError("The job does not match the saved receipt.")
    if job["status"] in ("pending", "processing"):
        print(job["status"] + ". Wait 10 seconds, then run this command again.")
        return
    if job["status"] != "completed":
        raise ValueError("Job " + job["status"] + ". Inspect job-status.json; do not resubmit.")
    result = get(url + "/results", "delivery.pending.json", headers)
    if result.status_code == 302:
        location = result.headers.get("Location", "")
        parsed = urlsplit(location)
        if parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password:
            raise ValueError("Expected an HTTPS result URL.")
        # This URL retrieves the JSON delivery record, not the video.
        # Never forward the FlashData key to the signed storage URL.
        result = get(location, "delivery.pending.json", {})
    if result.status_code != 200:
        raise ValueError(f"HTTP {result.status_code}. Run collect.py again after resolving it.")
    delivery = result.json()
    if (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 delivery.pending.json before using the result.")
    (directory / "delivery.pending.json").replace(directory / "delivery.json")
    print("Saved:", directory / "delivery.json")
    print("Usage:", delivery.get("usage"))


if __name__ == "__main__":
    try:
        main()
    except (IndexError, KeyError, OSError, ValueError, requests.RequestException) as error:
        print("Network request failed. Keep this attempt and inspect its saved files."
              if isinstance(error, requests.RequestException) else str(error), file=sys.stderr)
        sys.exit(1)
ตรวจสอบงานที่บันทึกไว้
python collect.py job-001

อะไร delivery.json มี

ผล ที่ ตาม มา คือ file_url, file_size 2561. สืบค้นเมื่อ 24 พฤษภาคม พ.ศ. เก็บบันทึกทั้งหมดไว้ แฟ้ม URL ชื่อของคุณ S3 วัตถุ; มันไม่ได้ทําให้ถังส่วนตัว อ่านได้ในที่สาธารณะ

job-001/delivery.json สาขาวิชาชีพ
{
  "source": "youtube_download",
  "status": "done",
  "results": [
    {
      "file_url": "https://your-media-bucket.s3.us-east-1.amazonaws.com/recipes/clip-001/jNQXAC9IVRw.mp4",
      "file_size": 1048576,
      "md5": "0123456789abcdef0123456789abcdef"
    }
  ]
}

4. อ่านของส่วนตัวและตรวจสอบ

บันทึกสคริปต์สําหรับตรวจสอบภาพไว้ด้านข้างของสคริปต์อื่น ๆ ใช้การแสดงตัวของ AWS ที่ปรับแต่งเอง โดยสิทธิ์ในการอ่านไปยังออบเจกต์ สคริปต์ตรวจสอบว่าการส่งมอบเป็นของวางแผน S3 ถัง, นําหน้า และชื่อแฟ้มวิดีโอ แล้วดาวน์โหลดไป media.mp4.part.

ตรงกับจํานวนที่นับได้เท่านั้น MD5 ผลิต media.mp4 ถึง verified.json. กําลังทําการตรวจสอบอีกครั้ง ตรวจสอบว่ามีอยู่ก่อนแล้ว media.mp4 ในท้องที่ ขั้นตอนนี้อ่านของคุณ S3 วัตถุ; มันไม่ส่งตัวอื่น FlashData ดาวน์โหลดแล้ว

download-video/verify.py
# Save as download-video/verify.py, beside submit.py.
import hashlib
import json
import os
import re
import sys
from contextlib import closing
from datetime import datetime, timezone
from urllib.parse import urlsplit

import boto3
from submit import ROOT, read_json


def main():
    os.umask(0o077)
    folder = sys.argv[1]
    if not re.fullmatch(r"[A-Za-z0-9_-]+", folder):
        raise ValueError("Use the saved output folder name.")
    directory = ROOT / folder
    request = read_json(directory / "request.json")
    receipt = read_json(directory / "submission.json")
    job = read_json(directory / "job-status.json")["job"]
    delivery = read_json(directory / "delivery.json")
    if (request["source"] != "youtube_download" or receipt["source"] != "youtube_download"
            or job["id"] != receipt["id"] or job["source"] != "youtube_download"
            or job["status"] != "completed" or delivery.get("source") != "youtube_download"
            or delivery.get("status") != "done" or len(delivery["results"]) != 1):
        raise ValueError("Check the saved request, receipt, status and delivery.")
    storage = request["params"]["storage"]
    bucket, region, prefix = (storage[k] for k in ("storage_url", "region", "object_prefix"))
    file = delivery["results"][0]
    parsed = urlsplit(file["file_url"])
    # This recipe uses an ASCII prefix and the MP4 filename generated for the video.
    object_key = prefix + "/" + request["video_id"] + ".mp4"
    if (storage["storage_type"] != "s3" or parsed.scheme != "https"
            or parsed.netloc != bucket + ".s3." + region + ".amazonaws.com"
            or parsed.path != "/" + object_key or parsed.query or parsed.fragment
            or 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("Delivery URL, byte count or MD5 does not match this recipe's request.")
    local = directory / "media.mp4"
    pending = directory / "media.mp4.part"
    if not local.exists():
        # Boto3 uses your local AWS read identity, not the upload key sent to FlashData.
        with pending.open("xb") as output:
            s3 = boto3.client("s3", region_name=region)
            with closing(s3.get_object(Bucket=bucket, Key=object_key)["Body"]) as stream:
                while chunk := stream.read(1024 * 1024):
                    output.write(chunk)
        local = pending
    size, digest = 0, hashlib.md5(usedforsecurity=False)
    with local.open("rb") as stream:
        while chunk := stream.read(1024 * 1024):
            size += len(chunk)
            digest.update(chunk)
    if size != file["file_size"] or digest.hexdigest() != file["md5"].lower():
        raise ValueError("Size or MD5 mismatch. Keep the local file for inspection.")
    final = directory / "media.mp4"
    if local == pending:
        pending.rename(final)
    record = {
        "job_id": receipt["id"], "video_id": request["video_id"],
        "bucket": bucket, "object_key": object_key, "bytes": size, "md5": digest.hexdigest(),
        "verified_at": datetime.now(timezone.utc).isoformat(), "usage": delivery.get("usage"),
    }
    (directory / "verified.json").write_text(json.dumps(record, indent=2), encoding="utf-8")
    print("Verified:", final, "—", size, "bytes; MD5 matches.")


if __name__ == "__main__":
    try:
        main()
    except Exception as error:
        print(str(error), file=sys.stderr)
        sys.exit(1)
ตรวจสอบการส่งมอบที่บันทึกไว้
python verify.py job-001

ผลสําเร็จ

การนับทีละน้อยข้างต้น คือ การเปรียบเทียบ ตอนนี้คุณมี MP4 ในถังของคุณ, การตรวจสอบสําเนาท้องถิ่นและ verified.json การผูกแฟ้มกับงานของมัน IDวีดีโอ IDกุญแจออบเจ็กต์, checksum และรายงานการใช้งาน

เทอร์มินัล
Verified: .../job-001/media.mp4 — 1048576 bytes; MD5 matches.

ทําต่อโดยไม่ดาวน์โหลดครั้งที่สอง

เกิดอะไรขึ้นการกระทําถัดไป
เวลาทํางานอัตโนมัติ หรือไม่มีงาน ID รอดแล้วทํางานต่อไป001 และตรวจสอบ History โดยใช้เวลาและวิดีโอของมัน ไม่ต้องลบโฟลเดอร์เพื่อบังคับให้มีการส่งข้อมูลต่อไป กลับ มา ทํา งาน เดิม อีก ก่อน ตัดสิน ใจ ว่า จําเป็น ต้อง มี คํา ขอ ใหม่ หรือ ไม่.
การประมวลผล/ การประมวลผลเดี๋ยวก่อน 10 ไม่กี่วินาทีก็กลับมาทวงคืนงาน001. มันอ่านเฉพาะงานที่มีอยู่
งานล้มเหลวInspect job-status.json สําหรับข้อผิดพลาด แก้ไขการปรับแต่งวิดีโอหรือจัดเก็บลงแฟ้ม ก่อนที่จะทําการเริ่มงานใหม่โดยตรงในโฟลเดอร์ใหม่และส่วนนําหน้า
401 / 403 / 402 / 429ตรวจสอบกุญแจ อนุมัติหรือความสมดุล สําหรับ 429อ่าน Retry-After ในหัวจดหมายที่ถูกพิทักษ์รักษาไว้ ไม่ให้ทําการส่งสคริปต์ใหม่อีกครั้งโดยอัตโนมัติ
การดึงข้อมูลผลลัพธ์ล้มเหลวหรือการเซ็น URL หมดอายุเรียกเก็บงาน- 001 เพื่อร้องขอผลลัพธ์ที่มีอยู่อีกครั้ง
S3 AccessDeniedแก้ไขข้อกําหนดการอ่านการแสดงตัวหรือตะกร้าภายในเครื่อง FlashData. เข้าถึงการอัปโหลดและอ่านภายในเครื่องแยกต่างหาก.
ส่วนประกอบแฟ้ม, พาธไม่ถูกต้อง, จํานวนนับแบบไบต์ หรือ MD5เก็บการส่งมอบและไฟล์สําหรับการตรวจสอบ เพื่อความสดชื่น S3 อ่านหลังจากแก้ไขสาเหตุแล้ว ย้าย media.mp4.part แล้วนอกจากนั้น พวกเขาจะได้ทดสอบอีก อย่ากลับไปรับอีก