Skip to content

lib

Utility functions used for AYON - Harmony integration.

check_libs()

Check if OpenHarmony_ is available.

AYON expects either path in LIB_OPENHARMONY_PATH or openHarmony.js present in TOONBOOM_GLOBAL_SCRIPT_LOCATION.

Throws

RuntimeError: If openHarmony is not found.

.. _OpenHarmony: https://github.com/cfourney/OpenHarmony

Source code in client/ayon_harmony/api/lib.py
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
def check_libs():
    """Check if `OpenHarmony`_ is available.

    AYON expects either path in `LIB_OPENHARMONY_PATH` or `openHarmony.js`
    present in `TOONBOOM_GLOBAL_SCRIPT_LOCATION`.

    Throws:
        RuntimeError: If openHarmony is not found.

    .. _OpenHarmony:
        https://github.com/cfourney/OpenHarmony

    """
    if os.getenv("LIB_OPENHARMONY_PATH"):
        return

    script_location = os.getenv("TOONBOOM_GLOBAL_SCRIPT_LOCATION")
    if not script_location:
        log.error(
            "Cannot find OpenHarmony library."
            " Please set path to it in LIB_OPENHARMONY_PATH"
            " environment variable."
        )
        raise RuntimeError("Missing OpenHarmony library.")

    script_path = os.path.join(script_location, "openHarmony.js")
    if os.path.exists(script_path):
        os.environ["LIB_OPENHARMONY_PATH"] = script_location

copy_with_progress(src, dst)

Copy file with a progress bar dialog.

Parameters:

Name Type Description Default
src str

Source file path.

required
dst str

Destination file path.

required
Source code in client/ayon_harmony/api/lib.py
325
326
327
328
329
330
331
332
333
334
335
336
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
def copy_with_progress(src, dst):
    """Copy file with a progress bar dialog.

    Args:
        src (str): Source file path.
        dst (str): Destination file path.
    """
    file_size = os.path.getsize(src)

    progress = QtWidgets.QProgressDialog(
        f"Copying {os.path.basename(src)}...",
        None,
        0,
        100
    )
    progress.setStyleSheet(style.load_stylesheet())
    progress.setWindowTitle("Transferring File")
    progress.setWindowModality(QtCore.Qt.WindowModal)
    progress.setMinimumDuration(0)
    progress.setValue(0)
    progress.setCancelButton(None)

    chunk_size = 1024 * 1024  # 1MB chunks
    bytes_copied = 0

    try:
        with open(src, 'rb') as fsrc:
            with open(dst, 'wb') as fdst:
                last_process_events = time.monotonic()
                while True:
                    chunk = fsrc.read(chunk_size)
                    if not chunk:
                        break

                    fdst.write(chunk)
                    bytes_copied += len(chunk)

                    if file_size > 0:
                        percent = int((bytes_copied / file_size) * 100)
                    else:
                        # Handle empty source file gracefully
                        percent = 100

                    progress.setValue(percent)

                    # Process Qt events to keep UI responsive
                    now = time.monotonic()
                    if now - last_process_events >= 0.05:
                        QtWidgets.QApplication.processEvents(
                            QtCore.QEventLoop.AllEvents, 50
                        )
                        last_process_events = now

        shutil.copystat(src, dst)

    except Exception:
        # Remove partially written destination file to avoid corrupted state
        try:
            if os.path.exists(dst):
                os.remove(dst)
        except OSError as cleanup_error:
            # Log but don't mask the original exception
            print(
                "Warning: Failed to remove partial file "
                f"'{dst}': {cleanup_error}"
            )
        raise  # Re-raise the original exception to the caller

    finally:
        progress.close()

    log.info(f"Successfully copied {src} to {dst}")

delete_node(node)

Physically delete node from scene.

Source code in client/ayon_harmony/api/lib.py
757
758
759
760
761
762
763
764
def delete_node(node):
    """ Physically delete node from scene. """
    send(
        {
            "function": "AyonHarmonyAPI.deleteNode",
            "args": node
        }
    )

find_backdrop_by_name(name)

Find backdrop by its name.

Parameters:

Name Type Description Default
name str

Name of the backdrop.

required

Returns:

Name Type Description
dict Optional[dict]

Backdrop.

