From c17f2f3773081f2998146293d78c8eec8d45447b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=AA=E5=BF=97=E9=B9=8F?= Date: Tue, 1 Dec 2026 23:58:00 +0000 Subject: [PATCH 1/2] [feat] assets: import a video from a web page link MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary - Stage the video on a supported web page as an upload (PUT uploads/{handle}/url) and register it with the existing asset.import command, so the edit lease is only needed for the short staging write. The handle records its link: the same link answers without downloading again and another link is rejected (409). The route ends the download when the client disconnects. - Download in a separate worker process with yt-dlp site extractors only, selecting formats yt-dlp fetches directly over HTTP(S). Inside the worker yt-dlp may start only ffmpeg/ffprobe on local files and deno; external downloaders, PhantomJS and section downloads are refused, so every network request is yt-dlp's own. It connects directly, without the system proxy, and its resolver refuses any answer that the shared public-address check rejects, so redirects, media servers and host-agnostic extractors cannot reach loopback, private, reserved or multicast addresses. Cancellation, the timeout and the end of the calling process (the worker exits when its stdin closes) end the worker's whole process tree. The worker starts with -X utf8 -P and answers in ASCII JSON, so non-ASCII titles and paths survive a non-UTF-8 Windows code page. Playlists, live streams and sources over 15 minutes or 512 MB are refused; an unknown size is counted while downloading. Browser-playable codecs (H.264, VP9, AV1) are preferred up to 1080p. - CLI: asset import-url downloads on the CLI machine and registers through the asset import path; in an Agent turn the file stays in the execution directory and is published with artifact.publish. Repeating an --operation-id with the same link replays its receipt before any download; another link under the same ID is rejected. - A bundled Agent skill points link requests to asset import-url, so the Agent no longer resolves and curls a site's original file, and treats a refusal as final instead of fetching the link another way. - Canvas: "Import video from link" in the canvas New node menu opens a dialog whose Cancel ends the download, and places the imported video as a node. - Keep the url_import_* messages in one bilingual table in the domain (domain/url_import.py), used by the HTTP layer and the CLI, so CLI and Agent errors follow OPENDIRECTOR_LANGUAGE like HTTP errors follow Accept-Language. - Add yt-dlp as a dependency and document the feature in the user and CLI guides. Signed-off-by: 汪志鹏 Co-Authored-By: Claude Opus 5.5 --- apps/api/src/opendirector_api/creation.py | 13 +- apps/api/src/opendirector_api/localization.py | 3 +- apps/api/src/opendirector_api/models.py | 4 + docs/guides/cli.md | 11 + docs/guides/user-guide.md | 9 + docs/guides/user-guide.zh-CN.md | 9 + .../agent/skills/video-link-import/SKILL.md | 42 ++ .../application/creation_assets.py | 30 + packages/core/src/opendirector/cli.py | 83 ++- .../src/opendirector/domain/url_import.py | 50 ++ .../infrastructure/creation_uploads.py | 14 +- .../integrations/http_settings.py | 11 +- .../src/opendirector/media/download_worker.py | 167 +++++ .../core/src/opendirector/media/downloads.py | 119 ++++ pyproject.toml | 2 +- requirements.txt | 2 + src/backend/creationClient.ts | 15 + src/canvas/CanvasCreationMenu.tsx | 11 + src/canvas/VideoLinkDialog.tsx | 97 +++ src/canvas/workspace/WorkspaceView.tsx | 10 + src/canvas/workspace/useWorkspaceTransfer.ts | 20 + src/i18n/messages/en-US/canvas.ts | 8 + src/i18n/messages/zh-CN/canvas.ts | 8 + tests/creationClient.test.ts | 43 ++ tests/test_video_link_import.py | 599 ++++++++++++++++++ 25 files changed, 1360 insertions(+), 20 deletions(-) create mode 100644 packages/agent/skills/video-link-import/SKILL.md create mode 100644 packages/core/src/opendirector/domain/url_import.py create mode 100644 packages/core/src/opendirector/media/download_worker.py create mode 100644 packages/core/src/opendirector/media/downloads.py create mode 100644 src/canvas/VideoLinkDialog.tsx create mode 100644 tests/test_video_link_import.py diff --git a/apps/api/src/opendirector_api/creation.py b/apps/api/src/opendirector_api/creation.py index 2cfca2c8d..fdbddfea7 100644 --- a/apps/api/src/opendirector_api/creation.py +++ b/apps/api/src/opendirector_api/creation.py @@ -5,6 +5,7 @@ from hashlib import sha256 from io import BytesIO import asyncio +import threading from fastapi.encoders import jsonable_encoder from fastapi.responses import JSONResponse import json @@ -33,7 +34,7 @@ from opendirector.domain.timeline_errors import timeline_error, timeline_error_message from opendirector.infrastructure.creation_projects import CreationProjects from opendirector.media.fonts import MAX_FONT_BYTES, inspect_font -from opendirector_api.models import AssetSource, Session +from opendirector_api.models import AssetSource, Session, UrlSource from opendirector_api.localization import localized_receipt from opendirector_api.localization import localized_error_for_language @@ -422,6 +423,16 @@ def copy_upload(project_id: UUID, handle_id: UUID, source: AssetSource, x_opendi return assets.stage_copy(project_id, handle_id, str(x_opendirector_session), source.projectId, source.assetId, source.fingerprint) + @router.put('/projects/{project_id}/uploads/{handle_id}/url', response_model=UploadInfo) + async def url_upload(project_id: UUID, handle_id: UUID, source: UrlSource, request: Request, + x_opendirector_session: UUID = Header()): + stop = threading.Event() + try: + return await preview_until_disconnect(request, run_in_threadpool( + assets.stage_url, project_id, handle_id, str(x_opendirector_session), source.url, cancelled=stop.is_set)) + finally: + stop.set() + @router.get('/projects/{project_id}/uploads/{handle_id}', response_model=UploadInfo) def upload_info(project_id: UUID, handle_id: UUID, x_opendirector_session: UUID = Header()): return assets.uploads.info(project_id, handle_id, str(x_opendirector_session)) diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index fd3d72d25..a04a1f532 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -10,6 +10,7 @@ from opendirector.domain.timeline_errors import timeline_error_message +from opendirector.domain.url_import import url_import_message from opendirector.domain.creation.commands import CommandReceipt from opendirector.domain.capabilities import Capability @@ -195,7 +196,7 @@ def localized_error_for_language( code: str = "operation_rejected", required_capability: Capability | None = None, ) -> str: - specific = timeline_error_message(code, language) + specific = timeline_error_message(code, language) or url_import_message(code, language, chinese) if specific is not None: return specific if not wants_english_language(language): diff --git a/apps/api/src/opendirector_api/models.py b/apps/api/src/opendirector_api/models.py index 75e65dfe7..a095e33f5 100644 --- a/apps/api/src/opendirector_api/models.py +++ b/apps/api/src/opendirector_api/models.py @@ -23,6 +23,10 @@ class AssetSource(Model): fingerprint: str | None = Field(default=None, max_length=128, description='Expected source content; a different one is refused.') +class UrlSource(Model): + url: str = Field(min_length=1, max_length=2048) + + class ModelConnection(Model): connectionType: Literal['api', 'self_hosted'] = 'api' protocol: Literal['openai', 'volcengine', 'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'vllm_omni_segmentation', 'vllm_omni_music', 'vllm_omni_depth', 'vllm_omni_score'] | None = None diff --git a/docs/guides/cli.md b/docs/guides/cli.md index ff46af94c..dda824b3c 100644 --- a/docs/guides/cli.md +++ b/docs/guides/cli.md @@ -128,6 +128,17 @@ An unsuccessful Agent export to its macOS/Linux execution directory can leave an In an Agent execution context, files must remain inside the authorized execution directory and commands remain scoped to that context. `timeline default-font` returns a read-only installation path; copy that font into the authorized execution directory before using `asset import`. The installation path does not bypass that boundary. Package commands do not require an open editor. MP4 rendering requires the browser. Editable JSON describes same-project structure; FCPXML and legacy XML media bundles refuse text overlays. +## 从链接导入视频 / Import a video from a link + +```bash +opendirector --project PROJECT_UUID asset import-url "https://commons.wikimedia.org/wiki/File:EXAMPLE.webm" +opendirector --project PROJECT_UUID canvas add-material --asset ASSET_UUID --x 0 --y 0 +``` + +`asset import-url` 只启用 yt-dlp 的站点解析器(不启用通用解析器),只选择可直接通过 HTTP(S) 下载的文件格式(只以 HLS/DASH 分片流或片段形式提供的视频返回 `url_import_unsupported`);下载进程中 yt-dlp 只能启动处理本地文件的 ffmpeg/ffprobe 和无网络权限的 deno,外部下载器、PhantomJS 等其他程序一律拒绝,因此所有网络请求都经过下方的地址检查,拒绝播放列表和直播,视频最长 15 分钟、512 MB(大小未知时在下载过程中累计,超出即停止)。下载在独立进程中直连完成,不使用系统代理;该进程的每次域名解析(包括跳转和媒体服务器)只要得到本机、局域网、链路本地、保留(含 NAT64)或组播等非公网地址就拒绝连接,返回 `url_import_private`;取消、超时或调用方进程退出(包括 Agent 轮次被停止)都会结束下载进程及其启动的子进程;在 Windows 上,调用方被强行结束时下载进程会退出,但它启动的 ffmpeg 等子进程可能自行运行到结束。下载在 CLI 所在机器完成,再走与 `asset import` 相同的登记路径,因此编辑租约只用于最后的登记,长时间下载不会占用编辑权。回执包含 `assetId` 和来源页面 `source`(链接、标题、站点、时长)。Agent 执行时文件保存在执行目录的 `downloads/` 下并在回执 `file` 中给出;其他情况使用临时目录,可用 `--output-dir` 保留。重复使用同一 `--operation-id` 和同一链接时,先查原回执并直接返回(`replayed: true`),不再下载;同一 `--operation-id` 换用其他链接返回 `url_import_operation_conflict`。Agent 执行时复用执行目录中已下载的文件。可用站点取决于 yt-dlp 的站点解析器:部分网站会拦截服务器或机房 IP,YouTube 等站点还可能需要 yt-dlp 的 JavaScript 运行时组件(本功能不安装),此时返回 `url_import_failed` 及原因,请改为下载后用 `asset import` 登记。画布中的「从链接导入视频」由服务端下载到上传暂存区(同一句柄只对应一个链接,换链接返回 `url_import_handle_conflict`),再执行同一 `asset.import`;关闭对话框或断开连接会结束下载进程,不登记素材。 + +`asset import-url` enables only yt-dlp's site extractors (not the generic extractor), selects only formats downloaded directly over HTTP(S) (videos offered only as HLS/DASH segment streams or as sections return `url_import_unsupported`); inside the download process yt-dlp may start only ffmpeg/ffprobe on local files and deno without network permission, while external downloaders, PhantomJS and other programs are refused, so every network request passes the address check below, refuses playlists and live streams, and limits videos to 15 minutes and 512 MB; when the size is unknown it is counted during the download, which stops once the limit is exceeded. The download runs in a separate process that connects directly, without the system proxy. Every name that process resolves, including redirects and media servers, must resolve only to public addresses; loopback, private, link-local, reserved (including NAT64), multicast and other non-public answers refuse the connection with `url_import_private`. Cancellation, the timeout or the end of the calling process (including a stopped Agent turn) ends the download process and anything it started; on Windows, when the caller itself is killed, the download process exits but an ffmpeg it started may run to completion. The CLI downloads on its own machine and then registers through the same path as `asset import`, so the edit lease is held only for registration, not for the download. The receipt includes `assetId` and the source page (`url`, `title`, `site`, `durationSeconds`). In an Agent turn the file is kept under `downloads/` in the execution directory and reported as `file`; otherwise a temporary directory is used unless `--output-dir` is given. Repeating the same `--operation-id` with the same link returns the original receipt (`replayed: true`) without downloading again; the same `--operation-id` with a different link returns `url_import_operation_conflict`. In an Agent turn the downloaded file in the execution directory is reused. Which sites work depends on yt-dlp's site extractors: some sites block server and data-centre addresses, and sites such as YouTube can additionally need yt-dlp's JavaScript runtime components, which this feature does not install. Such failures return `url_import_failed` with the reason; download the file manually and register it with `asset import`. The canvas **Import video from link** action downloads on the server into an upload handle (one link per handle; another link returns `url_import_handle_conflict`) and then runs the same `asset.import`. Closing the dialog or disconnecting ends the download process and registers nothing. + ## Voice library `opendirector voice list --model MODEL_CONFIG_UUID` reads the full library and returns the selected model's connection identity, voices and adapter requirements. For a large MOSS library, request up to 150 voices per page. diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md index f82ab04cb..7da2bc554 100644 --- a/docs/guides/user-guide.md +++ b/docs/guides/user-guide.md @@ -219,6 +219,15 @@ Select a node, then choose an action from its toolbar. For a local edit, mark an area or create a selection first, then enter your instructions and confirm the action. If a required model capability is missing, follow the tool's instructions to configure it. Hover over a disabled control for an explanation. +### Import a video from a link + +Right-click the canvas, choose **New node → Import video from link**, and paste the page of a single video. OpenDirector downloads it on the computer that runs the app, registers it as a video asset and adds it as a video node, ready for references, trimming or other video tools. + +- One video page on a supported site, up to 15 minutes and 512 MB. Playlists, live streams and videos offered only as segmented streams (HLS/DASH) are not supported. Every connection the download makes, including redirects and media servers, must go to a public internet address; this computer and the local network are refused. Link import connects directly, without the system proxy. +- Cancel stops the download and registers nothing; if registration had already finished, the video is still added. +- Which sites work depends on the yt-dlp downloader. Some sites block downloads from servers or data centres, and some (such as YouTube) may need extra yt-dlp components. If the import fails, download the file yourself and use **Upload**. +- Import only videos you have the right to use. The asset is named after the page title; the link itself is not stored in the project. + ## Arrange and export videos 1. Create a timeline node and open its editor. diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md index 8c595c6b4..6372ffd9e 100644 --- a/docs/guides/user-guide.zh-CN.md +++ b/docs/guides/user-guide.zh-CN.md @@ -219,6 +219,15 @@ Codex 网页检索引用在具有匹配来源时显示为编号链接;复制 需要局部修改时先标记区域或创建选区,再填写要求并确认执行。缺少所需模型能力时,按工具提示补充配置;灰色入口以悬停提示为准。 +### 从链接导入视频 + +右键画布,选择 **新建节点 → 从链接导入视频**,粘贴单个视频的网页链接。OpenDirector 在运行应用的电脑上下载视频,登记为视频素材并添加为视频节点,之后可作参考、修剪或使用其他视频工具。 + +- 支持常见视频网站的单个视频页面,最长 15 分钟、512 MB。不支持播放列表、直播以及只以分片流(HLS/DASH)提供的视频。下载过程中的每个连接(包括跳转和媒体服务器)都必须指向公网地址,本机或局域网地址会被拒绝;链接导入直接连接,不使用系统代理。 +- 点击「取消」会停止下载,不登记素材;如果取消时素材已经登记完成,视频仍会添加到画布上。 +- 可用站点取决于 yt-dlp 下载组件:部分网站会拦截服务器或机房的下载,部分网站(如 YouTube)可能需要额外的 yt-dlp 组件。导入失败时,可自行下载后使用 **上传**。 +- 请只导入你有权使用的视频。素材以网页标题命名,工程中不保存链接本身。 + ## 编排和导出视频 1. 创建时间线节点并打开编辑器。 diff --git a/packages/agent/skills/video-link-import/SKILL.md b/packages/agent/skills/video-link-import/SKILL.md new file mode 100644 index 000000000..f2968af2d --- /dev/null +++ b/packages/agent/skills/video-link-import/SKILL.md @@ -0,0 +1,42 @@ +--- +name: video-link-import +description: 从视频网页链接(yt-dlp 支持的站点上的单个视频页面)导入视频到工程和画布:使用 opendirector asset import-url,不要自己用 curl/wget 拼直链下载。Use when the user gives a video page URL and wants the video in the project, on the canvas, or as a reference. +--- + +# Video link import / 从链接导入视频 + +`opendirector asset import-url` downloads the video on a page with the site's +own extractor, prefers a format the browser can play (H.264, VP9 or AV1 up to +1080p), and registers it through the same path as `asset import`. Do not +resolve direct file URLs with curl or wget: a page's original file may be a +format the canvas cannot play. + +## Steps + +1. Read the canvas with `opendirector project show --summary` to choose a + free position. +2. `opendirector asset import-url "URL"` — add `--name` for a custom title. + The receipt returns `assetId` and `source` (`url`, `title`, `site`, + `durationSeconds`); in an Agent turn `file` is the downloaded copy in the + execution directory. +3. `opendirector canvas add-material --asset ASSET_ID --x X --y Y` shows it + on the canvas. + +## When the import is refused + +A refusal is final for that link. Never fetch the same link another way +(curl, wget, Python, a browser tool or a different URL for the same host), +even if the user gave a direct file URL: the refusal is a security or policy +check, not a transport problem. Report the error code and ask the user to +upload the file or give a public page of a single video. + +- `url_import_private`: the link points to this computer or a local or + private network. +- `url_import_playlist`, `url_import_live`, `url_import_too_long`, + `url_import_too_large`, `url_import_unsupported`: ask for a single video + page of at most 15 minutes and 512 MB that is offered as a file, not only as + a stream. +- `url_import_failed`: the site refused or failed, often because it blocks + server downloads; ask the user to download the file and upload it. + +Import only videos the user has the right to use. diff --git a/packages/core/src/opendirector/application/creation_assets.py b/packages/core/src/opendirector/application/creation_assets.py index eded85e95..d58a7ef44 100644 --- a/packages/core/src/opendirector/application/creation_assets.py +++ b/packages/core/src/opendirector/application/creation_assets.py @@ -13,6 +13,8 @@ from opendirector.domain.creation.project import ProjectSnapshot from opendirector.domain.creation.validation import ContractError from opendirector.domain.projects import ProjectError +from opendirector.domain.url_import import url_import_error +from opendirector.media.downloads import download_video, validate_url, video_filename from opendirector.media.processing import open_image, png from opendirector.ports.files import ( AssetFileWrite, CHUNK_BYTES, MAX_CREATION_TEXT_BYTES, stream_identity, @@ -48,6 +50,34 @@ def stage_copy(self, project_id, handle, session, source_project_id, source_asse finally: writer.abort() + def stage_url(self, project_id, handle, session, url, *, cancelled=None): + url = validate_url(url) + owner = self.uploads.owner(project_id, handle, session) + if owner is not None: + if owner.sourceUrl != url or owner.cancelled: + raise url_import_error('url_import_handle_conflict') + staged = self.uploads.info(project_id, handle, session) + if staged.status in {'ready', 'registered'}: + return staged + stopped = cancelled or (lambda: False) + with TemporaryDirectory(prefix='opendirector-url-') as folder: + video = download_video(url, Path(folder), cancelled=cancelled) + if stopped(): + raise url_import_error('url_import_cancelled') + writer = self.uploads.begin(project_id, handle, session, video_filename(video.title, video.path.suffix or '.mp4'), + expected_kind='video', source_url=url) + try: + with video.path.open('rb') as stream: + while (chunk := stream.read(CHUNK_BYTES)) and not stopped(): + writer.write(chunk) + staged = None if stopped() else writer.finish() + finally: + writer.abort() + if stopped(): + self.uploads.cancel(project_id, handle, session) + raise url_import_error('url_import_cancelled') + return staged + def reference_available(self, project_id, asset_id, *, snapshot=None): stream, asset = self.open_media(project_id, asset_id, snapshot=snapshot) return self.check_reference_media(stream, asset) diff --git a/packages/core/src/opendirector/cli.py b/packages/core/src/opendirector/cli.py index 7f07da17f..ac9ff713f 100644 --- a/packages/core/src/opendirector/cli.py +++ b/packages/core/src/opendirector/cli.py @@ -35,6 +35,7 @@ from opendirector.domain.creation.commands import COMMAND_MODELS, command_fingerprint, parse_command from opendirector.domain.projects import ProjectError from opendirector.domain.timeline_errors import timeline_error, timeline_error_message +from opendirector.domain.url_import import url_import_error, url_import_message # Set once this process has told the transport how it started, so later requests # from the same process are not charged that start-up again. @@ -527,12 +528,19 @@ def asset_import(ctx: typer.Context, name: Annotated[str | None, typer.Option(help="Asset display name.")] = None): client = ctx.obj client.command = ctx.command_path + receipt = import_local_file(client, file, kind, name) + emit(receipt) + if receipt.get("status") == "rejected": + raise typer.Exit(1) + + +def import_local_file(client, file, kind, name, operation=None, handle=None): if client.live: # Server resolves and confines this path to the turn's execution directory. - emit(client.execute("artifact.publish", {"path": str(file), "name": name or file.name, "expectedKind": kind})) - return - operation = client.operation_id or uuid4() - handle = operation + return client.execute("artifact.publish", {"path": str(file), "name": name or file.name, "expectedKind": kind}, + identity=operation) + operation = operation or client.operation_id or uuid4() + handle = handle or operation payload = {"uploadHandle": str(handle), "name": name or file.name, "expectedKind": kind} previous = client.http.get(client.path(f"/receipts/{operation}")) if previous.status_code == 200: @@ -550,17 +558,70 @@ def asset_import(ctx: typer.Context, digest.update(chunk) if asset["fingerprint"] != "sha256:" + digest.hexdigest(): raise ProjectError("Operation ID was already used with different file content.") - emit(receipt) - if receipt["status"] == "rejected": - raise typer.Exit(1) - return + return receipt if previous.status_code != 404: raise ProjectError(previous.text, previous.status_code) client.open() with file.open("rb") as stream: client.request("PUT", client.path(f"/uploads/{handle}"), headers={"X-Asset-Name": quote(name or file.name), "X-Asset-Kind": kind}, content=stream) - emit(client.execute("asset.import", payload, identity=operation)) + return client.execute("asset.import", payload, identity=operation) + + +@group("asset").command("import-url", help="Download the single video on a supported web page and register it as a video asset.", + epilog="Example: opendirector --project PROJECT_UUID asset import-url \"https://commons.wikimedia.org/wiki/File:EXAMPLE.webm\" " + "Then show it on the canvas with canvas add-material.") +def asset_import_url(ctx: typer.Context, + url: Annotated[str, typer.Argument(help="Page of one video on a site yt-dlp supports (no playlists or live streams).")], + name: Annotated[str | None, typer.Option(help="Asset display name; defaults to the page title.")] = None, + output_dir: Annotated[Path | None, typer.Option(file_okay=False, + help="Keep the downloaded file in this directory. In an Agent turn it defaults to ./downloads " + "in the execution directory; otherwise a temporary directory is removed afterwards.")] = None): + import tempfile + from opendirector.infrastructure.creation_uploads import upload_asset_id + from opendirector.media.downloads import download_video, validate_url, video_filename + client = ctx.obj + client.command = ctx.command_path + url = validate_url(url) + operation = client.operation_id or uuid4() + handle = uuid5(operation, url) + if not client.live: + if client.project is None: + raise ProjectError("Select a project with --project UUID.") + previous = client.http.get(client.path(f"/receipts/{operation}")) + if previous.status_code == 200: + receipt = previous.json() + asset = next((item for item in receipt["changed"] if item["objectType"] == "asset"), None) + if receipt["status"] != "rejected" and (asset is None or asset["id"] != str(upload_asset_id(client.project, handle))): + raise url_import_error('url_import_operation_conflict') + emit({**receipt, "assetId": asset["id"] if asset else None, "replayed": True}) + if receipt["status"] == "rejected": + raise typer.Exit(1) + return + if previous.status_code != 404: + raise ProjectError(previous.text, previous.status_code) + keep = output_dir or (Path.cwd() / "downloads" if client.live else None) + with tempfile.TemporaryDirectory(prefix="opendirector-url-") as temporary: + folder = (keep / str(operation)) if keep else Path(temporary) + folder.mkdir(parents=True, exist_ok=True) + record = folder / "source.json" + page = json.loads(record.read_text(encoding="utf-8")) if record.is_file() else None + if page is not None and page["url"] != url: + raise url_import_error('url_import_operation_conflict') + if page is None or not (folder / page["file"]).is_file(): + video = download_video(url, folder) + page = {"url": url, "page": video.url, "title": video.title, "site": video.site, + "durationSeconds": video.duration, "file": video.path.name} + record.write_text(json.dumps(page, ensure_ascii=False), encoding="utf-8") + path = folder / page["file"] + receipt = import_local_file(client, path, "video", name or video_filename(page["title"], path.suffix or ".mp4"), + operation, handle) + asset = next((item for item in receipt.get("changed", []) if item["objectType"] == "asset"), None) + emit({**receipt, "assetId": asset["id"] if asset else None, + "source": {"url": page["page"], "title": page["title"], "site": page["site"], "durationSeconds": page["durationSeconds"]}, + **({"file": str(path)} if keep else {})}) + if receipt.get("status") == "rejected": + raise typer.Exit(1) @group("canvas").command("optimize-prompt", help="Rewrite an image or video prompt with the node's references and a configured text model; does not edit the canvas.") @@ -1049,7 +1110,9 @@ def main(): value = {"error": str(error)} if isinstance(error, ProjectError): value['code'] = error.code - value['error'] = timeline_error_message(error.code, os.environ.get('OPENDIRECTOR_LANGUAGE', 'en-US')) or str(error) + language = os.environ.get('OPENDIRECTOR_LANGUAGE', 'en-US') + value['error'] = (timeline_error_message(error.code, language) or url_import_message(error.code, language, str(error)) + or str(error)) emit(value) raise SystemExit(1) diff --git a/packages/core/src/opendirector/domain/url_import.py b/packages/core/src/opendirector/domain/url_import.py new file mode 100644 index 000000000..7a4695db4 --- /dev/null +++ b/packages/core/src/opendirector/domain/url_import.py @@ -0,0 +1,50 @@ +from opendirector.domain.projects import ProjectError + +MAX_DOWNLOAD_SECONDS = 15 * 60 +MAX_DOWNLOAD_BYTES = 512 * 1024 * 1024 + +URL_IMPORT_MESSAGES = { + 'url_import_invalid': ('请输入有效的视频网页链接。', 'Enter a valid link to a video page.'), + 'url_import_private': ('不能从本机或局域网地址下载视频。', + 'Videos cannot be downloaded from this computer or the local network.'), + 'url_import_unsupported': ('不支持该网站或该视频的下载方式,请改为下载后从本地导入。', + 'This site or video cannot be downloaded here. Download the video and import the file instead.'), + 'url_import_failed': ('无法从该链接下载视频。', 'Could not download the video from this link.'), + 'url_import_timeout': ('下载超时,请改为下载后从本地导入。', 'The download timed out. Download the video and import the file instead.'), + 'url_import_unavailable': ('未安装链接下载组件 yt-dlp,请重新安装 OpenDirector 后重试。', + 'The link download component yt-dlp is not installed. Reinstall OpenDirector and try again.'), + 'url_import_playlist': ('该链接是播放列表或合集,请改用单个视频的链接。', + 'This link is a playlist or collection. Use the link of a single video.'), + 'url_import_live': ('不能下载正在直播或尚未开始的视频。', 'Live or upcoming streams cannot be downloaded.'), + 'url_import_too_long': (f'视频超过 {MAX_DOWNLOAD_SECONDS // 60} 分钟,请先截取需要参考的片段。', + f'The video is longer than {MAX_DOWNLOAD_SECONDS // 60} minutes. Trim the part you want to reference first.'), + 'url_import_too_large': (f'视频文件超过 {MAX_DOWNLOAD_BYTES // (1024 * 1024)} MB,请改用较短或较低清晰度的版本。', + f'The video file is larger than {MAX_DOWNLOAD_BYTES // (1024 * 1024)} MB. Use a shorter or lower-resolution version.'), + 'url_import_cancelled': ('已取消下载。', 'The download was cancelled.'), + 'url_import_handle_conflict': ('该上传句柄已取消或已用于其他链接,请使用新的句柄。', + 'This upload handle was cancelled or already used for another link. Use a new handle.'), + 'url_import_operation_conflict': ('该操作标识已用于其他链接,请换一个操作标识。', + 'This operation ID was already used with a different link. Use a new operation ID.'), +} + +URL_IMPORT_STATUS = {'url_import_unavailable': 503, 'url_import_cancelled': 499, 'url_import_handle_conflict': 409, + 'url_import_operation_conflict': 409, 'url_import_timeout': 504} + +DETAIL_SEPARATOR = ':' + + +def url_import_error(code: str, detail: str = '') -> ProjectError: + message = URL_IMPORT_MESSAGES[code][0] + if detail: + message = message.rstrip('。') + DETAIL_SEPARATOR + detail + return ProjectError(message, URL_IMPORT_STATUS.get(code, 422), code=code) + + +def url_import_message(code: str | None, language: str | None, message: str = '') -> str | None: + messages = URL_IMPORT_MESSAGES.get(code or '') + if messages is None: + return None + english = (language or '').lower().startswith('en') + text = messages[1 if english else 0] + detail = message.partition(DETAIL_SEPARATOR)[2].strip() + return f'{text} {detail}' if english and detail else (message if detail else text) diff --git a/packages/core/src/opendirector/infrastructure/creation_uploads.py b/packages/core/src/opendirector/infrastructure/creation_uploads.py index 81707ee89..eead9a10f 100644 --- a/packages/core/src/opendirector/infrastructure/creation_uploads.py +++ b/packages/core/src/opendirector/infrastructure/creation_uploads.py @@ -41,6 +41,7 @@ class UploadOwner(Contract): name: str = Field(description='User-visible name.') expectedKind: MediaKind | None = Field(default=None, description='Required media kind, when specified.') cancelled: bool = Field(default=False, description='Whether the staged upload was cancelled.') + sourceUrl: str | None = Field(default=None, description='Web page the staged video was downloaded from.') class UploadRecord(Contract): @@ -142,9 +143,10 @@ def _owner(self, folder, project_id, handle, session): raise ProjectError('上传句柄不属于当前工程或会话。', 409) return owner - def begin(self, project_id, handle, session, name, *, expected_kind=None, trusted=False): + def begin(self, project_id, handle, session, name, *, expected_kind=None, trusted=False, source_url=None): project_id, handle = UUID(str(project_id)), UUID(str(handle)) - owner = UploadOwner(projectId=project_id, id=handle, sessionId=session, name=asset_name(name), expectedKind=expected_kind) + owner = UploadOwner(projectId=project_id, id=handle, sessionId=session, name=asset_name(name), expectedKind=expected_kind, + sourceUrl=source_url) lock = self.lock(project_id, handle) lock.acquire() try: @@ -177,6 +179,14 @@ def _info(self, owner, snapshot, record=None): kind=record.kind if record else None, fingerprint=record.fingerprint if record else None, metadata=record.metadata if record else None, assetId=asset_id if registered and not owner.cancelled else None) + def owner(self, project_id, handle, session): + with self.lock(project_id, handle), self.projects.local.transaction() as db: + self._scope(db, project_id, session) + folder = upload_directory(self.projects.state_dir, UUID(str(project_id)), UUID(str(handle))) + if not child(folder, 'owner.json').exists(): + return None + return self._owner(folder, project_id, handle, session) + def info(self, project_id, handle, session): with self.lock(project_id, handle), self.projects.local.transaction() as db: snapshot = self._scope(db, project_id, session) diff --git a/packages/core/src/opendirector/integrations/http_settings.py b/packages/core/src/opendirector/integrations/http_settings.py index 5a775808a..5f60aef81 100644 --- a/packages/core/src/opendirector/integrations/http_settings.py +++ b/packages/core/src/opendirector/integrations/http_settings.py @@ -128,15 +128,16 @@ def _public_candidate(url, schemes): return target, host, port or (443 if target.scheme == 'https' else 80) +def public_address(address): + checked = getattr(address, 'ipv4_mapped', None) or address + return checked.is_global and not checked.is_multicast and not checked.is_reserved + + def _public_pin(target, answers): """Check every answer; pin to the first. None when any answer is not public.""" addresses = [ip_address(answer) for answer in answers] - if not addresses: + if not addresses or not all(map(public_address, addresses)): return None - for address in addresses: - checked = getattr(address, 'ipv4_mapped', None) or address - if not checked.is_global or checked.is_multicast or checked.is_reserved: - return None # A pooled connection to one IP must not reuse another hostname's TLS identity. headers = {'Host': target.netloc.decode('ascii'), 'Connection': 'close'} return target.copy_with(host=str(addresses[0])), headers, {'sni_hostname': target.host} diff --git a/packages/core/src/opendirector/media/download_worker.py b/packages/core/src/opendirector/media/download_worker.py new file mode 100644 index 000000000..8eaa9b82a --- /dev/null +++ b/packages/core/src/opendirector/media/download_worker.py @@ -0,0 +1,167 @@ +import importlib +import ipaddress +import json +import os +import signal +import socket +import subprocess +import sys +import threading +from pathlib import Path + +from opendirector.integrations.http_settings import public_address + +BLOCKED = 'opendirector-blocked-address' +TOO_LARGE = 'opendirector-too-large' +BLOCKED_PROGRAM = 'opendirector-blocked-program' +LOCAL_PROGRAMS = frozenset({'ffmpeg', 'ffprobe', 'deno'}) +PROXY_VARIABLES = ('http_proxy', 'https_proxy', 'all_proxy', 'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY') + + +class Rejected(Exception): + def __init__(self, code, detail=''): + super().__init__(code) + self.code, self.detail = code, detail + + +def global_address(text): + return public_address(ipaddress.ip_address(text.split('%', 1)[0])) + + +def guard(resolve): + def checked(host, port, *args, **kwargs): + answers = resolve(host, port, *args, **kwargs) + name = (host.decode() if isinstance(host, bytes) else str(host)).lower().rstrip('.') + if not answers or not all(global_address(answer[4][0]) for answer in answers): + raise OSError(f'{BLOCKED}: {name}') + return answers + return checked + + +def confine(yt_dlp): + external = importlib.import_module('yt_dlp.downloader.external') + popen = subprocess.Popen.__init__ + + def local_only(self, args, *rest, **kwargs): + program = Path(str(args[0] if isinstance(args, (list, tuple)) else args)).stem.lower() + if program not in LOCAL_PROGRAMS: + raise OSError(f'{BLOCKED_PROGRAM}: {program}') + popen(self, args, *rest, **kwargs) + + def no_external_download(self, filename, info_dict): + raise yt_dlp.utils.DownloadError(f'{BLOCKED_PROGRAM}: {self.get_basename()}') + subprocess.Popen.__init__ = local_only + external.ExternalFD.real_download = no_external_download + + +def exit_with_parent(stream): + def watch(): + while stream.read(65536): + pass + if hasattr(os, 'killpg') and os.getpgrp() == os.getpid(): + os.killpg(os.getpid(), signal.SIGKILL) + os._exit(1) + threading.Thread(target=watch, daemon=True).start() + + +class _QuietLogger: + def debug(self, message): + pass + + info = warning = debug + + def error(self, message): + pass + + +def _detail(error): + text = str(error).removeprefix('ERROR: ').strip() + return text.splitlines()[0][:200] if text else '' + + +def fetch(request, yt_dlp): + folder, max_bytes = Path(request['folder']), request['maxBytes'] + sizes = {} + + def watch(state): + sizes[state.get('tmpfilename') or state.get('filename')] = state.get('downloaded_bytes') or 0 + if sum(sizes.values()) > max_bytes: + raise yt_dlp.utils.DownloadCancelled(TOO_LARGE) + + options = { + 'quiet': True, 'no_warnings': True, 'noprogress': True, 'logger': _QuietLogger(), + 'noplaylist': True, 'cachedir': False, 'overwrites': True, 'restrictfilenames': True, + 'allowed_extractors': ['default', '-generic'], + 'outtmpl': {'default': str(folder / 'source.%(ext)s')}, + 'format': request['format'], 'merge_output_format': 'mp4', + 'max_filesize': max_bytes, 'socket_timeout': 30, 'progress_hooks': [watch], 'proxy': '', + 'external_downloader': {}, 'hls_prefer_native': True, + } + + def failure(error): + text = str(error) + if BLOCKED in text: + return Rejected('url_import_private') + if TOO_LARGE in text or sum(sizes.values()) > max_bytes: + return Rejected('url_import_too_large') + if 'Unsupported URL' in text or BLOCKED_PROGRAM in text or 'No suitable extractor' in text or 'Requested format is not available' in text: + return Rejected('url_import_unsupported') + return Rejected('url_import_failed', _detail(error)) + + with yt_dlp.YoutubeDL(options) as client: + try: + info = client.extract_info(request['url'], download=False, process=False) + if info is not None and info.get('_type') not in {'playlist', 'multi_video'}: + info = client.process_ie_result(info, download=False) + except yt_dlp.utils.YoutubeDLError as error: + raise failure(error) from None + if info is None or info.get('_type') in {'playlist', 'multi_video'}: + raise Rejected('url_import_playlist') + if info.get('is_live') or info.get('live_status') in {'is_live', 'is_upcoming'}: + raise Rejected('url_import_live') + if info.get('section_start') is not None or info.get('section_end') is not None: + raise Rejected('url_import_unsupported') + duration = info.get('duration') + if duration and duration > request['maxSeconds']: + raise Rejected('url_import_too_long') + try: + info = client.process_ie_result(info, download=True) + except yt_dlp.utils.YoutubeDLError as error: + raise failure(error) from None + files = [Path(item['filepath']) for item in info.get('requested_downloads') or [] if item.get('filepath')] + path = next((item for item in files if item.is_file()), None) + if path is None: + announced = max([info.get('filesize') or 0, info.get('filesize_approx') or 0, + *[(item.get('filesize') or item.get('filesize_approx') or 0) for item in info.get('requested_formats') or []]]) + raise Rejected('url_import_too_large' if max(announced, sum(sizes.values())) > max_bytes else 'url_import_failed') + if path.stat().st_size > max_bytes: + raise Rejected('url_import_too_large') + return {'path': str(path), 'title': ((info.get('title') or '').strip() or path.stem)[:200], + 'url': info.get('webpage_url') or request['url'], + 'site': info.get('extractor_key') or info.get('extractor') or '', 'duration': duration} + + +def main(): + request = json.loads(sys.stdin.readline()) + exit_with_parent(sys.stdin) + for name in PROXY_VARIABLES: + os.environ.pop(name, None) + socket.getaddrinfo = guard(socket.getaddrinfo) + sys.modules['curl_cffi'] = None + try: + import yt_dlp + except ImportError: + result = {'code': 'url_import_unavailable'} + else: + confine(yt_dlp) + try: + result = {'video': fetch(request, yt_dlp)} + except Rejected as rejected: + result = {'code': rejected.code, 'detail': rejected.detail} + sys.stdout.write(json.dumps(result)) + sys.stdout.flush() + os._exit(0) + + +if __name__ == '__main__': + main() diff --git a/packages/core/src/opendirector/media/downloads.py b/packages/core/src/opendirector/media/downloads.py new file mode 100644 index 000000000..a07e16129 --- /dev/null +++ b/packages/core/src/opendirector/media/downloads.py @@ -0,0 +1,119 @@ +import ipaddress +import json +import os +import re +import signal +import subprocess +import sys +import threading +import time +from contextlib import suppress +from dataclasses import dataclass +from pathlib import Path +from urllib.parse import urlsplit + +from opendirector.domain.url_import import MAX_DOWNLOAD_BYTES, MAX_DOWNLOAD_SECONDS, url_import_error + +MAX_URL_LENGTH = 2048 +MAX_DOWNLOAD_HEIGHT = 1080 +DOWNLOAD_TIMEOUT_SECONDS = 30 * 60 +WINDOWS = sys.platform == 'win32' +WORKER = (sys.executable, '-X', 'utf8', '-P', '-m', 'opendirector.media.download_worker') + + +@dataclass(frozen=True) +class DownloadedVideo: + path: Path + title: str + url: str + site: str + duration: float | None + + +def validate_url(url: str) -> str: + value = (url or '').strip() + if not value or len(value) > MAX_URL_LENGTH or any(char.isspace() for char in value): + raise url_import_error('url_import_invalid') + parts = urlsplit(value) + if parts.scheme not in {'http', 'https'} or not parts.hostname or parts.username or parts.password: + raise url_import_error('url_import_invalid') + host = parts.hostname.rstrip('.').lower() + if host == 'localhost' or host.endswith('.localhost') or host.endswith('.local'): + raise url_import_error('url_import_private') + try: + address = ipaddress.ip_address(host) + except ValueError: + return value + if not address.is_global: + raise url_import_error('url_import_private') + return value + + +PLAYABLE_VIDEO = "[vcodec~='^(avc1|h264|vp0?9|av01)']" +DIRECT = "[protocol~='^https?$']" + +def download_format(): + limit = f'[height<={MAX_DOWNLOAD_HEIGHT}]{DIRECT}' + return '/'.join([f'bv*{limit}{PLAYABLE_VIDEO}+ba{DIRECT}', f'b{limit}{PLAYABLE_VIDEO}', + f'bv*{limit}+ba{DIRECT}', f'b{limit}', f'bv*{DIRECT}+ba{DIRECT}', f'b{DIRECT}']) + + +def _stop(worker): + if worker.poll() is None: + try: + if WINDOWS: + subprocess.run(['taskkill', '/PID', str(worker.pid), '/T', '/F'], capture_output=True, check=False, timeout=5) + else: + os.killpg(worker.pid, signal.SIGKILL) + except (OSError, subprocess.SubprocessError): + with suppress(ProcessLookupError): + worker.kill() + worker.wait() + + +def rejection(code, detail=''): + return url_import_error(code, detail if code == 'url_import_failed' else '') + + +def download_video(url: str, folder: Path, *, cancelled=None) -> DownloadedVideo: + url = validate_url(url) + request = {'url': url, 'folder': str(folder), 'format': download_format(), + 'maxBytes': MAX_DOWNLOAD_BYTES, 'maxSeconds': MAX_DOWNLOAD_SECONDS} + worker = subprocess.Popen(WORKER, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, + text=True, encoding='utf-8', start_new_session=not WINDOWS) + chunks = [] + reader = threading.Thread(target=lambda: chunks.append(worker.stdout.read()), daemon=True) + reader.start() + try: + worker.stdin.write(json.dumps(request) + '\n') + worker.stdin.flush() + deadline = time.monotonic() + DOWNLOAD_TIMEOUT_SECONDS + while worker.poll() is None: + if cancelled is not None and cancelled(): + raise rejection('url_import_cancelled') + if time.monotonic() > deadline: + raise rejection('url_import_timeout') + time.sleep(0.2) + reader.join(timeout=10) + output = ''.join(chunks) + finally: + _stop(worker) + with suppress(OSError): + worker.stdin.close() + reader.join(timeout=10) + if not reader.is_alive(): + worker.stdout.close() + try: + result = json.loads(output) + except ValueError: + raise rejection('url_import_failed') from None + if 'video' not in result: + raise rejection(result.get('code', 'url_import_failed'), result.get('detail', '')) + video = result['video'] + return DownloadedVideo(path=Path(video['path']), title=video['title'][:200], url=video['url'], + site=video['site'], duration=video['duration']) + + +def video_filename(title: str, suffix: str = '.mp4') -> str: + stem = re.sub(r'\s+', ' ', re.sub(r'[\\/:*?"<>|\x00-\x1f]+', ' ', title)).strip(' .') or 'video' + return stem[:120] + suffix diff --git a/pyproject.toml b/pyproject.toml index 992c4e7c0..cf11a9583 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -13,7 +13,7 @@ dependencies = [ "PyYAML>=6,<7", "filelock>=3.16,<4", "httpx[socks]>=0.27,<1", "anyio>=4,<5", "pydantic>=2.12,<3", "typer>=0.27.3,<0.28", "Pillow>=12,<14", "pillow-heif>=1.8.1,<2", "fonttools==4.68.0", "fastapi>=0.115,<1", "uvicorn>=0.30,<1", - "starlette>=1.8,<2", "python-multipart>=0.0.33,<1", + "starlette>=1.8,<2", "python-multipart>=0.0.33,<1", "yt-dlp>=2026.11.23", "distlib>=0.4,<1; sys_platform == 'win32'", ] diff --git a/requirements.txt b/requirements.txt index ee26fc8c7..d21534ecd 100644 --- a/requirements.txt +++ b/requirements.txt @@ -111,3 +111,5 @@ typing-inspection==0.4.4 # pydantic uvicorn==0.54.0 # via opendirector (pyproject.toml) +yt-dlp==2026.11.23 + # via opendirector (pyproject.toml) diff --git a/src/backend/creationClient.ts b/src/backend/creationClient.ts index 392c47e44..b7c7ad0f7 100644 --- a/src/backend/creationClient.ts +++ b/src/backend/creationClient.ts @@ -739,6 +739,21 @@ export class CreationClient { ); return this.registerUpload(handle, info.name, info.kind); } + async importUrl(url: string, handle: string = crypto.randomUUID(), signal?: AbortSignal) { + const path = `${creationPath(this.id)}/uploads/${handle}`; + try { + const info = await request<{ name: string; kind: Asset["kind"] }>( + `${path}/url`, + { ...json("PUT", { url }), signal }, + ); + signal?.throwIfAborted(); + return await this.registerUpload(handle, info.name, info.kind); + } catch (error) { + if (signal?.aborted) + await storageRequest(path, { method: "DELETE" }).catch(() => undefined); + throw error; + } + } private async registerUpload( handle: string, name: string, diff --git a/src/canvas/CanvasCreationMenu.tsx b/src/canvas/CanvasCreationMenu.tsx index 9bd3dc7ce..14a5c71bb 100644 --- a/src/canvas/CanvasCreationMenu.tsx +++ b/src/canvas/CanvasCreationMenu.tsx @@ -43,12 +43,14 @@ type CreationActions = { onCreate: (kind: CanvasNodeKind) => void; onAssets: () => void; onUpload: () => void; + onImportUrl?: () => void; }; export function CreationMenuContent({ onCreate, onAssets, onUpload, + onImportUrl, allowedKinds, nodesOnly = false, }: CreationActions & { @@ -111,6 +113,12 @@ export function CreationMenuContent({ {t("canvas.menu.localUpload")} + {onImportUrl && ( + + )} )} @@ -234,6 +242,9 @@ export function CanvasCreationMenu({ onCreate: (kind: CanvasNodeKind) => run(() => actions.onCreate(kind)), onAssets: () => run(actions.onAssets), onUpload: () => run(actions.onUpload), + onImportUrl: actions.onImportUrl + ? () => run(actions.onImportUrl!) + : undefined, }; const shortcuts = navigator.platform.includes("Mac") ? ["⌘V", "⌘⇧Z", "⌘Z"] diff --git a/src/canvas/VideoLinkDialog.tsx b/src/canvas/VideoLinkDialog.tsx new file mode 100644 index 000000000..2c05dc306 --- /dev/null +++ b/src/canvas/VideoLinkDialog.tsx @@ -0,0 +1,97 @@ +import { useEffect, useRef, useState } from "react"; +import { errorMessage } from "../backend/api"; +import { useT } from "../i18n/I18nProvider"; + +export function VideoLinkDialog({ + onClose, + onSubmit, +}: { + onClose: () => void; + onSubmit: (url: string, signal: AbortSignal) => Promise; +}) { + const t = useT(); + const dialog = useRef(null); + const download = useRef(null); + const [url, setUrl] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + useEffect(() => { + const element = dialog.current!; + element.showModal(); + return () => { + download.current?.abort(); + element.close(); + }; + }, []); + const cancel = () => { + download.current?.abort(); + onClose(); + }; + return ( + { + event.preventDefault(); + cancel(); + }} + onClick={(event) => { + if (event.target === event.currentTarget && !busy) cancel(); + }} + > +
{ + event.preventDefault(); + if (busy || !url.trim()) return; + const controller = new AbortController(); + download.current = controller; + setBusy(true); + setError(""); + try { + await onSubmit(url.trim(), controller.signal); + if (!controller.signal.aborted) onClose(); + } catch (reason) { + if (!controller.signal.aborted) setError(errorMessage(reason)); + } finally { + if (download.current === controller) download.current = null; + if (!controller.signal.aborted) setBusy(false); + } + }} + > + + + setUrl(event.target.value)} + placeholder="https://" + /> +

