Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
157 changes: 124 additions & 33 deletions src/scenes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,82 @@ fn clip_entered_error(asset: &FlowAsset, before: &HashMap<String, ClipBaseline>)
}
}

/// Validates that each entry in `asset_ids` is non-empty and does not name a non-video asset or collection.
fn validate_video_asset_ids(snap: &Value, asset_ids: &[String]) -> Result<Vec<String>> {
let collections = snap
.get("collections")
.and_then(Value::as_array)
.map(Vec::as_slice)
.unwrap_or(&[]);
let assets = snap
.get("assets")
.and_then(Value::as_array)
.map(Vec::as_slice)
.unwrap_or(&[]);
let mut cleaned = Vec::with_capacity(asset_ids.len());
for raw_id in asset_ids {
let id = raw_id.trim();
anyhow::ensure!(!id.is_empty(), "Video asset ID must not be empty");
if collections
.iter()
.any(|c| c.get("id").and_then(Value::as_str) == Some(id))
{
anyhow::bail!("Asset '{id}' is a collection, expected a video asset");
}
if let Some(found) = assets
.iter()
.find(|a| a.get("id").and_then(Value::as_str) == Some(id))
{
let kind = found
.get("kind")
.and_then(Value::as_str)
.unwrap_or("unknown");
anyhow::ensure!(
kind == "video",
"Asset '{id}' has kind '{kind}', expected 'video'"
);
}
cleaned.push(id.to_string());
}
Ok(cleaned)
}

/// Validates that `scene_id` names a live scene in `snap`.
fn validate_scene_target_id(snap: &Value, raw_scene_id: &str) -> Result<String> {
let scene_id = raw_scene_id.trim();
anyhow::ensure!(!scene_id.is_empty(), "Scene ID must not be empty");
if snap
.get("collections")
.and_then(Value::as_array)
.is_some_and(|cols| {
cols.iter()
.any(|c| c.get("id").and_then(Value::as_str) == Some(scene_id))
})
{
anyhow::bail!("Target '{scene_id}' is a collection, expected a scene");
}
let Some(found) = snap
.get("assets")
.and_then(Value::as_array)
.and_then(|assets| {
assets
.iter()
.find(|a| a.get("id").and_then(Value::as_str) == Some(scene_id))
})
else {
anyhow::bail!("Scene '{scene_id}' does not exist in the active project");
};
let kind = found
.get("kind")
.and_then(Value::as_str)
.unwrap_or("unknown");
anyhow::ensure!(
kind == "scene",
"Target '{scene_id}' has kind '{kind}', expected 'scene'"
);
Ok(scene_id.to_string())
}

