Skip to content

update_from_ayon

Module that handles creation, update or removal of SG entities based on AYON events.

create_sg_entity_from_ayon_event(ayon_event, sg_session, ayon_entity_hub, sg_project, sg_enabled_entities, sg_project_code_field, custom_attribs_map, addon_settings)

Create a Shotgrid entity from an AYON event.

Parameters:

Name Type Description Default
sg_event dict

AYON event.

required
sg_session Shotgun

The Shotgrid API session.

required
ayon_entity_hub EntityHub

The AYON EntityHub.

required
sg_project dict

The Shotgrid project.

required
sg_enabled_entities list

List of Shotgrid entities to be enabled.

required
sg_project_code_field str

'code' most likely

required
custom_attribs_map dict

Dictionary that maps a list of attribute names from AYON to Shotgrid.

required

Raises:

Type Description
ValueError

If the AYON entity does not exist.

Returns:

Name Type Description
ay_entity Entity

source AYON entity with updated Shotgrid ID and Type attributes.

Source code in services/shotgrid_common/ayon_shotgrid_hub/update_from_ayon.py
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def create_sg_entity_from_ayon_event(
    ayon_event: Dict,
    sg_session: shotgun_api3.Shotgun,
    ayon_entity_hub: ayon_api.entity_hub.EntityHub,
    sg_project: Dict,
    sg_enabled_entities: List[str],
    sg_project_code_field: [str],
    custom_attribs_map: Dict[str, str],
    addon_settings: Dict[str, Any],
):
    """Create a Shotgrid entity from an AYON event.

    Args:
        sg_event (dict): AYON event.
        sg_session (shotgun_api3.Shotgun): The Shotgrid API session.
        ayon_entity_hub (ayon_api.entity_hub.EntityHub): The AYON EntityHub.
        sg_project (dict): The Shotgrid project.
        sg_enabled_entities (list): List of Shotgrid entities to be enabled.
        sg_project_code_field (str): 'code' most likely
        custom_attribs_map (dict): Dictionary that maps a list of attribute names from
            AYON to Shotgrid.

    Raises:
        ValueError: If the AYON entity does not exist.

    Returns:
        ay_entity (ayon_api.entity_hub.EntityHub.Entity): source AYON entity
            with updated Shotgrid ID and Type attributes.
    """
    ay_id = ayon_event["summary"]["entityId"]
    ay_entity = ayon_entity_hub.get_or_query_entity_by_id(
        ay_id, ["folder", "task", "version"])

    if not ay_entity:
        raise ValueError(
            "Event has a non existent entity? "
            f"{ayon_event['summary']['entityId']}"
        )

    sg_id = ay_entity.attribs.get("shotgridId")
    sg_type = ay_entity.attribs.get("shotgridType")

    if not sg_type:
        if ay_entity.entity_type == "task":
            sg_type = "Task"
        elif ay_entity.entity_type == "version":
            sg_type = "Version"
        else:
            sg_type = ay_entity.folder_type

    sg_entity = None

    if sg_id is not None:
        try:
            sg_id = int(sg_id)
        except (ValueError, TypeError):
            log.warning(
                f"Skip SG entity processing from AYON '{ay_entity}'. "
                f"AYON entity defines an invalid non-integer sg_id '{sg_id}'."
            )
            return ay_entity

    if sg_id and sg_type:
        sg_entity = sg_session.find_one(sg_type, [["id", "is", sg_id]])

    if sg_entity:
        log.warning(f"Entity {sg_entity} already exists in Shotgrid!")
        return ay_entity

    try:
        sg_parent_entity = _get_sg_parent_entity(
            sg_session, ay_entity, ayon_event)

        sg_entity = create_new_sg_entity(
            ay_entity,
            sg_session,
            sg_project,
            sg_parent_entity,
            sg_enabled_entities,
            sg_project_code_field,
            custom_attribs_map,
            addon_settings,
            ayon_event["project"]
        )
        if not sg_entity:
            log.warning(f"Couldn't create SG entity for '{ay_id}")

        if (
            ay_entity.entity_type == "folder"
            and ay_entity.folder_type == "AssetCategory"
        ):
            # AssetCategory is special, we don't want to create it in Shotgrid
            # but we need to assign Shotgrid ID and Type to it
            sg_entity = {
                "id": ay_entity.name.lower(),
                "type": "AssetCategory"
            }

        if not sg_entity:
            if hasattr(ay_entity, "folder_type"):
                log.warning(
                    f"Unable to create `{ay_entity.folder_type}` <{ay_id}> "
                    "in Shotgrid!"
                )
            else:
                log.warning(
                    f"Unable to create `{ay_entity.entity_type}` <{ay_id}> "
                    "in Shotgrid!"
                )
            return ay_entity

        sg_id = sg_entity["attribs"]["shotgridId"]
        sg_type = sg_entity["attribs"]["shotgridType"]
        log.info(f"Created Shotgrid entity: {sg_id} of {sg_type}")

        ay_entity.attribs.set(
            SHOTGRID_ID_ATTRIB,
            sg_id
        )
        ay_entity.attribs.set(
            SHOTGRID_TYPE_ATTRIB,
            sg_type
        )
        ayon_entity_hub.commit_changes()
        return ay_entity

    except Exception:
        log.error(
            f"Unable to create {sg_type} <{ay_id}> in Shotgrid!",
            exc_info=True
        )
        return None