Source code in client/ayon_harmony/api/lib.py
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
def find_backdrop_by_name(name: str) -> Optional[dict]:
    """Find backdrop by its name.

    Args:
        name (str): Name of the backdrop.

    Returns:
        dict: Backdrop.
    """
    backdrops = send(
        {"function": "Backdrop.backdrops", "args": ["Top"]}
    )["result"]
    for backdrop in backdrops:
        if backdrop["title"]["text"] == name:
            return backdrop

    return None

find_node_by_name(name, node_type)

Find node by its name.

Parameters:

Name Type Description Default
name str

Name of the Node. (without part before '/')

required
node_type str

Type of the Node. 'READ' - for loaded data with Loaders (background) 'GROUP' - for loaded data with Loaders (templates) 'WRITE' - render nodes

required

Returns:

Name Type Description
str

FQ Node name.

Source code in client/ayon_harmony/api/lib.py
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
def find_node_by_name(name, node_type):
    """Find node by its name.

    Args:
        name (str): Name of the Node. (without part before '/')
        node_type (str): Type of the Node.
            'READ' - for loaded data with Loaders (background)
            'GROUP' - for loaded data with Loaders (templates)
            'WRITE' - render nodes

    Returns:
        str: FQ Node name.

    """
    nodes = send(
        {"function": "node.getNodes", "args": [[node_type]]}
    )["result"]
    for node in nodes:
        node_name = node.split("/")[-1]
        if name == node_name:
            return node

    return None

get_all_top_names()

Get all top node and backdrop names in the scene.

Returns:

Name Type Description
set set

Set of top node names.

Source code in client/ayon_harmony/api/lib.py
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
def get_all_top_names() -> set:
    """Get all top node and backdrop names in the scene.

    Returns:
        set: Set of top node names.

    """
    nodes = send({"function": "node.subNodes", "args": ["Top"]})["result"]
    backdrops = {
        backdrop["title"]["text"]
        for backdrop in send(
            {"function": "Backdrop.backdrops", "args": ["Top"]}
        )["result"]
    }
    return set(nodes) | backdrops

get_layers_info(top_only=True) cached

Returns list of dicts with info about timeline layers

'position' goes from 0 at the top and increases to bottom on timeline

Source code in client/ayon_harmony/api/lib.py
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
@lru_cache(maxsize=1)
def get_layers_info(top_only: bool = True) -> list[dict[str, str]]:
    """Returns list of dicts with info about timeline layers

    'position' goes from 0 at the top and increases to bottom on timeline
    """
    layers_info = send(
        {
            "function": "AyonHarmony.getLayerInfos",
            "args": [top_only]
        }
    )["result"]
    layers_info = [layer for layer in layers_info if layer["enabled"]]
    return sorted(
        layers_info,
        key=lambda layer: layer["position"],
        reverse=True
    )

get_local_harmony_path(filepath)

From the provided path get the equivalent local Harmony path.

Source code in client/ayon_harmony/api/lib.py
297
298
299
300
301
def get_local_harmony_path(filepath):
    """From the provided path get the equivalent local Harmony path."""
    basename = os.path.splitext(os.path.basename(filepath))[0]
    harmony_path = os.path.join(os.path.expanduser("~"), ".ayon", "harmony")
    return os.path.join(harmony_path, basename)

get_palettes_paths()

Get all palettes paths in the scene.

Returns:

Name Type Description
set set

Set of palettes paths.

Source code in client/ayon_harmony/api/lib.py
784
785
786
787
788
789
790
791
792
def get_palettes_paths() -> set:
    """Get all palettes paths in the scene.

    Returns:
        set: Set of palettes paths.
    """
    return {pal["_path"] for pal in send(
        {"function": "AyonHarmony.getAllPalettesPaths"}
    )["result"]}

imprint(node_id, data, remove=False)

Write data to the node as json.

Parameters:

Name Type Description Default
node_id str

Path to node or id of object.

required
data dict

Dictionary of key/value pairs.

required
remove bool

Removes the data from the scene.

False
Example

from ayon_harmony.api import lib node = "Top/Display" data = {"str": "something", "int": 1, "float": 0.32, "bool": True} lib.imprint(layer, data)

