Skip to content

update_from_shotgrid

Module that handles creation, update or removal of AYON entities based on ShotGrid Events.

The updates come through meta dictionaries such as: "meta": { "id": 1274, "type": "entity_retirement", "entity_id": 1274, "class_name": "Shot", "entity_type": "Shot", "display_name": "bunny_099_012", "retirement_date": "2023-03-31 15:26:16 UTC" }

And most of the times it fetches the ShotGrid entity as an AYON dict like: { "label": label, "name": name, SHOTGRID_ID_ATTRIB: ShotGrid id, CUST_FIELD_CODE_ID: ayon id stored in ShotGrid, CUST_FIELD_CODE_SYNC: sync status stored in ShotGrid, "type": the entity type, }

create_ay_entity_from_sg_event(sg_event, sg_project, sg_session, ayon_entity_hub, sg_enabled_entities, project_code_field, custom_attribs_map=None, addon_settings=None)

Create an AYON entity from a ShotGrid Event.

Parameters:

Name Type Description Default
sg_event dict

The meta key from a ShotGrid Event.

required
sg_project dict

The ShotGrid project.

required
sg_session Shotgun

The ShotGrid API session.

required
ayon_entity_hub EntityHub

The AYON EntityHub.

required
sg_enabled_entities list[str]

List of entity strings enabled.

required
project_code_field str

The Shotgrid project code field.

required
custom_attribs_map Optional[dict]

A dictionary that maps ShotGrid attributes to Ayon attributes.

None
addon_settings Optional[dict]

A dictionary of Settings

None

Returns:

Name Type Description
ay_entity Entity

The newly created entity.

Source code in services/shotgrid_common/ayon_shotgrid_hub/update_from_shotgrid.py
 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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