remove_sg_entity_from_ayon_event(ayon_event, sg_session)

Try to remove a Shotgrid entity from an AYON event.

Parameters:

Name Type Description Default
ayon_event dict

The meta key from a Shotgrid Event.

required
sg_session Shotgun

The Shotgrid API session.

required
Source code in services/shotgrid_common/ayon_shotgrid_hub/update_from_ayon.py
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
def remove_sg_entity_from_ayon_event(
    ayon_event: Dict,
    sg_session: shotgun_api3.Shotgun
):
    """Try to remove a Shotgrid entity from an AYON event.

    Args:
        ayon_event (dict): The `meta` key from a Shotgrid Event.
        sg_session (shotgun_api3.Shotgun): The Shotgrid API session.
    """
    ay_id = ayon_event["payload"]["entityData"]["id"]
    log.debug(f"Removing Shotgrid entity: {ayon_event['payload']}")

    sg_id = ayon_event["payload"]["entityData"]["attrib"].get("shotgridId")

    if not sg_id:
        ay_entity_path = ayon_event["payload"]["entityData"]["path"]
        log.warning(
            f"Entity '{ay_entity_path}' does not have a "
            "ShotGrid ID to remove."
        )
        return

    sg_type = ayon_event["payload"]["entityData"]["attrib"]["shotgridType"]

    if not sg_type:
        sg_type = ayon_event["payload"]["folderType"]

    if sg_id and sg_type:
        sg_entity = sg_session.find_one(
            sg_type,
            filters=[["id", "is", int(sg_id)]]
        )
    else:
        sg_entity = sg_session.find_one(
            sg_type,
            filters=[[CUST_FIELD_CODE_ID, "is", ay_id]]
        )

    if not sg_entity:
        log.warning(
            f"Unable to find AYON entity with id '{ay_id}' in Shotgrid.")
        return

    sg_id = sg_entity["id"]

    try:
        sg_session.delete(sg_type, int(sg_id))
        log.info(f"Retired Shotgrid entity: {sg_type} <{sg_id}>")
    except Exception:
        log.error(
            f"Unable to delete {sg_type} <{sg_id}> in Shotgrid!",
            exc_info=True
        )

update_sg_entity_from_ayon_event(ayon_event, sg_session, ayon_entity_hub, sg_project, sg_enabled_entities, sg_project_code_field, custom_attribs_map, addon_settings)

Try to update a Shotgrid entity from an AYON event.

Parameters:

Name Type Description Default
sg_event dict

The meta key from a Shotgrid Event.

required
sg_session Shotgun

The Shotgrid API session.

required
ayon_entity_hub EntityHub

The AYON EntityHub.

required
custom_attribs_map dict

A mapping of custom attributes to update.

required

Returns:

Name Type Description
sg_entity dict

The modified Shotgrid entity.