Source code in client/ayon_harmony/api/lib.py
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
def imprint(node_id, data, remove=False):
    """Write `data` to the `node` as json.

    Arguments:
        node_id (str): Path to node or id of object.
        data (dict): Dictionary of key/value pairs.
        remove (bool): Removes the data from the scene.

    Example:
        >>> from ayon_harmony.api import lib
        >>> node = "Top/Display"
        >>> data = {"str": "something", "int": 1, "float": 0.32, "bool": True}
        >>> lib.imprint(layer, data)
    """
    scene_data = get_scene_data()

    if remove and (node_id in scene_data):
        scene_data.pop(node_id, None)
    else:
        if node_id in scene_data:
            scene_data[node_id].update(data)
        else:
            scene_data[node_id] = data

    set_scene_data(scene_data)

launch(application_path, *args)

Set Harmony for launch.

Launches Harmony and the server, then starts listening on the main thread for callbacks from the server. This is to have Qt applications run in the main thread.

Parameters:

Name Type Description Default
application_path str

Path to Harmony.

required
Source code in client/ayon_harmony/api/lib.py
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
def launch(application_path, *args):
    """Set Harmony for launch.

    Launches Harmony and the server, then starts listening on the main thread
    for callbacks from the server. This is to have Qt applications run in the
    main thread.

    Args:
        application_path (str): Path to Harmony.

    """
    from ayon_core.pipeline import install_host
    from ayon_harmony.api import HarmonyHost

    install_host(HarmonyHost())

    ProcessContext.port = random.randrange(49152, 65535)
    os.environ["AYON_HARMONY_PORT"] = str(ProcessContext.port)
    ProcessContext.application_path = application_path

    # Launch Harmony.
    setup_startup_scripts()
    check_libs()

    if len(args) > 0 and (scene_path := Path(args[-1])).suffix == ".zip":
        launch_zip_file(scene_path)

    open_workfile_app = env_value_to_bool("AYON_HARMONY_WORKFILES_ON_LAUNCH")
    workfile_already_open = ProcessContext.workfile_path
    if is_headless_mode_enabled():
        if not workfile_already_open:
            open_empty_workfile()
    elif open_workfile_app or not workfile_already_open:
        ProcessContext.workfile_tool = host_tools.get_tool_by_name(
            "workfiles"
        )
        host_tools.show_workfiles(save=True)
        ProcessContext.execute_in_main_thread(check_workfiles_tool)

launch_zip_file(filepath)

Launch a Harmony application instance with the provided zip file.

Parameters:

Name Type Description Default
filepath str

Path to file.

required
Source code in client/ayon_harmony/api/lib.py
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
def launch_zip_file(filepath):
    """Launch a Harmony application instance with the provided zip file.

    Args:
        filepath (str): Path to file.
    """
    # Close existing scene.
    if ProcessContext.pid:
        os.kill(ProcessContext.pid, signal.SIGTERM)

    # Stop server.
    if ProcessContext.server:
        ProcessContext.server.stop()

    # Launch AYON server.
    ProcessContext.server = Server(ProcessContext.port)
    ProcessContext.server.start()
    # thread = threading.Thread(target=self.server.start)
    # thread.daemon = True
    # thread.start()

    # Save workfile path for later.
    ProcessContext.workfile_path = filepath

    # Unzip the scene file and get the .xstage path
    try:
        scene_path = unzip_scene_file(filepath)
    except Exception as e:
        print(f"Error unzipping scene file: {e}")
        ProcessContext.server.stop()
        return

    print("Launching {}".format(scene_path))
    # QUESTION Could we use 'run_detached_process' from 'ayon_core.lib'?
    kwargs = {}
    if (
        platform.system().lower() == "windows"
        and not is_using_ayon_console()
    ):
        kwargs.update({
            "creationflags": subprocess.CREATE_NO_WINDOW,
            "stdout": subprocess.DEVNULL,
            "stderr": subprocess.DEVNULL
        })

    process = subprocess.Popen(
        [ProcessContext.application_path, scene_path],
        **kwargs
    )
    ProcessContext.pid = process.pid
    ProcessContext.process = process
    ProcessContext.stdout_broker.host_connected()

localize_file(filepath)

Copy file to local temp location for faster processing.

Parameters:

Name Type Description Default
filepath str

Path to the file (possibly on network).

required

Returns:

Name Type Description
str

Path to localized file, or original if already local.

