Skip to content

utils

Create an entity link via AYON REST API.

Create a link between two folders (input and output) with the specified link type. Multiple links with the same input/output/type are allowed (e.g., for multi-occurence casting).

Parameters:

Name Type Description Default
project_name str

AYON project name.

required
user UserEntity

User entity for authentication.

required
ayon_server_url str

Base URL of the AYON server.

required
input_id str

AYON folder ID of the link input (source).

required
output_id str

AYON folder ID of the link output (target).

required
link_type str

Link type identifier in format "name|input_type|output_type" (e.g., "breakdown|folder|folder").

required
data dict[str, Any] | None

Optional dictionary containing link metadata (e.g., kitsuAssetId, kitsuTargetId, occurence).

None

Returns:

Type Description
str | None

Created link ID string if successful, None otherwise. Warnings

str | None

on failure.

Source code in server/kitsu/utils.py
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
async def create_entity_link(
    project_name: str,
    user: "UserEntity",
    ayon_server_url: str,
    input_id: str,
    output_id: str,
    link_type: str,
    data: dict[str, Any] | None = None,
) -> str | None:
    """Create an entity link via AYON REST API.

    Create a link between two folders (input and output) with the specified
    link type. Multiple links with the same input/output/type are allowed
    (e.g., for multi-occurence casting).

    Args:
        project_name: AYON project name.
        user: User entity for authentication.
        ayon_server_url: Base URL of the AYON server.
        input_id: AYON folder ID of the link input (source).
        output_id: AYON folder ID of the link output (target).
        link_type: Link type identifier in format "name|input_type|output_type"
            (e.g., "breakdown|folder|folder").
        data: Optional dictionary containing link metadata (e.g., kitsuAssetId,
            kitsuTargetId,             occurence).

    Returns:
        Created link ID string if successful, None otherwise. Warnings
        on failure.
    """
    session = await Session.create(user)
    headers = {"Authorization": f"Bearer {session.token}"}
    payload: dict = {
        "input": input_id,
        "output": output_id,
        "linkType": link_type,
    }
    if data:
        payload["data"] = data

    async with httpx.AsyncClient() as client:
        res = await client.post(
            f"{ayon_server_url}/api/projects/{project_name}/links",
            json=payload,
            headers=headers,
        )
    if res.status_code not in (200, 201):
        logging.warning(
            f"Failed to create link {input_id}->{output_id} "
            f"type '{link_type}': {res.status_code} {res.text}"
        )
        return
    try:
        return res.json().get("id")
    except Exception:
        return None

create_folder(project_name, name, **kwargs) async

TODO: This is a re-implementation of create folder, which does not require background tasks. Maybe just use the similar function from api.folders.folders.py?

Source code in server/kitsu/utils.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
async def create_folder(
    project_name: str,
    name: str,
    **kwargs,
) -> FolderEntity:
    """
    TODO: This is a re-implementation of create folder, which does not
    require background tasks. Maybe just use the similar function from
    api.folders.folders.py?
    """
    payload = {**kwargs, **create_name_and_label(name)}

    folder = FolderEntity(
        project_name=project_name,
        payload=payload,
    )
    await folder.save()
    event = {
        "topic": "entity.folder.created",
        "description": f"Folder {folder.name} created",
        "summary": {"entityId": folder.id, "parentId": folder.parent_id},
        "project": project_name,
    }

    await dispatch_event(**event)
    return folder

create_name_and_label(kitsu_name)

From a name coming from kitsu, create a name and label

Source code in server/kitsu/utils.py
43
44
45
46
def create_name_and_label(kitsu_name: str) -> dict[str, str]:
    """From a name coming from kitsu, create a name and label"""
    name_slug = slugify(kitsu_name, separator="_")
    return {"name": name_slug, "label": kitsu_name}

Delete an entity link via AYON REST API.

Delete a link by its ID. Log warnings if the deletion fails.

Parameters:

Name Type Description Default
project_name str

AYON project name.

required
user UserEntity

User entity for authentication.

required
ayon_server_url str

Base URL of the AYON server.