Source code in services/shotgrid_common/ayon_shotgrid_hub/update_from_ayon.py
337
338
339
340
341
342
343
344
345
346
347
348
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
405
406
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
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
def update_sg_entity_from_ayon_event(
    ayon_event: Dict,
    sg_session: shotgun_api3.Shotgun,
    ayon_entity_hub: ayon_api.entity_hub.EntityHub,
    sg_project: Dict,
    sg_enabled_entities: List[str],
    sg_project_code_field: [str],
    custom_attribs_map: Dict[str, str],
    addon_settings: Dict[str, Any],
):
    """Try to update a Shotgrid entity from an AYON event.

    Args:
        sg_event (dict): The `meta` key from a Shotgrid Event.
        sg_session (shotgun_api3.Shotgun): The Shotgrid API session.
        ayon_entity_hub (ayon_api.entity_hub.EntityHub): The AYON EntityHub.
        custom_attribs_map (dict): A mapping of custom attributes to update.

    Returns:
        sg_entity (dict): The modified Shotgrid entity.

    """
    ay_id = ayon_event["summary"]["entityId"]
    ay_entity = ayon_entity_hub.get_or_query_entity_by_id(
        ay_id, ["folder", "task", "version"])

    if not ay_entity:
        raise ValueError(
            "Event has a non existent entity? "
            f"{ayon_event['summary']['entityId']}"
        )

    sg_id = ay_entity.attribs.get("shotgridId")
    sg_entity_type = ay_entity.attribs.get("shotgridType")

    # react to an AYON entity being updated
    # that does not exist yet in Shotgrid.
    if sg_id is None:

        # Create SG entity and update existing ay_entity.
        ay_entity = create_sg_entity_from_ayon_event(
            ayon_event,
            sg_session,
            ayon_entity_hub,
            sg_project,
            sg_enabled_entities,
            sg_project_code_field,
            custom_attribs_map,
            addon_settings,
        )

        sg_id = ay_entity.attribs.get("shotgridId")
        sg_entity_type = ay_entity.attribs.get("shotgridType")

        if sg_id is None:
            log.warning(f"Could not create SG entity from {ay_entity}.")
            return

    try:
        sg_field_name = "code"
        if ay_entity["entity_type"] == "task":
            sg_field_name = "content"

        data_to_update = {
            CUST_FIELD_CODE_ID: ay_entity["id"]
        }

        try:
            data_to_update[sg_field_name] = ay_entity["name"]
        except NotImplementedError:
            pass  # Version does not have a name.

        # Add any possible new values to update
        new_attribs = ayon_event["payload"].get("newValue")

        if isinstance(new_attribs, dict):
            # If payload newValue is a dict it means it's an attribute update
            # but this only apply to case were attribs key is in the
            # newValue dict
            if "attribs" in new_attribs:
                new_attribs = new_attribs["attribs"]

        # Label changed
        elif ayon_event["topic"].endswith("label_changed"):
            new_value = ayon_event["payload"].get("newValue")
            data_to_update[sg_field_name] = new_value
            new_attribs = None

        # Otherwise it's a tag/status update
        elif ayon_event["topic"].endswith("status_changed"):
            sg_statuses = get_sg_statuses(sg_session, sg_entity_type)
            ay_statuses = {
                status.name: status.short_name
                for status in  ayon_entity_hub.project_entity.statuses
            }
            short_name = ay_statuses.get(new_attribs)
            if short_name in sg_statuses:
                new_attribs = {"status": short_name}
            else:
                log.error(
                    f"Unable to update '{sg_entity_type}' with status "
                    f"'{new_attribs}' in Shotgrid as it's not compatible! "
                    f"It should be one of: {sg_statuses}"
                )
                return

        elif ayon_event["topic"].endswith("tags_changed"):
            tags_event_list = new_attribs
            new_attribs = {"tags": []}
            sg_tags = get_sg_tags(sg_session)
            for tag_name in tags_event_list:
                if tag_name.lower() in sg_tags:
                    tag_id = sg_tags[tag_name]
                else:
                    log.info(
                        f"Tag '{tag_name}' not found in ShotGrid, "
                        "creating a new one."
                    )
                    new_tag = sg_session.create("Tag", {'name': tag_name})
                    tag_id = new_tag["id"]

                new_attribs["tags"].append(
                    {"name": tag_name, "id": tag_id, "type": "Tag"}
                )
        elif ayon_event["topic"].endswith("assignees_changed"):
            sg_assignees = []
            for user_name in new_attribs:
                ayon_user = ayon_api.get_user(user_name)
                if not ayon_user or not ayon_user["data"].get("sg_user_id"):
                    log.warning(f"User {user_name} is not synched to SG yet.")
                    continue
                sg_assignees.append(
                    {"type": "HumanUser",
                     "id": ayon_user["data"]["sg_user_id"]}
                )
            new_attribs = {"assignees": sg_assignees}
        else:
            log.warning(
                "Unknown event type, skipping update of custom attribs.")
            new_attribs = None

        if new_attribs:
            data_to_update.update(get_sg_custom_attributes_data(
                sg_session,
                new_attribs,
                sg_entity_type,
                custom_attribs_map
            ))


        sg_entity = sg_session.update(
            sg_entity_type,
            int(sg_id),
            data_to_update
        )
        log.info(f"Updated ShotGrid entity: {sg_entity}")
        return sg_entity

    except Exception:
        log.error(
            f"Unable to update {sg_entity_type} <{sg_id}> in ShotGrid!",
            exc_info=True
        )