Source code in client/ayon_harmony/api/lib.py
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
def localize_file(filepath):
    """Copy file to local temp location for faster processing.

    Args:
        filepath (str): Path to the file (possibly on network).

    Returns:
        str: Path to localized file, or original if already local.
    """
    local_scene_dir_path = os.path.join(
        os.path.expanduser("~"), ".ayon", "harmony"
    )
    os.makedirs(local_scene_dir_path, exist_ok=True)

    local_zip = os.path.join(local_scene_dir_path, os.path.basename(filepath))
    log.info(f"Copying {filepath} to {local_zip}")

    copy_with_progress(filepath, local_zip)
    return local_zip

maintained_nodes_state(nodes)

Maintain nodes states during context.

Source code in client/ayon_harmony/api/lib.py
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
@contextlib.contextmanager
def maintained_nodes_state(nodes):
    """Maintain nodes states during context."""
    # Collect current state.
    states = send(
        {
            "function": "AyonHarmonyAPI.areEnabled", "args": nodes
        })["result"]

    # Disable all nodes.
    send(
        {
            "function": "AyonHarmonyAPI.disableNodes", "args": nodes
        })

    try:
        yield
    finally:
        send(
            {
                "function": "AyonHarmonyAPI.setState",
                "args": [nodes, states]
            })

on_file_changed(path, threaded=True)

Threaded zipping and move of the project directory.

This method is called when the .xstage file is changed.

Source code in client/ayon_harmony/api/lib.py
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
def on_file_changed(path, threaded=True):
    """Threaded zipping and move of the project directory.

    This method is called when the `.xstage` file is changed.
    """
    log.debug("File changed: " + path)

    if ProcessContext.workfile_path is None:
        return

    if threaded:
        thread = threading.Thread(
            target=zip_and_move,
            args=(os.path.dirname(path), ProcessContext.workfile_path)
        )
        thread.start()
    else:
        zip_and_move(os.path.dirname(path), ProcessContext.workfile_path)

read(node_id)

Read object metadata in to a dictionary.

Parameters:

Name Type Description Default
node_id str

Path to node or id of object.

required

Returns:

Type Description

dict

Source code in client/ayon_harmony/api/lib.py
729
730
731
732
733
734
735
736
737
738
739
740
741
742
def read(node_id):
    """Read object metadata in to a dictionary.

    Args:
        node_id (str): Path to node or id of object.

    Returns:
        dict
    """
    scene_data = get_scene_data()
    if node_id in scene_data:
        return scene_data[node_id]

    return {}

remove(node_id)

Remove node data from scene metadata.

Parameters:

Name Type Description Default
node_id str

full name (eg. 'Top/renderAnimation')

required
Source code in client/ayon_harmony/api/lib.py
745
746
747
748
749
750
751
752
753
754
def remove(node_id):
    """
        Remove node data from scene metadata.

        Args:
            node_id (str): full name (eg. 'Top/renderAnimation')
    """
    data = get_scene_data()
    del data[node_id]
    set_scene_data(data)

rename_node(node_name, new_name)

Rename node name

Source code in client/ayon_harmony/api/lib.py
977
978
979
980
981
982
983
984
def rename_node(node_name, new_name):
    """ Rename node name """
    send(
        {
            "function": "AyonHarmony.renameNode",
            "args": [node_name, new_name]
        }
    )

save_scene(zip_and_move=True)

Save the Harmony scene safely.

The built-in (to AYON) background zip and moving of the Harmony scene folder, interferes with server/client communication by sending two requests at the same time. This only happens when sending "scene.saveAll()". This method prevents this double request and safely saves the scene.

Source code in client/ayon_harmony/api/lib.py
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
def save_scene(zip_and_move=True):
    """Save the Harmony scene safely.

    The built-in (to AYON) background zip and moving of the Harmony scene
    folder, interferes with server/client communication by sending two
    requests at the same time. This only happens when sending
    "scene.saveAll()". This method prevents this double request and safely
    saves the scene.

    """
    # Need to turn off the background watcher else the communication with
    # the server gets spammed with two requests at the same time.
    scene_path = send(
        {"function": "AyonHarmonyAPI.saveScene"})["result"]

    # # Manually update the remote file.
    if zip_and_move:
        on_file_changed(scene_path, threaded=False)

    # Re-enable the background watcher.
    send({"function": "AyonHarmonyAPI.enableFileWather"})

save_scene_as(filepath)

Save Harmony scene as filepath.