/// Parameters for `flow_scenes`.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
pub(crate) struct ScenesParams {
Expand Down Expand Up @@ -190,44 +266,51 @@ pub(crate) async fn handle_scenes(
Ok(json!({ "count": scenes.len(), "scenes": scenes }))
}
"create" => {
let asset_ids = req.asset_ids.unwrap_or_default();
let _ = read_snapshot(engine).await?;
let raw_asset_ids = req.asset_ids.unwrap_or_default();
let snap = read_snapshot(engine).await?;
let asset_ids = validate_video_asset_ids(&snap, &raw_asset_ids)?;
let payload = json!({
"action": "create",
"asset_ids": asset_ids,
"name": req.name,
});
let res = engine.call_flow_async("sceneOp", json!([payload])).await?;
if res.get("ok").and_then(|v| v.as_bool()) != Some(true) {
if res.get("ok").and_then(Value::as_bool) != Some(true)
|| res.get("confirmed").and_then(Value::as_bool) != Some(true)
{
anyhow::bail!(
"Failed to create scene: {}",
res.get("error")
.and_then(|v| v.as_str())
.unwrap_or("unknown")
.and_then(Value::as_str)
.unwrap_or("scene clips not confirmed")
);
}
Ok(res)
}
"add_clips" => {
let scene_id = req.id.context("flow_scenes add_clips requires 'id'")?;
let asset_ids = req
let raw_scene_id = req.id.context("flow_scenes add_clips requires 'id'")?;
let raw_asset_ids = req
.asset_ids
.filter(|v| !v.is_empty())
.context("flow_scenes add_clips requires non-empty 'asset_ids'")?;
let _ = read_snapshot(engine).await?;
let snap = read_snapshot(engine).await?;
let scene_id = validate_scene_target_id(&snap, &raw_scene_id)?;
let asset_ids = validate_video_asset_ids(&snap, &raw_asset_ids)?;
let payload = json!({
"action": "add_clips",
"scene_id": scene_id,
"asset_ids": asset_ids,
"position": req.position,
});
let res = engine.call_flow_async("sceneOp", json!([payload])).await?;
if res.get("ok").and_then(|v| v.as_bool()) != Some(true) {
if res.get("ok").and_then(Value::as_bool) != Some(true)
|| res.get("confirmed").and_then(Value::as_bool) != Some(true)
{
anyhow::bail!(
"Failed to add clips to scene: {}",
res.get("error")
.and_then(|v| v.as_str())
.unwrap_or("unknown")
.and_then(Value::as_str)
.unwrap_or("scene clips not confirmed")
);
}
Ok(res)
Expand Down Expand Up @@ -320,7 +403,7 @@ pub(crate) async fn run_video_extend(
if let Some(nav_url) = res.get("need_navigate").and_then(|v| v.as_str()) {
engine.navigate(nav_url).await?;
tokio::time::sleep(Duration::from_millis(1200)).await;
let _ = ensure_flow_store(engine).await;
let _ = read_snapshot(engine).await;
let retry_payload = json!({
"action": "prepare_extend",
"asset_id": target.id,
Expand Down Expand Up @@ -379,7 +462,14 @@ pub(crate) async fn run_video_extend(
on_progress("extending video...".to_string());
}

if let Ok(cur_snap) = list_assets_with_project(engine).await {
let cur_snap = match list_assets_with_project(engine).await {
Ok(snap_ok) => Some(snap_ok),
Err(_) => {
let _ = ensure_flow_store(engine).await;
list_assets_with_project(engine).await.ok()
}
};
if let Some(cur_snap) = cur_snap {
for asset in &cur_snap.assets {
if asset.kind == "video"
&& !clip_is_failed(asset)
Expand All @@ -406,26 +496,27 @@ pub(crate) async fn run_video_extend(
));
break;
}
if !extending {
let fresh: Vec<FlowAsset> = cur_snap
.assets
.iter()
.filter(|a| {
a.kind == "video"
&& a.url.is_some()
&& before.get(&a.id).is_none_or(|prior| {
a.primary_media_id.as_deref().map_or_else(
|| a.url != prior.url,
|media_id| prior.primary_media_id.as_deref() != Some(media_id),
)
})
})
.cloned()
.collect();
if !fresh.is_empty() {
new_assets = fresh;
break;
}
let fresh: Vec<FlowAsset> = cur_snap
.assets
.iter()
.filter(|a| {
a.kind == "video"
&& !clip_is_failed(a)
&& !matches!(a.media_status.as_deref(), Some("pending" | "scheduled"))
&& a.url.is_some()
&& (!extending || a.media_status.as_deref() == Some("success"))
&& before.get(&a.id).is_none_or(|prior| {
a.primary_media_id.as_deref().map_or_else(
|| !extending && a.url != prior.url,
|media_id| prior.primary_media_id.as_deref() != Some(media_id),
)
})
})
.cloned()
.collect();
if !fresh.is_empty() {
new_assets = fresh;
break;
}
}
if Instant::now() >= deadline {
Expand Down
113 changes: 108 additions & 5 deletions ts/angular.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,17 @@

import {
characterLookMedia,
collectionIdOf,
delay,
elText,
fifeBase,
isTrashedTile,
legacyTile,
normalizeFlowMediaUrl,
parentCollectionId,
readMediaUrl,
} from "./dom";
import { frontendBuild, readBuildLabel } from "./frontend_builds";
import { frontendBuild, readBuildLabel, snapshotFormat } from "./frontend_builds";
import { runtimeState } from "./state";
import type { AngularRouter, FlowStoreHandle, FlowTile, NgLView } from "./types";

Expand Down Expand Up @@ -431,13 +435,112 @@ function sceneIds(tiles: Map<string, FlowTile> | null | undefined): string[] {
tile.type === "SCENE" && !tile.isPending ? [String(tile.id ?? id)] : []);
}

/** Finds and normalizes the first clip tile that `workflowIds` names in `tiles`. */
function findFirstClipTile(
tiles: Map<string, FlowTile> | null | undefined,
workflowIds: string[],
): FlowTile | null {
const firstId = workflowIds[0]?.trim();
if (!firstId || !(tiles instanceof Map)) return null;
const direct = tiles.get(firstId);
if (direct && !isTrashedTile(direct)) {
return legacyTile(direct) ?? null;
}
for (const tile of tiles.values()) {
if (!tile || isTrashedTile(tile)) continue;
if (String(tile.id ?? "") === firstId || String(tile.workflowId ?? "") === firstId) {
return legacyTile(tile) ?? null;
}
}
return null;
}

/** Derives a float width-to-height aspect ratio (`0.5625` for `9:16`, `16/9` for `16:9` or empty scenes). */
function deriveSceneAspectRatio(firstTile: FlowTile | null): number {
if (!firstTile) return 16 / 9;
const candidates = [
firstTile.Kb?.aspectRatio,
firstTile.Fb?.aspectRatio,
firstTile.aspectRatio,
];
let ratio = candidates.find(
(v): v is number => typeof v === "number" && Number.isFinite(v) && v > 0,
);
if (ratio === undefined) {
const width =
firstTile.Fb?.tc?.width ??
firstTile.tc?.width ??
firstTile.Fb?.width ??
firstTile.width;
const height =
firstTile.Fb?.tc?.height ??
firstTile.tc?.height ??
firstTile.Fb?.height ??
firstTile.height;
if (
typeof width === "number" &&
Number.isFinite(width) &&
width > 0 &&
typeof height === "number" &&
Number.isFinite(height) &&
height > 0
) {
ratio = width / height;
}
}
return ratio !== undefined && ratio < 1 ? 0.5625 : 16 / 9;
}

/** Derives the parent collection ID for a new scene from clip `0` or the active `/collection/<cid>` route. */
function deriveSceneCollectionId(
tiles: Map<string, FlowTile> | null | undefined,
firstTile: FlowTile | null,
): string | undefined {
const collectionType = snapshotFormat()?.tileTypes.collection ?? "COLLECTION";
const collectionIds = new Set<string>();
if (tiles instanceof Map) {
for (const [id, rawTile] of tiles.entries()) {
if (
rawTile &&
!isTrashedTile(rawTile) &&
String(rawTile.type ?? "").toUpperCase() === collectionType
) {
collectionIds.add(String(rawTile.id ?? id));
}
}
}
const isCollectionId = (id: string): boolean => collectionIds.has(id);
const fromTile = collectionIdOf(firstTile, isCollectionId);
if (fromTile) return fromTile;
const directParent = firstTile ? parentCollectionId(firstTile) : null;
if (directParent && (!(tiles instanceof Map) || !tiles.has(directParent) || collectionIds.has(directParent))) {
return directParent;
}
const routeMatch = /\/project\/[^/?#]+\/collection\/([^/?#]+)/.exec(location.pathname || "");
if (routeMatch?.[1]) {
try {
const routeCid = decodeURIComponent(routeMatch[1]).trim();
if (routeCid && (!(tiles instanceof Map) || !tiles.has(routeCid) || collectionIds.has(routeCid))) {
return routeCid;
}
} catch {
// Ignore malformed URI components in location.pathname.
}
}
return undefined;
}

/** Creates a scene and waits for its ID from Flow. */
export async function createScene(
helper: FlowStoreHandle,
getMap: () => Map<string, FlowTile> | null | undefined,
workflowIds: string[],
): Promise<{ ok: boolean; id?: string; error?: string }> {
const before = new Set(sceneIds(getMap()));
const initialMap = getMap();
const before = new Set(sceneIds(initialMap));
const firstClip = findFirstClipTile(initialMap, workflowIds);
const aspectRatio = deriveSceneAspectRatio(firstClip);
const collectionId = deriveSceneCollectionId(initialMap, firstClip);
const resultField = frontendBuild(readBuildLabel())?.projectStore.mutations?.sceneCreated ?? "VWa";
let confirmedId: string | undefined;
let failure: string | undefined;
Expand All @@ -451,9 +554,9 @@ export async function createScene(
void Promise.resolve().then(() => helper.mutate({
type: "create_scene",
rg: workflowIds,
Fc: undefined,
wc: undefined,
aspectRatio: 1,
Fc: collectionId,
wc: collectionId,
aspectRatio,
De: completion,
ve: completion,
})).then((response) => {
Expand Down
8 changes: 7 additions & 1 deletion ts/project_store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,10 +342,16 @@ export function findProjectStoreInView(

for (const slot of view) {
consider(slot);
if (!slot || typeof slot !== "object" || slot instanceof Node) continue;
if (!slot || typeof slot !== "object" || slot instanceof Node || Array.isArray(slot) || slot instanceof Map) {
continue;
}
for (const key of format.componentSlots) {
consider(Object.getOwnPropertyDescriptor(slot, key)?.value);
}
const ownKeys = Object.getOwnPropertyNames(slot);
for (let i = 0; i < ownKeys.length && i < 48; i += 1) {
consider(Object.getOwnPropertyDescriptor(slot, ownKeys[i])?.value);
}
}
return matches;
}
Expand Down
Loading
Loading