def create_ay_entity_from_sg_event(
    sg_event: Dict,
    sg_project: Dict,
    sg_session: shotgun_api3.Shotgun,
    ayon_entity_hub: ayon_api.entity_hub.EntityHub,
    sg_enabled_entities: List[str],
    project_code_field: str,
    custom_attribs_map: Optional[Dict[str, str]] = None,
    addon_settings: Optional[Dict[str, str]] = None
):
    """Create an AYON entity from a ShotGrid Event.

    Args:
        sg_event (dict): The `meta` key from a ShotGrid Event.
        sg_project (dict): The ShotGrid project.
        sg_session (shotgun_api3.Shotgun): The ShotGrid API session.
        ayon_entity_hub (ayon_api.entity_hub.EntityHub): The AYON EntityHub.
        sg_enabled_entities (list[str]): List of entity strings enabled.
        project_code_field (str): The Shotgrid project code field.
        custom_attribs_map (Optional[dict]): A dictionary that maps ShotGrid
            attributes to Ayon attributes.
        addon_settings (Optional[dict]): A dictionary of Settings

    Returns:
        ay_entity (ayon_api.entity_hub.EntityHub.Entity): The newly
            created entity.
    """
    default_task_type = addon_settings[
        "compatibility_settings"]["default_task_type"]
    sg_parent_field = get_sg_entity_parent_field(
        sg_session,
        sg_project,
        sg_event["entity_type"],
        sg_enabled_entities,
    )

    extra_fields = [sg_parent_field]

    sg_ay_dict = get_sg_entity_as_ay_dict(
        sg_session,
        sg_event["entity_type"],
        sg_event["entity_id"],
        project_code_field,
        default_task_type,
        custom_attribs_map=custom_attribs_map,
        extra_fields=extra_fields,
    )

    log.debug(f"ShotGrid Entity as AYON dict: {sg_ay_dict}")
    if not sg_ay_dict:
        log.warning(
            f"Entity {sg_event['entity_type']} <{sg_event['entity_id']}> "
            "no longer exists in ShotGrid, aborting..."
        )
        return

    if sg_ay_dict["type"].lower() == "comment":
        # SG note as AYON comment creation is
        # handled by update_ayon_entity_from_sg_event
        if sg_ay_dict["attribs"]["shotgridType"] == "Note":
            return
        if sg_ay_dict["attribs"]["shotgridType"] == "Reply":
            handle_reply(
                sg_ay_dict,
                sg_session,
                ayon_entity_hub,
            )
            return

    ayon_id_stored_in_sg = sg_ay_dict["data"].get(CUST_FIELD_CODE_ID)
    if ayon_id_stored_in_sg:
        # Revived entity, check if it's still in the Server
        ay_entity = ayon_entity_hub.get_or_query_entity_by_id(
            ayon_id_stored_in_sg,
            [sg_ay_dict["type"]]
        )

        if ay_entity:
            log.debug("ShotGrid Entity exists in AYON.")
            # Ensure AYON Entity has the correct ShotGrid ID
            ay_entity = _update_sg_id(
                ay_entity,
                custom_attribs_map,
                sg_ay_dict,
                ayon_entity_hub.project_entity
            )

            return ay_entity

    ay_parent_entity = None
    items_to_create = collections.deque()
    while ay_parent_entity is None:
        items_to_create.append(sg_ay_dict)
        ay_parent_entity = _get_ayon_parent_entity(
            ayon_entity_hub,
            project_code_field,
            sg_ay_dict,
            sg_parent_field,
            sg_project,
            sg_session,
            addon_settings
        )

        sg_parent = sg_ay_dict["data"].get(sg_parent_field)
        if not ay_parent_entity and not sg_parent:
            ay_parent_entity = ayon_entity_hub.project_entity

        if not ay_parent_entity:
            if sg_ay_dict["data"][sg_parent_field]["type"] == "Asset":
                extra_field = "sg_asset_type"

            else:
                extra_field = get_sg_entity_parent_field(
                    sg_session,
                    sg_project,
                    sg_ay_dict["data"][sg_parent_field]["type"],
                    sg_enabled_entities,
                )

            sg_ay_dict = get_sg_entity_as_ay_dict(
                sg_session,
                sg_ay_dict["data"][sg_parent_field]["type"],
                sg_ay_dict["data"][sg_parent_field]["id"],
                project_code_field,
                default_task_type,
                custom_attribs_map=custom_attribs_map,
                extra_fields=[extra_field],
            )
            sg_parent_field = extra_field

    while items_to_create:
        sg_ay_dict = items_to_create.pop()

        shotgrid_type = sg_ay_dict["attribs"][SHOTGRID_TYPE_ATTRIB]
        sg_parent_field = get_sg_entity_parent_field(
            sg_session,
            sg_project,
            shotgrid_type,
            sg_enabled_entities,
        )
        ay_parent_entity = _get_ayon_parent_entity(
            ayon_entity_hub,
            project_code_field,
            sg_ay_dict,
            sg_parent_field,
            sg_project,
            sg_session,
            addon_settings
        )

        ay_entity = create_new_ayon_entity(
            sg_session,
            ayon_entity_hub,
            ay_parent_entity,
            sg_ay_dict
        )

    return ay_entity

remove_ayon_entity_from_sg_event(sg_event, sg_session, ayon_entity_hub, project_code_field, addon_settings)

Try to remove an entity in AYON.

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
project_code_field str

The ShotGrid field that contains the AYON ID.

required
addon_settings dict

A dictionary of Settings.