Source code in client/ayon_harmony/api/lib.py
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
def save_scene_as(filepath):
    """Save Harmony scene as `filepath`."""
    scene_dir = os.path.dirname(filepath)
    destination = os.path.join(
        os.path.dirname(ProcessContext.workfile_path),
        os.path.splitext(os.path.basename(filepath))[0] + ".zip"
    )

    if os.path.exists(scene_dir):
        try:
            shutil.rmtree(scene_dir)
        except Exception as e:
            log.error(f"Cannot remove {scene_dir}")
            raise Exception(f"Cannot remove {scene_dir}") from e

    send(
        {"function": "scene.saveAs", "args": [scene_dir]}
    )["result"]

    zip_and_move(scene_dir, destination)

    ProcessContext.workfile_path = destination

    send(
        {"function": "AyonHarmonyAPI.addPathToWatcher", "args": filepath}
    )

select_nodes(nodes)

Selects nodes in Node View

Source code in client/ayon_harmony/api/lib.py
827
828
829
830
831
832
833
834
def select_nodes(nodes):
    """ Selects nodes in Node View """
    _ = send(
        {
            "function": "AyonHarmonyAPI.selectNodes",
            "args": nodes
        }
    )

send(request)

Public method for sending requests to Harmony.

Source code in client/ayon_harmony/api/lib.py
822
823
824
def send(request):
    """Public method for sending requests to Harmony."""
    return ProcessContext.server.send(request)

set_scene_data(data)

Write scene data to metadata.

Parameters:

Name Type Description Default
data dict

Data to write.

required
Source code in client/ayon_harmony/api/lib.py
714
715
716
717
718
719
720
721
722
723
724
725
726
def set_scene_data(data):
    """Write scene data to metadata.

    Args:
        data (dict): Data to write.

    """
    # Write scene data.
    send(
        {
            "function": "AyonHarmonyAPI.setSceneData",
            "args": data
        })

setup_startup_scripts()

Manages installation of ayon's TB_sceneOpened.js for Harmony launch.

If a studio already has defined "TOONBOOM_GLOBAL_SCRIPT_LOCATION", copies the TB_sceneOpened.js to that location if the file is different. Otherwise, will set the env var to point to the ayon/harmony folder.

Admins should be aware that this will overwrite TB_sceneOpened in the "TOONBOOM_GLOBAL_SCRIPT_LOCATION", and that if they want to have additional logic, they will need to one of the following: * Create a Harmony package to manage startup logic * Use TB_sceneOpenedUI.js instead to manage startup logic * Add their startup logic to ayon/harmony/TB_sceneOpened.js

Source code in client/ayon_harmony/api/lib.py
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
def setup_startup_scripts():
    """Manages installation of ayon's TB_sceneOpened.js for Harmony launch.

    If a studio already has defined "TOONBOOM_GLOBAL_SCRIPT_LOCATION", copies
    the TB_sceneOpened.js to that location if the file is different.
    Otherwise, will set the env var to point to the ayon/harmony folder.

    Admins should be aware that this will overwrite TB_sceneOpened in the
    "TOONBOOM_GLOBAL_SCRIPT_LOCATION", and that if they want to have additional
    logic, they will need to one of the following:
        * Create a Harmony package to manage startup logic
        * Use TB_sceneOpenedUI.js instead to manage startup logic
        * Add their startup logic to ayon/harmony/TB_sceneOpened.js
    """
    ayon_host_dir = os.path.join(HARMONY_ADDON_ROOT, "api")
    startup_js = "TB_sceneOpened.js"

    env_location = os.getenv("TOONBOOM_GLOBAL_SCRIPT_LOCATION")
    if not env_location:
        os.environ["TOONBOOM_GLOBAL_SCRIPT_LOCATION"] = ayon_host_dir
        return

    ayon_harmony_startup = os.path.join(ayon_host_dir, startup_js)
    env_harmony_startup = os.path.join(env_location, startup_js)

    # Check if destination file exists or if files are the same
    if (
        os.path.exists(env_harmony_startup)
        and filecmp.cmp(ayon_harmony_startup, env_harmony_startup)
    ):
        return

    try:
        shutil.copy(ayon_harmony_startup, env_harmony_startup)
    except Exception:
        log.warning(
            f"Failed to copy {ayon_harmony_startup} to {env_harmony_startup}!"
            " Defaulting to AYON's TOONBOOM_GLOBAL_SCRIPT_LOCATION.",
            exc_info=True
        )

        os.environ["TOONBOOM_GLOBAL_SCRIPT_LOCATION"] = ayon_host_dir