{busy ? t("canvas.linkImport.downloading") : t("canvas.linkImport.hint")}

+ {error && ( +

+ {error} +

+ )} +
+ + +
+
+
+ ); +} diff --git a/src/canvas/workspace/WorkspaceView.tsx b/src/canvas/workspace/WorkspaceView.tsx index 79e33f120..f5dd772ce 100644 --- a/src/canvas/workspace/WorkspaceView.tsx +++ b/src/canvas/workspace/WorkspaceView.tsx @@ -45,6 +45,7 @@ import { CanvasActionsContext } from "../CanvasActionsContext"; import { CanvasConnectionLine, CanvasConnectionPreview, CanvasInteractionOverlay } from "../CanvasConnections"; import { CanvasCreationMenu, CreationMenuContent } from "../CanvasCreationMenu"; +import { VideoLinkDialog } from "../VideoLinkDialog"; import { CanvasFlowSurface } from "../CanvasFlowSurface"; import { CanvasIcon } from "../CanvasIcon"; @@ -224,6 +225,7 @@ export function WorkspaceView({ rt, editingState, editSession }: { importDocument, importFiles, importInput, + importUrl, importLibrarySubjects, initializationError, insertLibraryItems, @@ -393,6 +395,7 @@ export function WorkspaceView({ rt, editingState, editSession }: { setWelcomeOpen(false); }; const [exampleLoading, setExampleLoading] = useState(false); + const [linkImportPoint, setLinkImportPoint] = useState<{ x: number; y: number } | null>(null); const exampleCatalog = useRef | null>(null); const optimizedPrompts = useRef(new Map()); const loadExamples = () => @@ -2158,6 +2161,7 @@ export function WorkspaceView({ rt, editingState, editSession }: { setLibraryOpen(true); }} onUpload={() => openFilePicker()} + onImportUrl={readOnly ? undefined : () => setLinkImportPoint(menu.world)} onPaste={() => paste()} onUndo={() => replayHistory()} onRedo={() => replayHistory(true)} @@ -2733,6 +2737,12 @@ export function WorkspaceView({ rt, editingState, editSession }: { /> )} + {linkImportPoint && ( + setLinkImportPoint(null)} + onSubmit={(url, signal) => importUrl(url, linkImportPoint, signal)} + /> + )} { + const documentId = historyRef.current.present.id; + const ref = await creationClient(documentId).importUrl(url, crypto.randomUUID(), signal); + const resource = await workspaceProjection(documentId).resource(ref); + if (historyRef.current.present.id !== documentId) { + notify(t("canvas.workspace.toast.importCancelledSwitched")); + return; + } + const where = point ?? center(); + const node = createNode( + resource.kind, + { x: where.x - 176, y: where.y - 130 }, + resourceNodeData(resource), + ); + command({ type: "add-nodes", nodes: [node] }); + setSelected([node.id]); + notify(t("canvas.linkImport.done", { title: resource.title })); + }; + const insertLibraryItems = async (items: LibraryItem[]) => { const client = creationClient(doc.id); let placed = 0; @@ -968,4 +987,5 @@ export function useWorkspaceTransfer(rt: WorkspaceRuntime, readOnly: boolean) { rt.importCanvasArchive = importCanvasArchive; rt.openFilePicker = openFilePicker; rt.importFiles = importFiles; + rt.importUrl = importUrl; } diff --git a/src/i18n/messages/en-US/canvas.ts b/src/i18n/messages/en-US/canvas.ts index 8fb622281..d8ba702a6 100644 --- a/src/i18n/messages/en-US/canvas.ts +++ b/src/i18n/messages/en-US/canvas.ts @@ -20,6 +20,14 @@ export const canvas = { "This downstream type is not supported, or the reference source is unavailable", "canvas.menu.addFromAssets": "Add from asset library", "canvas.menu.localUpload": "Upload from computer", + "canvas.menu.importFromLink": "Import video from link", + "canvas.linkImport.title": "Import video from link", + "canvas.linkImport.label": "Video page link", + "canvas.linkImport.hint": "Use the page of a single video on a common video site, up to 15 minutes and 512 MB; playlists and live streams are not supported. Import only videos you have the right to use. Some sites block server downloads; download the file and upload it instead.", + "canvas.linkImport.downloading": "Downloading and registering the video. Longer videos can take a few minutes.", + "canvas.linkImport.importing": "Importing…", + "canvas.linkImport.submit": "Import", + "canvas.linkImport.done": "Imported “{title}”.", "canvas.menu.paste": "Paste", "canvas.menu.redo": "Redo", "canvas.menu.undo": "Undo", diff --git a/src/i18n/messages/zh-CN/canvas.ts b/src/i18n/messages/zh-CN/canvas.ts index 2027d1267..17f8080f5 100644 --- a/src/i18n/messages/zh-CN/canvas.ts +++ b/src/i18n/messages/zh-CN/canvas.ts @@ -20,6 +20,14 @@ export const canvas = { "canvas.menu.downstreamUnavailable": "不支持此下游类型或参考源不可用", "canvas.menu.addFromAssets": "从资产库添加", "canvas.menu.localUpload": "本地上传", + "canvas.menu.importFromLink": "从链接导入视频", + "canvas.linkImport.title": "从链接导入视频", + "canvas.linkImport.label": "视频网页链接", + "canvas.linkImport.hint": "支持常见视频网站的单个视频页面,最长 15 分钟、512 MB;不支持播放列表和直播。请只导入你有权使用的视频。部分网站会拦截服务器下载,可下载后改用本地上传。", + "canvas.linkImport.downloading": "正在下载并登记视频,较长的视频可能需要几分钟。", + "canvas.linkImport.importing": "正在导入…", + "canvas.linkImport.submit": "导入", + "canvas.linkImport.done": "已导入「{title}」。", "canvas.menu.paste": "粘贴", "canvas.menu.redo": "重做", "canvas.menu.undo": "撤销", diff --git a/tests/creationClient.test.ts b/tests/creationClient.test.ts index bedadcde4..7d7b62637 100644 --- a/tests/creationClient.test.ts +++ b/tests/creationClient.test.ts @@ -1907,3 +1907,46 @@ test("a failed display read is reported and recovers on retry", async () => { globalThis.fetch = original; } }); + +test("a link import stages on the server, registers once, and a cancelled one is cleaned up unregistered", async () => { + const snapshot = empty(), client = new CreationClient(snapshot.project.id); + client.install(snapshot); + const registered: string[] = []; + Object.assign(client, { + registerUpload: async (handle: string, name: string, kind: string) => { + registered.push(`${handle}:${name}:${kind}`); + return { assetId: handle, revision: 1, fingerprint: "sha256:x", kind }; + }, + }); + const original = globalThis.fetch; + const calls: { url: string; method: string; body?: string }[] = []; + let hold: ((value: Response) => void) | undefined; + globalThis.fetch = async (input, options) => { + calls.push({ url: String(input), method: options?.method ?? "GET", body: options?.body as string | undefined }); + if (String(input).endsWith("/url") && hold === undefined) + return Response.json({ name: "Clip.webm", kind: "video" }); + if (String(input).endsWith("/url")) + return new Promise((resolve, reject) => { + hold = resolve; + options?.signal?.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError"))); + }); + return Response.json({}); + }; + try { + await client.importUrl("https://example.com/v/1", "handle-1"); + assert.equal(calls[0]!.method, "PUT"); + assert.ok(calls[0]!.url.endsWith(`/projects/${snapshot.project.id}/uploads/handle-1/url`)); + assert.deepEqual(JSON.parse(calls[0]!.body!), { url: "https://example.com/v/1" }); + assert.deepEqual(registered, ["handle-1:Clip.webm:video"]); + hold = () => undefined; + const controller = new AbortController(); + const pending = client.importUrl("https://example.com/v/2", "handle-2", controller.signal); + await new Promise((resolve) => setTimeout(resolve, 0)); + controller.abort(); + await assert.rejects(pending); + assert.deepEqual(registered, ["handle-1:Clip.webm:video"]); + assert.ok(calls.some((call) => call.method === "DELETE" && call.url.endsWith("/uploads/handle-2"))); + } finally { + globalThis.fetch = original; + } +}); diff --git a/tests/test_video_link_import.py b/tests/test_video_link_import.py new file mode 100644 index 000000000..6b8d176e6 --- /dev/null +++ b/tests/test_video_link_import.py @@ -0,0 +1,599 @@ +import asyncio +import http.server +import json +import os +import signal +import socket +import subprocess +import sys +import threading +import time +from pathlib import Path +from types import SimpleNamespace +from uuid import UUID, uuid4 + +import httpx +import pytest +from fastapi.testclient import TestClient +from typer.testing import CliRunner + +from opendirector import cli +from opendirector.agent.tools import AgentTools +from opendirector.application import creation_assets +from opendirector.application.creation_assets import CreationAssets +from opendirector.domain.creation.commands import parse_command +from opendirector.domain.projects import ProjectError +from opendirector.infrastructure.creation_files import upload_directory +from opendirector.infrastructure.creation_projects import CreationProjects +from opendirector.infrastructure.local_projects import LocalProjects +from opendirector.infrastructure.model_configs import ModelConfigs +from opendirector.media import download_worker, downloads +from opendirector_api.main import create_app +from generation_helpers import new_project + +pytestmark = pytest.mark.cpu + + +@pytest.fixture(scope='module') +def clip(): + return subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', 'testsrc2=size=160x90:rate=24:duration=2', + '-pix_fmt', 'yuv420p', '-c:v', 'libx264', '-f', 'mp4', '-movflags', 'frag_keyframe+empty_moov', + 'pipe:1'], capture_output=True, check=True).stdout + + +@pytest.fixture +def project(tmp_path): + store, pid, session = new_project(tmp_path, 'Link import') + return store, str(pid), session + + +@pytest.mark.parametrize('url, code', [ + ('ftp://example.com/video', 'url_import_invalid'), + ('not a url', 'url_import_invalid'), + ('https://user:secret@example.com/v', 'url_import_invalid'), + ('http://localhost:8000/v', 'url_import_private'), + ('http://127.0.0.1/v', 'url_import_private'), + ('http://192.168.1.10/v', 'url_import_private'), + ('http://[::1]/v', 'url_import_private'), + ('http://printer.local/v', 'url_import_private'), +]) +def test_link_validation_rejects_non_web_and_private_addresses(url, code): + with pytest.raises(ProjectError) as rejected: + downloads.validate_url(url) + assert rejected.value.code == code + + +class YoutubeDLError(Exception): + pass + + +class DownloadError(YoutubeDLError): + pass + + +class DownloadCancelled(YoutubeDLError): + pass + + +class FakeDownloader: + info: dict = {} + options: dict = {} + chunks: tuple = () + + def __init__(self, options): + FakeDownloader.options = options + + def __enter__(self): + return self + + def __exit__(self, *_): + return False + + def extract_info(self, url, download, process=True): + assert download is False and process is False + if self.info.get('error'): + raise DownloadError(self.info['error']) + return dict(self.info) + + def process_ie_result(self, info, download): + if not download: + return info + for downloaded in self.chunks: + for hook in self.options['progress_hooks']: + hook({'status': 'downloading', 'tmpfilename': 'source.part', 'downloaded_bytes': downloaded}) + path = Path(self.options['outtmpl']['default']).parent / 'source.mp4' + path.write_bytes(self.info.get('bytes', b'video')) + if self.info.get('skip'): + return {**info, 'requested_downloads': []} + return {**info, 'requested_downloads': [{'filepath': str(path)}]} + + +FAKE_YTDLP = SimpleNamespace(YoutubeDL=FakeDownloader, + utils=SimpleNamespace(DownloadError=DownloadError, DownloadCancelled=DownloadCancelled, + YoutubeDLError=YoutubeDLError)) + + +def fetch(tmp_path, info, *, chunks=(), max_bytes=1000): + FakeDownloader.info, FakeDownloader.chunks = info, chunks + return download_worker.fetch({'url': 'https://www.example.com/watch?v=1', 'folder': str(tmp_path), + 'format': downloads.download_format(), 'maxBytes': max_bytes, 'maxSeconds': 900}, FAKE_YTDLP) + + +@pytest.mark.parametrize('info, code', [ + ({'_type': 'playlist'}, 'url_import_playlist'), + ({'is_live': True}, 'url_import_live'), + ({'duration': 16 * 60}, 'url_import_too_long'), + ({'duration': 10, 'skip': True}, 'url_import_failed'), + ({'duration': 10, 'skip': True, 'filesize_approx': 5000}, 'url_import_too_large'), + ({'error': 'ERROR: Unsupported URL: https://example.com/'}, 'url_import_unsupported'), + ({'error': 'ERROR: No suitable extractor found for URL https://example.com/'}, 'url_import_unsupported'), + ({'error': 'ERROR: [site] 1: HTTP Error 412'}, 'url_import_failed'), + ({'error': 'ERROR: [site] 1: '}, 'url_import_private'), +]) +def test_worker_rejects_what_it_cannot_import(tmp_path, info, code): + with pytest.raises(download_worker.Rejected) as rejected: + fetch(tmp_path, info) + assert rejected.value.code == code + + +def test_a_playlist_is_refused_without_reading_its_entries(tmp_path): + def entries(): + raise AssertionError('playlist entries were read') + yield + with pytest.raises(download_worker.Rejected) as rejected: + fetch(tmp_path, {'_type': 'playlist', 'entries': entries()}) + assert rejected.value.code == 'url_import_playlist' + + +def test_worker_stops_once_the_streamed_bytes_exceed_the_budget(tmp_path): + with pytest.raises(download_worker.Rejected) as streamed: + fetch(tmp_path, {'title': 'Unknown size and duration'}, chunks=(600, 1200)) + assert streamed.value.code == 'url_import_too_large' + with pytest.raises(download_worker.Rejected) as large: + fetch(tmp_path, {'title': 'Big', 'bytes': b'x' * 1001}) + assert large.value.code == 'url_import_too_large' + + +def test_worker_uses_site_extractors_direct_connections_and_playable_formats(tmp_path): + video = fetch(tmp_path, {'title': 'A/B: test', 'duration': 12.5, 'webpage_url': 'https://www.example.com/v/1', + 'extractor_key': 'Example'}) + assert Path(video['path']).read_bytes() == b'video' and video['title'] == 'A/B: test' and video['site'] == 'Example' + options = FakeDownloader.options + assert options['allowed_extractors'] == ['default', '-generic'] and options['noplaylist'] is True and options['proxy'] == '' + assert options['external_downloader'] == {} + direct = "[protocol~='^https?$']" + assert all(choice.count(direct) == choice.count('+') + 1 for choice in options['format'].split('/')) + assert downloads.video_filename(video['title'], '.webm') == 'A B test.webm' + + +def answers(*addresses): + return lambda host, port, *args, **kwargs: [(socket.AF_INET6 if ':' in item else socket.AF_INET, socket.SOCK_STREAM, 6, '', + (item, port)) for item in addresses] + + +@pytest.mark.parametrize('addresses, allowed', [ + (('93.184.216.34',), True), + (('2606:2800:220:1:248:1893:25c8:1946',), True), + (('93.184.216.34', '10.0.0.5'), False), + (('127.0.0.1',), False), + (('169.254.169.254',), False), + (('100.64.0.1',), False), + (('::1',), False), + (('::ffff:192.168.1.10',), False), + (('fd00::1',), False), + (('64:ff9b::7f00:1',), False), + (('::127.0.0.1',), False), + (('224.0.0.1',), False), + ((), False), +]) +def test_resolver_guard_rejects_any_non_global_answer(addresses, allowed): + checked = download_worker.guard(answers(*addresses)) + if allowed: + assert checked('video.example', 443) + else: + with pytest.raises(OSError, match=download_worker.BLOCKED): + checked('video.example', 443) + + +def test_guarded_resolver_stops_a_host_agnostic_extractor_before_it_connects(tmp_path, monkeypatch): + yt_dlp = pytest.importorskip('yt_dlp') + hits = [] + + class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + hits.append(self.path) + self.send_response(200) + self.end_headers() + + do_POST = do_GET + + def log_message(self, *args): + pass + server = http.server.HTTPServer(('127.0.0.1', 0), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + resolve = socket.getaddrinfo + monkeypatch.setattr(socket, 'getaddrinfo', download_worker.guard( + lambda host, *args, **kwargs: resolve('127.0.0.1' if host == 'intranet.example' else host, *args, **kwargs))) + try: + url = f'http://intranet.example:{server.server_address[1]}/Mediasite/Play/0123456789abcdef0123456789abcdef1d' + assert downloads.validate_url(url) == url + with pytest.raises(download_worker.Rejected) as rejected: + download_worker.fetch({'url': url, 'folder': str(tmp_path), 'format': 'b', 'maxBytes': 10 ** 6, 'maxSeconds': 900}, + yt_dlp) + assert rejected.value.code == 'url_import_private' and hits == [] + finally: + server.shutdown() + + +def local_server(hits): + class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + hits.append(self.path) + body = (b'#EXTM3U\n#EXT-X-KEY:METHOD=AES-128,URI="/key"\n#EXTINF:2,\n/segment.ts\n#EXT-X-ENDLIST\n' + if self.path.endswith('.m3u8') else b'x' * 16) + self.send_response(200) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + server = http.server.HTTPServer(('127.0.0.1', 0), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + return server + + +@pytest.mark.parametrize('protocol', ['m3u8', 'm3u8_native', 'http_dash_segments', 'rtmp']) +def test_streamed_formats_are_never_selected_so_no_external_program_fetches(tmp_path, monkeypatch, protocol): + yt_dlp = pytest.importorskip('yt_dlp') + hits = [] + server = local_server(hits) + monkeypatch.setattr(socket, 'getaddrinfo', download_worker.guard(socket.getaddrinfo)) + base = f'http://127.0.0.1:{server.server_address[1]}' + info = {'id': 'stream', 'title': 'Stream', 'extractor': 'test', 'extractor_key': 'Test', 'webpage_url': 'https://www.example.com/v', + 'formats': [{'format_id': 'stream', 'url': f'{base}/m.m3u8', 'protocol': protocol, 'ext': 'mp4', + 'vcodec': 'avc1.64001f', 'acodec': 'mp4a.40.2', 'height': 720}]} + + class Offline(yt_dlp.YoutubeDL): + def extract_info(self, url, download=True, **kwargs): + return dict(info) + module = SimpleNamespace(YoutubeDL=Offline, utils=yt_dlp.utils) + try: + with pytest.raises(download_worker.Rejected) as rejected: + download_worker.fetch({'url': 'https://www.example.com/v', 'folder': str(tmp_path), 'format': downloads.download_format(), + 'maxBytes': 10 ** 6, 'maxSeconds': 900}, module) + assert rejected.value.code == 'url_import_unsupported' and hits == [] + info['formats'].append({'format_id': 'direct', 'url': f'{base}/v.mp4', 'protocol': 'http', 'ext': 'mp4', + 'vcodec': 'avc1.64001f', 'acodec': 'mp4a.40.2', 'height': 360}) + with pytest.raises(download_worker.Rejected) as blocked: + download_worker.fetch({'url': 'https://www.example.com/v', 'folder': str(tmp_path), 'format': downloads.download_format(), + 'maxBytes': 10 ** 6, 'maxSeconds': 900}, module) + assert blocked.value.code == 'url_import_private' and hits == [] + finally: + server.shutdown() + + +def test_a_section_result_is_refused_before_anything_downloads(tmp_path, monkeypatch): + yt_dlp = pytest.importorskip('yt_dlp') + hits = [] + server = local_server(hits) + monkeypatch.setattr(socket, 'getaddrinfo', download_worker.guard(socket.getaddrinfo)) + info = {'id': 'clip', 'title': 'Clip', 'extractor': 'test', 'extractor_key': 'Test', 'section_start': 1, 'section_end': 3, + 'formats': [{'format_id': 'direct', 'url': f'http://127.0.0.1:{server.server_address[1]}/v.mp4', 'protocol': 'http', + 'ext': 'mp4', 'vcodec': 'avc1.64001f', 'acodec': 'mp4a.40.2', 'height': 360}]} + + class Offline(yt_dlp.YoutubeDL): + def extract_info(self, url, download=True, **kwargs): + return dict(info) + try: + with pytest.raises(download_worker.Rejected) as rejected: + download_worker.fetch({'url': 'https://www.example.com/v', 'folder': str(tmp_path), 'format': downloads.download_format(), + 'maxBytes': 10 ** 6, 'maxSeconds': 900}, SimpleNamespace(YoutubeDL=Offline, utils=yt_dlp.utils)) + assert rejected.value.code == 'url_import_unsupported' and hits == [] + finally: + server.shutdown() + + +def test_confined_yt_dlp_starts_only_local_media_programs_and_no_external_downloader(monkeypatch): + yt_dlp = pytest.importorskip('yt_dlp') + external = pytest.importorskip('yt_dlp.downloader.external') + monkeypatch.setattr(subprocess.Popen, '__init__', subprocess.Popen.__init__) + monkeypatch.setattr(external.ExternalFD, 'real_download', external.ExternalFD.real_download) + download_worker.confine(yt_dlp) + for program in (['phantomjs', '--version'], ['/usr/bin/curl', 'http://127.0.0.1/'], ['aria2c'], ['rtmpdump']): + with pytest.raises(OSError, match=download_worker.BLOCKED_PROGRAM): + yt_dlp.utils.Popen(program) + with yt_dlp.utils.Popen(['ffprobe', '-version'], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) as probe: + assert probe.wait() == 0 + with yt_dlp.YoutubeDL({'quiet': True}) as client: + downloader = external.FFmpegFD(client, {}) + with pytest.raises(yt_dlp.utils.DownloadError, match=download_worker.BLOCKED_PROGRAM): + downloader.real_download('out.mp4', {'url': 'http://127.0.0.1/v.mp4', 'protocol': 'http'}) + + +@pytest.mark.skipif(sys.platform == 'win32', reason='POSIX process groups') +def test_killing_the_calling_process_group_also_ends_the_worker_and_its_children(tmp_path): + pids = tmp_path / 'pids' + worker = ('import pathlib, subprocess, sys, time; ' + 'from opendirector.media.download_worker import exit_with_parent; ' + 'sys.stdin.readline(); exit_with_parent(sys.stdin); ' + 'child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"]); ' + f'part = pathlib.Path({str(pids) + ".part"!r}); part.write_text(f"{{__import__(\'os\').getpid()}} {{child.pid}}"); ' + f'part.rename({str(pids)!r}); time.sleep(60)') + caller = ('import sys; from pathlib import Path; from opendirector.media import downloads; ' + f'downloads.WORKER = (sys.executable, "-c", {worker!r}); ' + f'downloads.download_video("https://www.example.com/v/1", Path({str(tmp_path)!r}))') + cli = subprocess.Popen([sys.executable, '-c', caller], start_new_session=True) + deadline = time.monotonic() + 20 + while not pids.exists() and time.monotonic() < deadline: + time.sleep(0.05) + started = [int(pid) for pid in pids.read_text().split()] + os.killpg(cli.pid, signal.SIGTERM) + assert cli.wait(timeout=10) == -signal.SIGTERM + + deadline = time.monotonic() + 5 + while any(map(alive, started)) and time.monotonic() < deadline: + time.sleep(0.05) + assert not any(map(alive, started)) + + +def alive(pid): + try: + return Path(f'/proc/{pid}/stat').read_text().split()[2] != 'Z' + except OSError: + return False + + +def worker_script(monkeypatch, body): + monkeypatch.setattr(downloads, 'WORKER', (sys.executable, '-c', body)) + + +def test_parent_kills_a_cancelled_worker_and_maps_its_results(monkeypatch, tmp_path): + worker_script(monkeypatch, 'import time; time.sleep(30)') + started = time.monotonic() + calls = iter([False, False, True]) + with pytest.raises(ProjectError) as cancelled: + downloads.download_video('https://www.example.com/v/1', tmp_path, cancelled=lambda: next(calls)) + assert cancelled.value.code == 'url_import_cancelled' and cancelled.value.status == 499 + assert time.monotonic() - started < 10 + worker_script(monkeypatch, 'import json; print(json.dumps({"code": "url_import_unavailable"}))') + with pytest.raises(ProjectError) as missing: + downloads.download_video('https://www.example.com/v/1', tmp_path) + assert missing.value.code == 'url_import_unavailable' and missing.value.status == 503 + worker_script(monkeypatch, 'print("not json")') + with pytest.raises(ProjectError) as broken: + downloads.download_video('https://www.example.com/v/1', tmp_path) + assert broken.value.code == 'url_import_failed' + target = tmp_path / 'source.webm' + worker_script(monkeypatch, 'import json, pathlib; pathlib.Path(%r).write_bytes(b"v"); print(json.dumps({"video": {"path": %r, ' + '"title": "Clip", "url": "https://www.example.com/v/1", "site": "Example", "duration": 2.0}}))' % (str(target), str(target))) + video = downloads.download_video('https://www.example.com/v/1', tmp_path) + assert video.path == target and video.title == 'Clip' and video.site == 'Example' + + +@pytest.mark.skipif(sys.platform == 'win32', reason='POSIX process groups') +def test_cancel_also_stops_processes_the_worker_started(monkeypatch, tmp_path): + marker = tmp_path / 'child.pid' + worker_script(monkeypatch, 'import pathlib, subprocess, sys, time; ' + f'child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"]); ' + f'part = pathlib.Path({str(marker) + ".part"!r}); part.write_text(str(child.pid)); ' + f'part.rename({str(marker)!r}); time.sleep(60)') + with pytest.raises(ProjectError) as cancelled: + downloads.download_video('https://www.example.com/v/1', tmp_path, cancelled=lambda: marker.exists()) + assert cancelled.value.code == 'url_import_cancelled' + child = int(marker.read_text()) + deadline = time.monotonic() + 5 + while alive(child) and time.monotonic() < deadline: + time.sleep(0.05) + assert not alive(child) + + +@pytest.mark.parametrize('encoding', ['cp936', 'cp1252']) +def test_non_ascii_titles_and_paths_survive_a_non_utf8_worker(monkeypatch, tmp_path, encoding): + pytest.importorskip('yt_dlp') + target = tmp_path / '中文目录 Café' / 'source.webm' + worker_script(monkeypatch, 'from opendirector.media import download_worker as worker; ' + f'worker.fetch = lambda request, yt_dlp: {{"path": {str(target)!r}, "title": "中文标题 Café", ' + '"url": "https://www.example.com/v/1", "site": "Example", "duration": 2.0}; worker.main()') + monkeypatch.setenv('PYTHONIOENCODING', encoding) + video = downloads.download_video('https://www.example.com/v/1', tmp_path) + assert video.title == '中文标题 Café' and video.path == target + + +def test_real_worker_reports_an_unsupported_site_without_a_network_request(tmp_path): + pytest.importorskip('yt_dlp') + with pytest.raises(ProjectError) as rejected: + downloads.download_video('https://www.example.com/not-a-video-site', tmp_path) + assert rejected.value.code == 'url_import_unsupported' + + +class FakeDownload: + def __init__(self, clip): + self.clip, self.calls, self.info = clip, [], {} + + def __call__(self, url, folder, *, cancelled=None): + url = downloads.validate_url(url) + if cancelled is not None and cancelled(): + raise downloads.rejection('url_import_cancelled') + if self.info.get('code'): + raise downloads.rejection(self.info['code'], self.info.get('detail', '')) + self.calls.append(url) + path = Path(folder) / 'source.mp4' + path.write_bytes(self.clip) + return downloads.DownloadedVideo(path=path, title='Reference clip', url=url, site='Example', duration=2.0) + + +@pytest.fixture +def fake_download(monkeypatch, clip): + fake = FakeDownload(clip) + monkeypatch.setattr(downloads, 'download_video', fake) + monkeypatch.setattr(creation_assets, 'download_video', fake) + return fake + + +def test_link_staging_registers_through_asset_import_and_does_not_download_twice(project, fake_download): + store, project_id, session = project + handle = uuid4() + assets = CreationAssets(store) + staged = assets.stage_url(project_id, handle, session, 'https://www.example.com/v/1') + assert staged.status == 'ready' and staged.kind == 'video' and staged.name == 'Reference clip.mp4' + again = assets.stage_url(project_id, handle, session, 'https://www.example.com/v/1') + assert again.fingerprint == staged.fingerprint and len(fake_download.calls) == 1 + with pytest.raises(ProjectError) as conflict: + assets.stage_url(project_id, handle, session, 'https://www.example.com/v/2') + assert conflict.value.code == 'url_import_handle_conflict' and conflict.value.status == 409 + assert len(fake_download.calls) == 1 + receipt = assets.execute(parse_command(dict(commandId=uuid4(), projectId=project_id, type='asset.import', + payload=dict(uploadHandle=handle, name=staged.name, expectedKind='video'))), session=session) + assert receipt.status == 'applied' + asset = next(item for item in store.snapshot(project_id).assets if item.kind == 'video') + assert asset.name == 'Reference clip.mp4' and asset.provenance.source == 'upload' + + +def test_cancelled_download_stages_nothing(project, fake_download): + store, project_id, session = project + handle = uuid4() + assets = CreationAssets(store) + with pytest.raises(ProjectError) as cancelled: + assets.stage_url(project_id, handle, session, 'https://www.example.com/v/1', cancelled=lambda: True) + assert cancelled.value.code == 'url_import_cancelled' and fake_download.calls == [] + assert assets.uploads.owner(project_id, handle, session) is None and store.snapshot(project_id).assets == () + + +@pytest.mark.parametrize('cancel_at', [3, 7]) +def test_cancelling_while_staging_leaves_no_staged_copy(monkeypatch, project, fake_download, clip, cancel_at): + store, project_id, session = project + handle = uuid4() + assets = CreationAssets(store) + monkeypatch.setattr(creation_assets, 'CHUNK_BYTES', len(clip) // 4 + 1) + checks = [] + + def cancelled(): + checks.append(1) + return len(checks) >= cancel_at + with pytest.raises(ProjectError) as stopped: + assets.stage_url(project_id, handle, session, 'https://www.example.com/v/1', cancelled=cancelled) + assert stopped.value.code == 'url_import_cancelled' and len(checks) >= cancel_at + assert assets.uploads.info(project_id, handle, session).status == 'cancelled' + folder = upload_directory(assets.uploads.projects.state_dir, UUID(project_id), handle) + assert sorted(path.name for path in folder.iterdir()) == ['owner.json'] + assert store.snapshot(project_id).assets == () + + +def test_a_cancelled_handle_is_refused_before_downloading(project, fake_download): + store, project_id, session = project + handle = uuid4() + assets = CreationAssets(store) + assets.uploads.begin(project_id, handle, session, 'old.mp4', expected_kind='video', source_url='https://www.example.com/v/1').abort() + assets.uploads.cancel(project_id, handle, session) + with pytest.raises(ProjectError) as refused: + assets.stage_url(project_id, handle, session, 'https://www.example.com/v/1') + assert refused.value.code == 'url_import_handle_conflict' and refused.value.status == 409 and fake_download.calls == [] + + +@pytest.mark.parametrize('language, private, failed', [ + ('en-US', 'Videos cannot be downloaded from this computer or the local network.', + 'Could not download the video from this link. [site] 1: HTTP Error 412'), + ('zh-CN', '不能从本机或局域网地址下载视频。', '无法从该链接下载视频:[site] 1: HTTP Error 412'), +]) +def test_cli_errors_follow_the_cli_language(monkeypatch, capsys, language, private, failed, fake_download): + monkeypatch.setenv('OPENDIRECTOR_LANGUAGE', language) + monkeypatch.delenv('OPENDIRECTOR_AGENT_SOCKET', raising=False) + monkeypatch.setattr(sys, 'argv', ['opendirector', '--project', str(uuid4()), 'asset', 'import-url', 'http://192.168.1.10/v']) + with pytest.raises(SystemExit): + cli.main() + assert json.loads(capsys.readouterr().out) == {'error': private, 'code': 'url_import_private'} + fake_download.info = {'code': 'url_import_failed', 'detail': '[site] 1: HTTP Error 412'} + monkeypatch.setattr(cli.Client, 'request', lambda self, *args, **kwargs: {}) + monkeypatch.setattr(cli.httpx.Client, 'get', lambda self, *args, **kwargs: httpx.Response(404)) + monkeypatch.setattr(sys, 'argv', ['opendirector', '--project', str(uuid4()), 'asset', 'import-url', 'https://www.example.com/v/2']) + with pytest.raises(SystemExit): + cli.main() + assert json.loads(capsys.readouterr().out) == {'error': failed, 'code': 'url_import_failed'} + + +def test_link_staging_route_localizes_rejections_and_registers_nothing(tmp_path, fake_download): + local = LocalProjects(tmp_path) + projects = CreationProjects(local) + project, session = uuid4(), str(uuid4()) + projects.execute(parse_command(dict(type='project.create', projectId=project, commandId=uuid4(), payload=dict(name='Link')))) + projects.open(project, session) + api = TestClient(create_app(local)) + headers = {'X-OpenDirector-Request': '1', 'X-OpenDirector-Session': session} + fake_download.info = {'code': 'url_import_playlist'} + path = f'/api/creation/projects/{project}/uploads/{uuid4()}/url' + english = api.put(path, headers={**headers, 'Accept-Language': 'en-US'}, json={'url': 'https://www.example.com/list'}) + assert english.status_code == 422 and english.json()['detail'].startswith('This link is a playlist') + chinese = api.put(path, headers={**headers, 'Accept-Language': 'zh-CN'}, json={'url': 'https://www.example.com/list'}) + assert chinese.status_code == 422 and '播放列表' in chinese.json()['detail'] + private = api.put(path, headers={**headers, 'Accept-Language': 'en-US'}, json={'url': 'http://127.0.0.1/v'}) + assert private.status_code == 422 and 'local network' in private.json()['detail'] + fake_download.info = {'code': 'url_import_failed', 'detail': '[site] 1: HTTP Error 412: Precondition Failed'} + blocked = api.put(path, headers={**headers, 'Accept-Language': 'en-US'}, json={'url': 'https://www.example.com/v/2'}) + assert blocked.json()['detail'] == 'Could not download the video from this link. [site] 1: HTTP Error 412: Precondition Failed' + assert projects.snapshot(project).assets == () + + +@pytest.fixture(params=['http', 'live'], ids=['http-testclient', 'live-bridge']) +def link_cli(request, tmp_path, monkeypatch, fake_download): + local = LocalProjects(tmp_path / 'data') + projects = CreationProjects(local) + project, turn = uuid4(), uuid4() + projects.execute(parse_command(dict(type='project.create', projectId=project, commandId=uuid4(), payload=dict(name='CLI')))) + api = TestClient(create_app(local)) + original = httpx.Client + + def forward(req): + response = api.request(req.method, req.url.path, headers=dict(req.headers), content=req.read()) + return httpx.Response(response.status_code, headers=response.headers, content=response.content) + monkeypatch.setattr(cli.httpx, 'Client', lambda **kwargs: original(**kwargs, transport=httpx.MockTransport(forward))) + if request.param == 'live': + session = str(uuid4()) + projects.open(project, session) + business = AgentTools(projects, None, ModelConfigs(local.repository)) + work = tmp_path / 'work' + work.mkdir() + monkeypatch.chdir(work) + monkeypatch.setenv('OPENDIRECTOR_AGENT_SOCKET', 'in-process-test') + + def call(self, name, arguments, *, identity=None): + return asyncio.run(business.execute(project, turn, session, str(identity or uuid4()), name, arguments, + roots=[], config=None, native_runtime='codex', execution_directory=work)) + monkeypatch.setattr(cli.Client, 'call', call) + else: + monkeypatch.delenv('OPENDIRECTOR_AGENT_SOCKET', raising=False) + monkeypatch.delenv('OPENDIRECTOR_AGENT_HOST', raising=False) + runner = CliRunner() + + def invoke(args, status=0): + result = runner.invoke(cli.app, ['--project', str(project), *args]) + assert result.exit_code == status, (result.output, result.exception) + return json.loads(result.output) + yield invoke, runner, projects, project, request.param, fake_download + + +def test_cli_imports_a_link_as_a_video_asset_and_replays_by_operation(link_cli): + invoke, runner, projects, project, transport, fake = link_cli + operation = str(uuid4()) + imported = invoke(['--operation-id', operation, 'asset', 'import-url', 'https://www.example.com/v/1']) + assert imported['status'] == 'applied' and imported['source']['title'] == 'Reference clip' + assert ('file' in imported) == (transport == 'live') + asset = next(item for item in projects.snapshot(project).assets if str(item.id) == imported['assetId']) + assert asset.kind == 'video' and asset.name == 'Reference clip.mp4' + replayed = invoke(['--operation-id', operation, 'asset', 'import-url', 'https://www.example.com/v/1']) + assert replayed['assetId'] == imported['assetId'] and len(projects.snapshot(project).assets) == 1 + assert len(fake.calls) == 1 + result = runner.invoke(cli.app, ['--project', str(project), '--operation-id', operation, 'asset', 'import-url', + 'https://www.example.com/v/2']) + assert isinstance(result.exception, ProjectError) and result.exception.code == 'url_import_operation_conflict' + assert len(fake.calls) == 1 and len(projects.snapshot(project).assets) == 1 + shown = invoke(['canvas', 'add-material', '--asset', imported['assetId'], '--x', '0', '--y', '0']) + item = next(item for item in projects.snapshot(project).canvasItems if str(item.id) == shown['itemId']) + assert item.kind == 'video' and str(item.binding.objectRef.assetId) == imported['assetId'] + + +def test_cli_rejects_a_private_link_before_any_download(link_cli): + _, runner, projects, project, _, fake = link_cli + result = runner.invoke(cli.app, ['--project', str(project), 'asset', 'import-url', 'http://127.0.0.1:8000/v']) + assert isinstance(result.exception, ProjectError) and result.exception.code == 'url_import_private' + assert fake.calls == [] and projects.snapshot(project).assets == () From ed472ab756401a6efca651011aa995498fbb24e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=AA=E5=BF=97=E9=B9=8F?= Date: Wed, 2 Dec 2026 04:52:35 +0000 Subject: [PATCH 2/2] [feat] canvas: do not place a link import cancelled after registration MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cancelling the link dialog while the registration receipt or the asset lookup was still pending closed the dialog, but the node could still be added to the same canvas afterwards. Check the cancel signal right before the canvas command; a video registered before the cancel stays in the asset library and the toast says so. Signed-off-by: 汪志鹏 Co-Authored-By: Claude Opus 5.5 --- docs/guides/user-guide.md | 2 +- docs/guides/user-guide.zh-CN.md | 2 +- src/canvas/workspace/linkImport.ts | 20 ++++++ src/canvas/workspace/useWorkspaceTransfer.ts | 35 +++++----- src/i18n/messages/en-US/canvas.ts | 1 + src/i18n/messages/zh-CN/canvas.ts | 1 + tests/creationClient.test.ts | 69 ++++++++++++++++++++ 7 files changed, 113 insertions(+), 17 deletions(-) create mode 100644 src/canvas/workspace/linkImport.ts diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md index 7da2bc554..08003dff7 100644 --- a/docs/guides/user-guide.md +++ b/docs/guides/user-guide.md @@ -224,7 +224,7 @@ For a local edit, mark an area or create a selection first, then enter your inst Right-click the canvas, choose **New node → Import video from link**, and paste the page of a single video. OpenDirector downloads it on the computer that runs the app, registers it as a video asset and adds it as a video node, ready for references, trimming or other video tools. - One video page on a supported site, up to 15 minutes and 512 MB. Playlists, live streams and videos offered only as segmented streams (HLS/DASH) are not supported. Every connection the download makes, including redirects and media servers, must go to a public internet address; this computer and the local network are refused. Link import connects directly, without the system proxy. -- Cancel stops the download and registers nothing; if registration had already finished, the video is still added. +- Cancel stops the download and registers nothing. If the video was already registered when you cancelled, Cancel only stops it from being placed: the asset stays in the asset library and is not removed. - Which sites work depends on the yt-dlp downloader. Some sites block downloads from servers or data centres, and some (such as YouTube) may need extra yt-dlp components. If the import fails, download the file yourself and use **Upload**. - Import only videos you have the right to use. The asset is named after the page title; the link itself is not stored in the project. diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md index 6372ffd9e..24f6d7fe4 100644 --- a/docs/guides/user-guide.zh-CN.md +++ b/docs/guides/user-guide.zh-CN.md @@ -224,7 +224,7 @@ Codex 网页检索引用在具有匹配来源时显示为编号链接;复制 右键画布,选择 **新建节点 → 从链接导入视频**,粘贴单个视频的网页链接。OpenDirector 在运行应用的电脑上下载视频,登记为视频素材并添加为视频节点,之后可作参考、修剪或使用其他视频工具。 - 支持常见视频网站的单个视频页面,最长 15 分钟、512 MB。不支持播放列表、直播以及只以分片流(HLS/DASH)提供的视频。下载过程中的每个连接(包括跳转和媒体服务器)都必须指向公网地址,本机或局域网地址会被拒绝;链接导入直接连接,不使用系统代理。 -- 点击「取消」会停止下载,不登记素材;如果取消时素材已经登记完成,视频仍会添加到画布上。 +- 点击「取消」会停止下载,不登记素材。如果取消时素材已经登记完成,取消只会阻止它被放到画布上:素材保留在资产库中,不会被删除。 - 可用站点取决于 yt-dlp 下载组件:部分网站会拦截服务器或机房的下载,部分网站(如 YouTube)可能需要额外的 yt-dlp 组件。导入失败时,可自行下载后使用 **上传**。 - 请只导入你有权使用的视频。素材以网页标题命名,工程中不保存链接本身。 diff --git a/src/canvas/workspace/linkImport.ts b/src/canvas/workspace/linkImport.ts new file mode 100644 index 000000000..803567350 --- /dev/null +++ b/src/canvas/workspace/linkImport.ts @@ -0,0 +1,20 @@ +export type LinkImportOutcome = { + status: "placed" | "cancelled" | "switched"; + resource: Resource; +}; + +export async function importLinkedVideo( + signal: AbortSignal | undefined, + steps: { + register: () => Promise; + resolve: (ref: Ref) => Promise; + sameDocument: () => boolean; + place: (resource: Resource) => void; + }, +): Promise> { + const resource = await steps.resolve(await steps.register()); + if (!steps.sameDocument()) return { status: "switched", resource }; + if (signal?.aborted) return { status: "cancelled", resource }; + steps.place(resource); + return { status: "placed", resource }; +} diff --git a/src/canvas/workspace/useWorkspaceTransfer.ts b/src/canvas/workspace/useWorkspaceTransfer.ts index 581b66f7b..108804f93 100644 --- a/src/canvas/workspace/useWorkspaceTransfer.ts +++ b/src/canvas/workspace/useWorkspaceTransfer.ts @@ -49,6 +49,7 @@ import { } from "../subjectLibraryImport.ts"; import { subjectWithResource, type SubjectMediaSlot } from "../subjectMedia.ts"; import { importedNodeIds, uploadPickerPlan, uploadTargetUnchanged } from "./entryPoints.ts"; +import { importLinkedVideo } from "./linkImport.ts"; import { assertUpload } from "../uploadPolicy.ts"; import { prefetchLibrary } from "../library/libraryPrefetch"; @@ -127,21 +128,25 @@ export function useWorkspaceTransfer(rt: WorkspaceRuntime, readOnly: boolean) { const importUrl = async (url: string, point?: Point, signal?: AbortSignal) => { const documentId = historyRef.current.present.id; - const ref = await creationClient(documentId).importUrl(url, crypto.randomUUID(), signal); - const resource = await workspaceProjection(documentId).resource(ref); - if (historyRef.current.present.id !== documentId) { - notify(t("canvas.workspace.toast.importCancelledSwitched")); - return; - } - const where = point ?? center(); - const node = createNode( - resource.kind, - { x: where.x - 176, y: where.y - 130 }, - resourceNodeData(resource), - ); - command({ type: "add-nodes", nodes: [node] }); - setSelected([node.id]); - notify(t("canvas.linkImport.done", { title: resource.title })); + const outcome = await importLinkedVideo(signal, { + register: () => creationClient(documentId).importUrl(url, crypto.randomUUID(), signal), + resolve: (ref) => workspaceProjection(documentId).resource(ref), + sameDocument: () => historyRef.current.present.id === documentId, + place: (resource) => { + const where = point ?? center(); + const node = createNode( + resource.kind, + { x: where.x - 176, y: where.y - 130 }, + resourceNodeData(resource), + ); + command({ type: "add-nodes", nodes: [node] }); + setSelected([node.id]); + }, + }); + const title = outcome.resource.title; + if (outcome.status === "switched") notify(t("canvas.workspace.toast.importCancelledSwitched")); + else if (outcome.status === "cancelled") notify(t("canvas.linkImport.cancelledRegistered", { title })); + else notify(t("canvas.linkImport.done", { title })); }; const insertLibraryItems = async (items: LibraryItem[]) => { diff --git a/src/i18n/messages/en-US/canvas.ts b/src/i18n/messages/en-US/canvas.ts index d8ba702a6..7611846e3 100644 --- a/src/i18n/messages/en-US/canvas.ts +++ b/src/i18n/messages/en-US/canvas.ts @@ -28,6 +28,7 @@ export const canvas = { "canvas.linkImport.importing": "Importing…", "canvas.linkImport.submit": "Import", "canvas.linkImport.done": "Imported “{title}”.", + "canvas.linkImport.cancelledRegistered": "Placement cancelled: “{title}” was registered before you cancelled. It is in the asset library and was not added to the canvas.", "canvas.menu.paste": "Paste", "canvas.menu.redo": "Redo", "canvas.menu.undo": "Undo", diff --git a/src/i18n/messages/zh-CN/canvas.ts b/src/i18n/messages/zh-CN/canvas.ts index 17f8080f5..5b01e7ca4 100644 --- a/src/i18n/messages/zh-CN/canvas.ts +++ b/src/i18n/messages/zh-CN/canvas.ts @@ -28,6 +28,7 @@ export const canvas = { "canvas.linkImport.importing": "正在导入…", "canvas.linkImport.submit": "导入", "canvas.linkImport.done": "已导入「{title}」。", + "canvas.linkImport.cancelledRegistered": "已取消放置:「{title}」在取消前已登记为素材,可在资产库中找到,未添加到画布。", "canvas.menu.paste": "粘贴", "canvas.menu.redo": "重做", "canvas.menu.undo": "撤销", diff --git a/tests/creationClient.test.ts b/tests/creationClient.test.ts index 7d7b62637..60af97ec4 100644 --- a/tests/creationClient.test.ts +++ b/tests/creationClient.test.ts @@ -20,6 +20,7 @@ import { } from "../src/backend/creationClient.ts"; import { CreationProjection } from "../src/backend/creationProjection.ts"; import { createDocument, createNode } from "../src/canvas/model.ts"; +import { importLinkedVideo } from "../src/canvas/workspace/linkImport.ts"; function empty(): ProjectSnapshot { return { @@ -1950,3 +1951,71 @@ test("a link import stages on the server, registers once, and a cancelled one is globalThis.fetch = original; } }); + +test("cancelling a link import while its registration receipt is pending keeps the asset but places no node", async () => { + const snapshot = empty(), client = new CreationClient(snapshot.project.id); + client.install(snapshot); + const registered: string[] = []; + const held: { receipt?: () => void } = {}; + Object.assign(client, { + registerUpload: (handle: string, name: string, kind: string) => + new Promise((resolve) => { + held.receipt = () => { + registered.push(handle); + resolve({ assetId: handle, revision: 1, fingerprint: "sha256:x", kind }); + }; + }), + }); + const original = globalThis.fetch; + const calls: { url: string; method: string }[] = []; + globalThis.fetch = async (input, options) => { + calls.push({ url: String(input), method: options?.method ?? "GET" }); + return String(input).endsWith("/url") ? Response.json({ name: "Clip.webm", kind: "video" }) : Response.json({}); + }; + const placed: string[] = []; + const steps = (signal: AbortSignal, onResolve: () => void = () => undefined) => ({ + register: () => client.importUrl("https://example.com/v/1", crypto.randomUUID(), signal), + resolve: async (ref: { assetId: string }) => { + onResolve(); + return { title: "Clip", assetId: ref.assetId }; + }, + sameDocument: () => true, + place: (resource: { assetId: string }) => placed.push(resource.assetId), + }); + const settle = async (before: () => void = () => undefined) => { + while (!held.receipt) await new Promise((resolve) => setTimeout(resolve, 0)); + const release = held.receipt; + held.receipt = undefined; + before(); + release(); + }; + try { + const waiting = new AbortController(); + const pending = importLinkedVideo(waiting.signal, steps(waiting.signal)); + await settle(() => waiting.abort()); + const outcome = await pending; + assert.equal(outcome.status, "cancelled"); + assert.deepEqual(placed, []); + assert.equal(registered.length, 1); + assert.ok(!calls.some((call) => call.method === "DELETE")); + + const resolving = new AbortController(); + const second = importLinkedVideo(resolving.signal, steps(resolving.signal, () => resolving.abort())); + await settle(); + assert.equal((await second).status, "cancelled"); + assert.deepEqual(placed, []); + + const kept = new AbortController(); + const third = importLinkedVideo(kept.signal, steps(kept.signal)); + await settle(); + assert.equal((await third).status, "placed"); + assert.deepEqual(placed, [registered[2]]); + + const switched = importLinkedVideo(kept.signal, { ...steps(kept.signal), sameDocument: () => false }); + await settle(); + assert.equal((await switched).status, "switched"); + assert.equal(placed.length, 1); + } finally { + globalThis.fetch = original; + } +});