required
Source code in services/shotgrid_common/ayon_shotgrid_hub/update_from_shotgrid.py
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
def remove_ayon_entity_from_sg_event(
    sg_event: Dict,
    sg_session: shotgun_api3.Shotgun,
    ayon_entity_hub: ayon_api.entity_hub.EntityHub,
    project_code_field: str,
    addon_settings: Dict[str, Any],
):
    """Try to remove an entity in AYON.

    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.
        project_code_field (str): The ShotGrid field that contains the AYON ID.
        addon_settings (dict): A dictionary of Settings.
    """
    default_task_type = addon_settings[
        "compatibility_settings"]["default_task_type"]

    sg_ay_dict = get_sg_entity_as_ay_dict(
        sg_session,
        sg_event["entity_type"],
        sg_event["entity_id"],
        project_code_field,
        default_task_type,
        retired_only=True
    )

    if not sg_ay_dict:
        sg_ay_dict = get_sg_entity_as_ay_dict(
            sg_session,
            sg_event["entity_type"],
            sg_event["entity_id"],
            project_code_field,
            default_task_type,
            retired_only=False,
        )
        if sg_ay_dict:
            log.info(
                f"No need to remove entity {sg_event['entity_type']} "
                f"<{sg_event['entity_id']}>, it's not retired anymore."
            )
            return
        else:
            log.warning(
                f"Entity {sg_event['entity_type']} <{sg_event['entity_id']}> "
                "no longer exists in ShotGrid."
            )

    if not sg_ay_dict["data"].get(CUST_FIELD_CODE_ID):
        log.warning(
            "Entity does not have an AYON ID, aborting..."
        )
        return

    ay_entity = ayon_entity_hub.get_or_query_entity_by_id(
        sg_ay_dict["data"].get(CUST_FIELD_CODE_ID),
        ["task" if sg_ay_dict.get("type").lower() == "task" else "folder"]
    )

    if not ay_entity:
        raise ValueError("Unable to update a non existing entity.")

    if sg_ay_dict["data"].get(CUST_FIELD_CODE_ID) != ay_entity.id:
        raise ValueError("Mismatching ShotGrid IDs, aborting...")

    if not ay_entity.immutable_for_hierarchy:
        log.info(f"Deleting AYON entity: {ay_entity}")
        ayon_entity_hub.delete_entity(ay_entity)
    else:
        log.info("Entity is immutable.")
        ay_entity.attribs.set(SHOTGRID_ID_ATTRIB, SHOTGRID_REMOVED_VALUE)

    ayon_entity_hub.commit_changes()

update_ayon_entity_from_sg_event(sg_event, sg_project, sg_session, ayon_entity_hub, sg_enabled_entities, project_code_field, addon_settings, custom_attribs_map=None)

Try to update an entity in AYON.

Parameters:

Name Type Description Default
sg_event dict

The meta key from a ShotGrid Event.

required
sg_project dict

The ShotGrid project.

required
sg_session Shotgun

The ShotGrid API session.

required
ayon_entity_hub EntityHub

The AYON EntityHub.

required
sg_enabled_entities list[str]

List of entity strings enabled.

required
project_code_field str

The ShotGrid project code field.

required
addon_settings dict

A dictionary of Settings.

required
custom_attribs_map dict

A dictionary that maps ShotGrid attributes to AYON attributes.

None

Returns:

Name Type Description
ay_entity Entity

The modified entity.