show(tool_name)

Call show on "module_name".

This allows to make a QApplication ahead of time and always "exec_" to prevent crashing.

Parameters:

Name Type Description Default
module_name str

Name of module to call "show" on.

required
Source code in client/ayon_harmony/api/lib.py
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
def show(tool_name):
    """Call show on "module_name".

    This allows to make a QApplication ahead of time and always "exec_" to
    prevent crashing.

    Args:
        module_name (str): Name of module to call "show" on.

    """
    # Requests often get doubled up when showing tools, so we wait a second
    #   for requests to be received properly.
    time.sleep(1)

    kwargs = {}
    if tool_name == "loader":
        kwargs["use_context"] = True
    elif tool_name == "publisher":
        kwargs["tab"] = "publish"
    elif tool_name == "creator":
        tool_name = "publisher"
        kwargs["tab"] = "create"

    ProcessContext.execute_in_main_thread(
        lambda: host_tools.show_tool_by_name(tool_name, **kwargs)
    )

    # Required return statement.
    return "nothing"

signature(postfix='func')

Return random ECMA6 compatible function name.

Parameters:

Name Type Description Default
postfix str

name to append to random string.

'func'

Returns: str: random function name.

Source code in client/ayon_harmony/api/lib.py
110
111
112
113
114
115
116
117
118
119
def signature(postfix="func") -> str:
    """Return random ECMA6 compatible function name.

    Args:
        postfix (str): name to append to random string.
    Returns:
        str: random function name.

    """
    return "f{}_{}".format(str(uuid4()).replace("-", "_"), postfix)

unzip_scene_file(filepath, headless=False)

Unzip a Harmony scene file and return the path to the .xstage file.

Parameters:

Name Type Description Default
filepath str

Path to the zip file.

required
headless bool

If True, run without any UI interaction. When a local cache exists with the same or newer timestamp, the local version will be used automatically. Defaults to False.

False

Returns:

Name Type Description
str str

Path to the .xstage file.

Raises:

Type Description
Exception

If no .xstage file is found or if the working folder cannot be deleted.