required
link_id str

ID of the link to delete.

required

Returns:

Type Description
None

None. Warnings on failure.

Source code in server/kitsu/utils.py
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
async def delete_entity_link(
    project_name: str,
    user: "UserEntity",
    ayon_server_url: str,
    link_id: str,
) -> None:
    """Delete an entity link via AYON REST API.

    Delete a link by its ID. Log warnings if the deletion fails.

    Args:
        project_name: AYON project name.
        user: User entity for authentication.
        ayon_server_url: Base URL of the AYON server.
        link_id: ID of the link to delete.

    Returns:
        None. Warnings on failure.
    """
    session = await Session.create(user)
    headers = {"Authorization": f"Bearer {session.token}"}

    async with httpx.AsyncClient() as client:
        res = await client.delete(
            f"{ayon_server_url}/api/projects/{project_name}/links/{link_id}",
            headers=headers,
        )

    if res.status_code not in (200, 204):
        logging.warning(
            f"Failed to delete link {link_id}: {res.status_code} {res.text}"
        )

get_folder_by_kitsu_id(project_name, kitsu_id, existing_folders=None) async

Get an Ayon FolderEndtity by its Kitsu ID

Source code in server/kitsu/utils.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
async def get_folder_by_kitsu_id(
    project_name: str,
    kitsu_id: str,
    existing_folders: dict[str, str] | None = None,
) -> FolderEntity | None:
    """Get an Ayon FolderEndtity by its Kitsu ID"""

    if existing_folders and (kitsu_id in existing_folders):
        folder_id = existing_folders[kitsu_id]

    else:
        res = await Postgres.fetch(
            f"""
            SELECT id FROM project_{project_name}.folders
            WHERE data->>'kitsuId' = $1
            """,
            kitsu_id,
        )
        if not res:
            return None
        folder_id = res[0]["id"]

    return await FolderEntity.load(project_name, folder_id)

Get a link ID by input/output IDs and link type.

Query the database for an existing link matching the given input, output, and link type. Return the first matching link's ID, or None if no link exists.

Parameters:

Name Type Description Default
project_name str

AYON project name (validated for SQL safety).

required
input_id str

AYON folder ID of the link input (source).

required
output_id str

AYON folder ID of the link output (target).

required
link_type str

Link type identifier (e.g., "breakdown|folder|folder").

required

Returns:

Type Description
str | None

Link ID string if found, None otherwise.

Source code in server/kitsu/utils.py
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
async def get_link_by_io(
    project_name: str,
    input_id: str,
    output_id: str,
    link_type: str,
) -> str | None:
    """Get a link ID by input/output IDs and link type.

    Query the database for an existing link matching the given input,
    output, and link type. Return the first matching link's ID, or None
    if no link exists.

    Args:
        project_name: AYON project name (validated for SQL safety).
        input_id: AYON folder ID of the link input (source).
        output_id: AYON folder ID of the link output (target).
        link_type: Link type identifier (e.g., "breakdown|folder|folder").

    Returns:
        Link ID string if found, None otherwise.
    """
    _ensure_safe_project_name(project_name)
    res = await Postgres.fetch(
        f"""
        SELECT id FROM project_{project_name}.links
        WHERE input_id = $1 AND output_id = $2 AND link_type = $3
        """,
        input_id,
        output_id,
        link_type,
    )
    if not res:
        return None
    return res[0]["id"]

Get all links for a given output folder and link type.

Query the database for all links where the specified folder is the output (target). Return link metadata including ID, input_id, and data.

Parameters:

Name Type Description Default
project_name str

AYON project name (validated for SQL safety).

required
output_id str

AYON folder ID of the link output (target).

required
link_type str

Link type identifier (e.g., "breakdown|folder|folder").

required

Returns:

Type Description
list[dict[str, Any]]

List of link dictionaries, each containing: - id: Link ID - input_id: AYON folder ID of the link input (source) - data: Link data dictionary (may contain kitsuAssetId, etc.)