Source code in services/shotgrid_common/ayon_shotgrid_hub/update_from_shotgrid.py
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
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
def update_ayon_entity_from_sg_event(
    sg_event: Dict,
    sg_project: Dict,
    sg_session: shotgun_api3.Shotgun,
    ayon_entity_hub: ayon_api.entity_hub.EntityHub,
    sg_enabled_entities: List[str],
    project_code_field: str,
    addon_settings: Dict[str, Any],
    custom_attribs_map: Optional[Dict[str, str]] = None,
):
    """Try to update an entity in AYON.

    Args:
        sg_event (dict): The `meta` key from a ShotGrid Event.
        sg_project (dict): The ShotGrid project.
        sg_session (shotgun_api3.Shotgun): The ShotGrid API session.
        ayon_entity_hub (ayon_api.entity_hub.EntityHub): The AYON EntityHub.
        sg_enabled_entities (list[str]): List of entity strings enabled.
        project_code_field (str): The ShotGrid project code field.
        addon_settings (dict): A dictionary of Settings.
        custom_attribs_map (dict): A dictionary that maps ShotGrid
            attributes to AYON attributes.

    Returns:
        ay_entity (ayon_api.entity_hub.EntityHub.Entity): The modified entity.

    """
    default_task_type = addon_settings[
        "compatibility_settings"]["default_task_type"]

    sg_ay_dict = get_sg_entity_as_ay_dict(
        sg_session,
        sg_event["entity_type"],
        sg_event["entity_id"],
        project_code_field,
        default_task_type,
        custom_attribs_map=custom_attribs_map
    )

    if not sg_ay_dict:
        log.warning(
            f"Entity {sg_event['entity_type']} <{sg_event['entity_id']}> "
            "no longer exists in ShotGrid, aborting..."
        )
        return

    if sg_ay_dict["type"].lower() == "comment":
        if sg_ay_dict["attribs"]["shotgridType"] == "Note":
            handle_comment(
                sg_ay_dict,
                sg_session,
                ayon_entity_hub,
            )
        else:
            handle_reply(
                sg_ay_dict,
                sg_session,
                ayon_entity_hub,
            )
        return

    # if the entity does not have an AYON ID, try to create it
    # and no need to update
    if not sg_ay_dict["data"].get(CUST_FIELD_CODE_ID):
        log.debug(f"Creating AYON Entity: {sg_ay_dict}")
        try:
            create_ay_entity_from_sg_event(
                sg_event,
                sg_project,
                sg_session,
                ayon_entity_hub,
                sg_enabled_entities,
                project_code_field,
                custom_attribs_map
            )
        except Exception:
            log.debug("AYON Entity could not be created", exc_info=True)
        return

    ay_entity = ayon_entity_hub.get_or_query_entity_by_id(
        sg_ay_dict["data"].get(CUST_FIELD_CODE_ID),
        [sg_ay_dict["type"]]
    )

    if not ay_entity:
        raise ValueError("Unable to update a non existing entity.")

    # make sure the entity is not immutable
    if (
        ay_entity.immutable_for_hierarchy
        and sg_event["attribute_name"] in SG_RESTRICTED_ATTR_FIELDS
    ):
        raise ValueError("Entity is immutable, aborting...")

    # Ensure AYON Entity has the correct ShotGrid ID
    ayon_entity_sg_id = str(
        ay_entity.attribs.get(SHOTGRID_ID_ATTRIB, "")
    )
    sg_entity_sg_id = str(
        sg_ay_dict["attribs"].get(SHOTGRID_ID_ATTRIB, "")
    )


    # We need to check for existence in `ayon_entity_sg_id` as it could be
    # that it's a new entity and it doesn't have a ShotGrid ID yet.
    if ayon_entity_sg_id and ayon_entity_sg_id != sg_entity_sg_id:
        log.error("Mismatching ShotGrid IDs, aborting...")
        raise ValueError("Mismatching ShotGrid IDs, aborting...")

    # Update entity label.
    if ay_entity.entity_type != "version":
        log.debug(f"Updating AYON Entity: {ay_entity.name}")
    else:
        log.debug(f"Updating AYON Entity: {ay_entity}")

    # TODO: Only update the updated fields in the event
    update_ay_entity_custom_attributes(
        ay_entity,
        sg_ay_dict,
        custom_attribs_map,
        ay_project=ayon_entity_hub.project_entity
    )

    ayon_entity_hub.commit_changes()

    if sg_ay_dict["data"].get(CUST_FIELD_CODE_ID) != ay_entity.id:
        sg_session.update(
            sg_ay_dict["attribs"][SHOTGRID_TYPE_ATTRIB],
            sg_ay_dict["attribs"][SHOTGRID_ID_ATTRIB],
            {
                CUST_FIELD_CODE_ID: ay_entity.id
            }
        )

    ay_entity.attribs.set(
        SHOTGRID_ID_ATTRIB,
        sg_ay_dict["attribs"].get(SHOTGRID_ID_ATTRIB, "")
    )
    ay_entity.attribs.set(
        SHOTGRID_TYPE_ATTRIB,
        sg_ay_dict["attribs"].get(SHOTGRID_TYPE_ATTRIB, "")
    )

    return ay_entity