Source code in client/ayon_harmony/api/lib.py
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
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
def unzip_scene_file(filepath: str, headless: bool = False) -> str:
    """Unzip a Harmony scene file and return the path to the .xstage file.

    Args:
        filepath (str): Path to the zip file.
        headless (bool): If True, run without any UI interaction. When a
            local cache exists with the same or newer timestamp, the local
            version will be used automatically. Defaults to False.

    Returns:
        str: Path to the .xstage file.

    Raises:
        Exception: If no .xstage file is found or if the working
            folder cannot be deleted.

    """
    print(f"Localizing {filepath}")

    local_scene_dir_path = Path(get_local_harmony_path(filepath))
    scene_path = local_scene_dir_path.joinpath(
        f"{local_scene_dir_path.name}.xstage"
    )

    unzip = True
    if scene_path.exists():
        # Check remote scene is newer than local.
        if scene_path.stat().st_mtime < Path(filepath).stat().st_mtime:
            # Remote is newer, delete local and unzip
            try:
                shutil.rmtree(local_scene_dir_path)
            except Exception as e:
                log.error(e)
                raise Exception(
                    f"Cannot delete working folder: {local_scene_dir_path}"
                ) from e
            unzip = True
        elif headless:
            # Local is newer or same timestamp - use local cache automatically
            log.info(
                "Headless mode: local cache is newer or same timestamp "
                "as server version. Using local cache."
            )
            unzip = False
        else:
            # Local is newer or same timestamp - ask user
            msg_box = QtWidgets.QMessageBox()
            msg_box.setStyleSheet(style.load_stylesheet())
            msg_box.setIcon(QtWidgets.QMessageBox.Question)
            msg_box.setWindowTitle("Local cache of version exists")
            msg_box.setText(
                "A cached version of this scene exists that is newer or "
                "with the same timestamp as the server version."
            )
            msg_box.setInformativeText(
                "Do you want to use the local file or "
                "re-cache from the server?"
            )
            msg_box.setStandardButtons(
                QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No
            )
            msg_box.setDefaultButton(QtWidgets.QMessageBox.Yes)

            msg_box.button(QtWidgets.QMessageBox.Yes).setText("Use Local")
            msg_box.button(QtWidgets.QMessageBox.No).setText("From Server")

            msg_box.setModal(True)

            result = msg_box.exec_()

            if result == QtWidgets.QMessageBox.No:
                try:
                    shutil.rmtree(local_scene_dir_path)
                except Exception as e:
                    log.error(e)
                    raise Exception(
                       f"Cannot delete working folder '{local_scene_dir_path}'"
                    ) from e
                unzip = True
            else:
                unzip = False

    if unzip:
        filepath = localize_file(filepath)
        with _ZipFile(filepath, "r") as zip_ref:
            names = zip_ref.namelist()
            main_name = next(
                Path(name).stem
                for name in names
                if name.endswith(".xstage")
            )

            # Detect if the archive is wrapped in a single root directory
            # named after `main_name`. When it is, we extract into the
            # parent of the local scene dir so the (renamed) root dir
            # becomes the local scene dir itself.
            has_root_dir = all(
                name == f"{main_name}/"
                or name.startswith(f"{main_name}/")
                for name in names
            )
            extract_root = (
                local_scene_dir_path.parent
                if has_root_dir
                else local_scene_dir_path
            )
            new_name = local_scene_dir_path.name
            root_prefix = f"{main_name}/"

            def _rename_top_level_file(name):
                if "/" not in name and Path(name).stem == main_name:
                    return f"{new_name}{Path(name).suffix}"
                return name

            for zip_info in zip_ref.infolist():
                if has_root_dir:
                    # Root-dir archives are handled by applying the same
                    # top-level file rename one level deeper and then
                    # reattaching the renamed root directory prefix.
                    relative_name = zip_info.filename[len(root_prefix):]
                    relative_name = _rename_top_level_file(relative_name)
                    zip_info.filename = f"{new_name}/{relative_name}"
                else:
                    zip_info.filename = _rename_top_level_file(
                        zip_info.filename
                    )

                zip_ref.extract(zip_info, extract_root)
        scene_path = next(local_scene_dir_path.glob("*.xstage"), None)

    if not scene_path:
        raise Exception("No xstage file was found.")

    return scene_path.as_posix()

zip_and_move(source, destination)

Zip a directory and move to destination.

Parameters:

Name Type Description Default
source str

Directory to zip and move to destination.

required
destination str

Destination file path to zip file.

required
Source code in client/ayon_harmony/api/lib.py
609
610
611
612
613
614
615
616
617
618
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
def zip_and_move(source, destination):
    """Zip a directory and move to `destination`.

    Args:
        source (str): Directory to zip and move to destination.
        destination (str): Destination file path to zip file.

    """
    zip_file = os.path.basename(source) + ".zip"
    zip_path = os.path.join(os.path.dirname(source), zip_file)

    file_list = []
    for root, dirs, files in os.walk(source):
        for file in files:
            file_path = os.path.join(root, file)
            arcname = os.path.relpath(file_path, source)
            file_list.append((file_path, arcname))

    progress = QtWidgets.QProgressDialog(
        "Archiving scene files...",
        None,
        0,
        max(1, len(file_list))
    )
    progress.setStyleSheet(style.load_stylesheet())
    progress.setWindowTitle("Creating Archive")
    progress.setWindowModality(QtCore.Qt.WindowModal)
    progress.setMinimumDuration(0)
    progress.setCancelButton(None)

    try:
        with _ZipFile(zip_path, 'w', zipfile.ZIP_STORED) as zipf:
            last_process_events = time.monotonic()
            for idx, (file_path, arcname) in enumerate(file_list):
                zipf.write(file_path, arcname)
                progress.setValue(idx + 1)
                now = time.monotonic()
                if now - last_process_events >= 0.05:
                    QtWidgets.QApplication.processEvents(
                        QtCore.QEventLoop.AllEvents, 50
                    )
                    last_process_events = now

        with _ZipFile(zip_path) as zr:
            if zr.testzip() is not None:
                raise Exception("File archive is corrupted.")

        copy_with_progress(zip_path, destination)
        os.remove(zip_path)

    except Exception:
        if os.path.exists(zip_path):
            os.remove(zip_path)
        raise
    finally:
        progress.close()

    log.debug(f"Saved '{source}' to '{destination}'")