Source code in server/kitsu/utils.py
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
async def get_links_for_output(
    project_name: str,
    output_id: str,
    link_type: str,
) -> list[dict[str, Any]]:
    """Get all links for a given output folder and link type.

    Query the database for all links where the specified folder is the
    output (target). Return link metadata including ID, input_id, and data.

    Args:
        project_name: AYON project name (validated for SQL safety).
        output_id: AYON folder ID of the link output (target).
        link_type: Link type identifier (e.g., "breakdown|folder|folder").

    Returns:
        List of link dictionaries, each containing:
            - id: Link ID
            - input_id: AYON folder ID of the link input (source)
            - data: Link data dictionary (may contain kitsuAssetId, etc.)
    """
    _ensure_safe_project_name(project_name)
    return await Postgres.fetch(
        f"""
        SELECT id, input_id, data FROM project_{project_name}.links
        WHERE output_id = $1 AND link_type = $2
        """,
        output_id,
        link_type,
    )

get_task_by_kitsu_id(project_name, kitsu_id, existing_tasks=None) async

Get an Ayon TaskEntity by its Kitsu ID

Source code in server/kitsu/utils.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
async def get_task_by_kitsu_id(
    project_name: str,
    kitsu_id: str,
    existing_tasks: dict[str, str] | None = None,
) -> TaskEntity | None:
    """Get an Ayon TaskEntity by its Kitsu ID"""

    if existing_tasks and (kitsu_id in existing_tasks):
        folder_id = existing_tasks[kitsu_id]

    else:
        res = await Postgres.fetch(
            f"""
            SELECT id FROM project_{project_name}.tasks
            WHERE data->>'kitsuId' = $1
            """,
            kitsu_id,
        )
        if not res:
            return None
        folder_id = res[0]["id"]

    return await TaskEntity.load(project_name, folder_id)

get_user_by_kitsu_id(kitsu_id) async

Get an Ayon UserEndtity by its Kitsu ID

Source code in server/kitsu/utils.py
49
50
51
52
53
54
55
56
57
58
59
60
async def get_user_by_kitsu_id(
    kitsu_id: str,
) -> UserEntity | None:
    """Get an Ayon UserEndtity by its Kitsu ID"""
    res = await Postgres.fetch(
        "SELECT name FROM public.users WHERE data->>'kitsuId' = $1",
        kitsu_id,
    )
    if not res:
        return None
    user = await UserEntity.load(res[0]["name"])
    return user

update_entity(project_name, entity, kwargs, attr_whitelist=None) async

Updates the entity for given attribute whitelist.

Saves changes and dispatches an update event.

Source code in server/kitsu/utils.py
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
async def update_entity(
    project_name, entity, kwargs, attr_whitelist: list[str] | None = None
):
    """Updates the entity for given attribute whitelist.

    Saves changes and dispatches an update event.
    """

    if attr_whitelist is None:
        attr_whitelist = []

    changed = False

    # keys that can be updated
    for key in attr_whitelist:
        if key in kwargs and getattr(entity, key) != kwargs[key]:
            setattr(entity, key, kwargs[key])
            logging.info(f"setattr {key}")
            changed = True
    if "attrib" in kwargs:
        for key, value in kwargs["attrib"].items():
            if getattr(entity.attrib, key) != value:
                setattr(entity.attrib, key, value)
                if key not in entity.own_attrib:
                    entity.own_attrib.append(key)
                logging.info(
                    f"setattr attrib.{key}"
                    f" {getattr(entity.attrib, key)} => {value}"
                )
                changed = True
    if changed:
        await entity.save()

        summary = {}
        if hasattr(entity, "id"):
            summary["id"] = entity.id
        if hasattr(entity, "parent_id"):
            summary["parent_id"] = entity.parent_id
        if hasattr(entity, "name"):
            summary["name"] = entity.name

        event = {
            "topic": f"entity.{entity.entity_type}.updated",
            "description": f"{entity.entity_type} {entity.name} updated",
            "summary": summary,
            "project": project_name,
        }
        logging.info(f"dispatch_event: {event}")
        await dispatch_event(**event)
    return changed