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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
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
274
275
276
277
278
279
280
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
315
316
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
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
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
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
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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
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
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896 | class ApplicationsAddon(BaseServerAddon):
settings_model = ApplicationsAddonSettings
# TODO remove this attribute when attributes support is removed
has_attributes = True
def initialize(self):
EventStream.subscribe(
"bundle.updated",
self._on_bundle_updated,
all_nodes=False,
)
self.add_endpoint(
"icons/{filename}",
self._get_icon,
method="GET",
)
self.add_endpoint(
"customIcons",
self._get_custom_icons,
method="GET",
)
self.add_endpoint(
"customIcons/{filename}",
self._upload_custom_icon,
method="POST",
)
self.add_endpoint(
"customIcons/{filename}",
self._upload_custom_icon,
method="PUT",
)
self.add_endpoint(
"customIcons/{filename}",
self._get_custom_icon,
method="GET",
)
self.add_endpoint(
"customIcons/{filename}",
self._delete_custom_icon,
method="DELETE",
)
self.add_endpoint(
"apps",
self._get_applications_endpoint,
method="GET",
)
self.add_endpoint(
"apps/{project_name}",
self._get_applications_endpoint,
method="GET",
)
self.add_endpoint(
"apps/{project_name}/task/{task_id}",
self._get_task_applications_endpoint,
method="GET",
)
self.add_endpoint(
"tools",
self._get_tools_endpoint,
method="GET",
)
self.add_endpoint(
"tools/{project_name}",
self._get_tools_endpoint,
method="GET",
)
async def get_simple_actions(
self,
project_name: str | None = None,
variant: str = "production",
) -> list["SimpleActionManifest"]:
return await get_action_manifests(
self,
project_name=project_name,
variant=variant,
)
async def get_dynamic_actions(
self,
context: ActionContext,
variant: str = "production",
) -> list["DynamicActionManifest"]:
return await get_dynamic_action_manifests(
self,
context=context,
variant=variant,
)
async def execute_action(
self,
executor: "ActionExecutor",
) -> "ExecuteResponseModel":
"""Execute an action provided by the addon"""
context = executor.context
project_name = context.project_name
entity_id = context.entity_ids[0]
bundle_args = []
if executor.variant not in ("production", "staging"):
bundle_args = ["--bundle", executor.variant]
if executor.identifier == DEBUG_TERMINAL_ID:
args = [
"addon", "applications", "launch-debug-terminal",
"--project", project_name,
"--task-id", entity_id,
]
args.extend(bundle_args)
return await executor.get_launcher_action_response(
args=args
)
app_name = entity_id_arg = command = None
skip_last_workfile = None
if executor.identifier.startswith(IDENTIFIER_PREFIX):
app_name = executor.identifier.removeprefix(IDENTIFIER_PREFIX)
command = "launch-by-id"
entity_id_arg = "--task-id"
config = await self.get_action_config(
executor.identifier,
executor.context,
executor.user,
executor.variant,
)
skip_last_workfile = config.get("skip_last_workfile")
elif executor.identifier.startswith(IDENTIFIER_WORKFILE_PREFIX):
app_name = executor.identifier.removeprefix(
IDENTIFIER_WORKFILE_PREFIX
)
command = "launch-by-workfile-id"
entity_id_arg = "--workfile-id"
if not app_name:
return await executor.get_simple_response(
message="Failed to launch application."
" Unknown action identifier.",
success=False,
)
args = [
"addon", "applications", command,
"--app", app_name,
"--project", project_name,
entity_id_arg, entity_id,
]
args.extend(bundle_args)
if skip_last_workfile is not None:
args.extend([
"--use-last-workfile", str(int(not skip_last_workfile))
])
# 'get_launcher_response' is available since AYON 1.8.3
if hasattr(executor, "get_launcher_response"):
return await executor.get_launcher_response(
args=args,
message=f"Launching {app_name}."
)
# Backwards compatibility
return await executor.get_launcher_action_response(
args=args,
message=f"Launching {app_name}"
)
async def get_default_settings(self):
return self.get_settings_model()(**DEFAULT_VALUES)
async def create_action_config_hash(
self,
identifier: str,
context: ActionContext,
user: UserEntity,
variant: str,
) -> str:
"""Create a hash for action config store"""
if not identifier.startswith(IDENTIFIER_PREFIX):
return await super().create_action_config_hash(
identifier, context, user, variant
)
# Change identifier to only app name and one task id
identifier = identifier.removeprefix(IDENTIFIER_PREFIX)
hash_content = [
user.name,
identifier,
context.project_name,
context.entity_ids[0],
]
logger.trace(f"Creating config hash from {hash_content}")
return hash_data(hash_content)
async def set_action_config(
self,
identifier: str,
context: ActionContext,
user: UserEntity,
variant: str,
config: dict[str, Any],
) -> None:
if not identifier.startswith(IDENTIFIER_PREFIX):
await super().set_action_config(
identifier, context, user, variant, config
)
return
if not context.entity_ids:
return
# Unset 'skip_last_workfile' if it is set to 'False'
if config.get("skip_last_workfile") is False:
config.pop("skip_last_workfile")
identifier = identifier.removeprefix(IDENTIFIER_PREFIX)
for entity_id in context.entity_ids:
config_hash = hash_data([
user.name,
identifier,
context.project_name,
entity_id,
])
await set_action_config(
config_hash,
config,
addon_name=self.name,
addon_version=self.version,
identifier=identifier,
project_name=context.project_name,
user_name=user.name,
)
async def get_application_items(
self,
project_name: str | None,
variant: str,
*,
version: str | None = None,
) -> list[ApplicationItem]:
"""Get available applications for a project and variant.
Meant as api function for other addons that need access to tools for
a given project and variant. It can resolve which addon version
should be used and get the information for the context, or just
pass in specific version to get the information for.
In case the addon version does not support the functionality yet (or
anymore) it will try to guess it based on settings, or returns
empty list.
Args:
project_name (str): Project name.
variant (str): Variant name, e.g. "production" or "staging".
version (str | None): Addon version to get tools for. If not
provided, it will use the resolved addon version for the
context.
Returns:
list[ApplicationItem]: List of available applications
for the context.
"""
if version is not None:
addon = self._get_addon_version(version)
else:
addon = await self.get_addon_for_context(project_name, variant)
if addon is None:
return []
if addon is not self and hasattr(addon, "get_application_items"):
kwargs = dict(
variant=variant,
version=addon.version,
)
return await addon.get_application_items(project_name, **kwargs)
if project_name is None:
settings = await addon.get_studio_settings(variant=variant)
else:
settings = await addon.get_project_settings(
project_name, variant=variant
)
try:
return get_application_items(
settings.dict(),
version=addon.version,
fill_icon_url=True,
)
except Exception:
logger.trace(
"Failed to collect available applications for a task"
f" from applications addon '{addon.version}'."
)
return []
async def get_tool_items(
self,
project_name: str | None,
variant: str,
*,
version: str | None = None,
) -> list[ToolItem]:
"""Get available tools for a project and variant.
Meant as api function for other addons that need access to tools for
a given project and variant. It can resolve which addon version
should be used and get the information for the context, or just
pass in specific version to get the information for.
In case the addon version does not support the functionality yet (or
anymore) it will try to guess it based on settings, or returns
empty list.
Args:
project_name (str): Project name.
variant (str): Variant name, e.g. "production" or "staging".
version (str | None): Addon version to get tools for. If not
provided, it will use the resolved addon version for the
context.
Returns:
list[ToolItem]: List of available tools for the context.
"""
if version is not None:
addon = self._get_addon_version(version)
else:
addon = await self.get_addon_for_context(project_name, variant)
if addon is None:
return []
if addon is not self and hasattr(addon, "get_tool_items"):
return await addon.get_tool_items(
project_name, variant=variant, version=addon.version
)
if project_name is None:
settings = await addon.get_studio_settings(variant=variant)
else:
settings = await addon.get_project_settings(
project_name, variant=variant
)
try:
return get_tool_items(settings.dict())
except Exception:
logger.trace(
"Failed to collect available tools"
f" from applications addon '{addon.version}'."
)
return []
async def get_application_items_for_task(
self,
project_name: str,
task_id: str,
variant: str,
*,
version: str | None = None,
) -> list[ApplicationItem]:
if version is not None:
addon = self._get_addon_version(version)
else:
addon = await self.get_addon_for_context(project_name, variant)
if addon is None:
return []
if (
addon is not self
and hasattr(addon, "get_application_items_for_task")
):
return await addon.get_application_items_for_task(
project_name,
task_id=task_id,
variant=variant,
version=addon.version,
)
settings = await addon.get_project_settings(
project_name, variant=variant
)
settings_value = settings.dict()
task_entity = await TaskEntity.load(project_name, task_id)
output = []
try:
app_items = get_application_items(
settings_value,
version=addon.version,
fill_icon_url=True,
)
app_items_by_name = {
app_item.full_name: app_item
for app_item in app_items
}
app_names_by_task_type = get_app_names_by_task_type(
settings_value,
{task_entity.task_type},
app_items=app_items,
)
for app_name in app_names_by_task_type[task_entity.task_type]:
app_item = app_items_by_name[app_name]
output.append(app_item)
except Exception:
logger.trace(
"Failed to collect available applications for a task"
f" from applications addon '{addon.version}'."
)
return output
async def get_addon_for_context(
self, project_name: str | None, variant: str
) -> BaseServerAddon | None:
"""Find applications addon version for a given context."""
if (
project_name is None
or variant not in ("production", "staging")
or not await has_project_bundle(project_name, variant=variant)
):
return await self._get_studio_bundle_addon(variant)
addons = await get_project_bundle_addons(
project_name, variant=variant
)
version = addons.get(self.name)
if not version or version == "__disable__":
return None
if version == "__inherit__":
return await self._get_studio_bundle_addon(variant)
return self._get_addon_version(version)
async def get_applications_settings_enum(
self,
*,
project_name: str | None = None,
settings_variant: str = None,
):
"""Helper that can be used to get applications enum for settings.
Example:
from ayon_server.addons import AddonLibrary
async def apps_enum(project_name, addon, settings_variant):
addon_library = AddonLibrary.getinstance()
app_addons = addon_library.data.get("applications") or {}
addon = app_addons.latest
if hasattr(addon, "get_applications_settings_enum"):
return await addon.get_applications_settings_enum(
project_name=project_name,
settings_variant=settings_variant,
)
return []
class SomeSettingsModel(BaseModel):
application: str = SettingsField(
default_factory=list,
title="Applications",
enum_resolver=apps_enum,
)
"""
if settings_variant is None:
settings_variant = "production"
addon = await self.get_addon_for_context(
project_name, settings_variant
)
if addon is self:
return await applications_enum(
project_name=project_name,
addon=addon,
settings_variant=settings_variant,
)
if hasattr(addon, "get_applications_settings_enum"):
return await addon.get_applications_settings_enum(
project_name=project_name,
settings_variant=settings_variant,
)
try:
return await applications_enum(
project_name=project_name,
addon=addon,
settings_variant=settings_variant,
)
except Exception:
log_traceback(
"Failed to get applications for"
f" Project: '{project_name}' Variant: '{settings_variant}'."
)
return []
async def get_applications_for_context(
self,
project_name: str | None,
variant: str,
) -> list[ApplicationItem]:
"""Get applications available for a given context.
DUPLICATE of 'get_application_items' method.
This method can be used by other addons to get applications available
for a given project and variant. It will return applications based
on variant and project bundle if project has any.
Will work only if the addon version is new enough to have
'get_application_items' method, otherwise it will return
empty list.
"""
return await self.get_application_items(
project_name,
variant,
)
async def get_tools_for_context(
self, project_name: str | None, variant: str
) -> list[ToolItem]:
"""Get tools available for a given context.
DUPLICATE of 'get_tool_items' method.
This method can be used by other addons to get tools available for
a given project and variant. It will return tools based on variant
and project bundle if project has any.
Will work only if the addon version is new enough to have
'get_tool_items' method, otherwise it will return empty list.
"""
return await self.get_tool_items(project_name, variant)
# --------------------------------------------
# Auto-fill of host_name in workfiles entities
# --------------------------------------------
async def _workfile_entities_auto_filled(self) -> bool:
async for _ in Postgres.iterate(
"SELECT * FROM public.addon_data"
" WHERE addon_name = $1 AND key = $2",
self.name,
"workfile_entities_host_name_filled",
):
return True
return False
async def _on_bundle_updated(
self, event: EventModel, *args, **kwargs
) -> None:
if await self._workfile_entities_auto_filled():
return
if not event.summary.get("isProduction"):
return
addons = event.payload.get("addons", {})
addon_version = addons.get(self.name)
if addon_version != self.version:
return
await self._autofill_workfile_entities()
async def _autofill_workfile_entities(self):
project_names = [
project.name
for project in await get_project_list()
]
for project_name in project_names:
query = f"""
SELECT id, attrib, path FROM project_{project_name}.workfiles
WHERE data->'host_name' IS NULL;
"""
workfile_entities = [
row
async for row in Postgres.iterate(query)
]
changes = []
for workfile_entity in workfile_entities:
ext = workfile_entity["attrib"].get("extension")
if not ext:
ext = os.path.splitext(workfile_entity["path"])[-1]
if not ext:
continue
mapped_host_name = EXT_TO_HOST_MAPPING.get(ext.lower())
if mapped_host_name:
changes.append((workfile_entity["id"], mapped_host_name))
for chunk in create_chunks(changes):
async with Postgres.transaction():
for (workfile_id, host_name) in chunk:
await Postgres.execute(
f"UPDATE project_{project_name}.workfiles"
" SET data = jsonb_set(data, '{host_name}', $1)"
" WHERE id = $2;",
host_name,
workfile_id
)
await Postgres.execute(
"INSERT INTO public.addon_data"
" (addon_name, addon_version, key, data)"
" VALUES ($1, $2, $3, $4)",
self.name,
self.version,
"workfile_entities_host_name_filled",
{
"project_names": project_names,
}
)
def _get_addon_version(self, version: str) -> BaseServerAddon | None:
if self.version == version:
return self
addon_library = AddonLibrary.getinstance()
if (addon_def := addon_library.data.get(self.name)) is None:
return None
return addon_def.get(version)
async def _get_studio_bundle_addon(
self, variant: str
) -> BaseServerAddon | None:
addon_library = AddonLibrary.getinstance()
if (addon_def := addon_library.data.get(self.name)) is None:
return None
addon_versions_by_name = (
await addon_library.get_addon_versions_by_variant(variant)
)
version = addon_versions_by_name.get(self.name)
return addon_def.get(version)
async def _get_applications_endpoint(
self,
project_name: str | None = None,
variant: str | None = Query(None, title="Settings Variant"),
version: str | None = Query(None, title="Addon version"),
):
if variant is None:
variant = "production"
app_items = await self.get_application_items(
project_name=project_name,
variant=variant,
version=version,
)
return {
"applications": [app_item for app_item in app_items]
}
async def _get_task_applications_endpoint(
self,
project_name: str,
task_id: str,
variant: str | None = Query(None, title="Settings Variant"),
version: str | None = Query(None, title="Addon version"),
):
if variant is None:
variant = "production"
app_items = await self.get_application_items_for_task(
project_name, task_id=task_id, variant=variant, version=version
)
return {
"applications": [app_item for app_item in app_items]
}
async def _get_tools_endpoint(
self,
project_name: str | None = None,
variant: str | None = Query(None, title="Settings Variant"),
version: str | None = Query(None, title="Addon version"),
):
if variant is None:
variant = "production"
tool_items = await self.get_tool_items(
project_name, variant=variant, version=version
)
return {
"tools": [tool_item for tool_item in tool_items]
}
def _get_custom_icons_dir(self) -> Path:
current_dir = Path(os.path.abspath(__file__)).parent
return current_dir.parent.parent / "custom_icons"
async def _get_icon(self, filename: str) -> FileResponse:
filename = os.path.basename(filename)
custom_icons_dir = self._get_custom_icons_dir()
if custom_icons_dir.exists():
path = custom_icons_dir / filename
if path.is_file():
return FileResponse(path)
current_dir = Path(os.path.abspath(__file__)).parent
path = current_dir.parent / "public" / "icons" / filename
if not path.is_file():
raise HTTPException(
status_code=404,
detail=f"Icon '{filename}' not found"
)
return FileResponse(path)
async def _upload_custom_icon(
self,
request: Request,
user: CurrentUser,
filename: str,
) -> dict[str, bool]:
filename = os.path.basename(filename)
custom_icons_dir = self._get_custom_icons_dir()
custom_icons_dir.mkdir(parents=True, exist_ok=True)
filepath = custom_icons_dir / filename
try:
async with aiofiles.open(str(filepath), "wb") as stream:
async for chunk in request.stream():
await stream.write(chunk)
except Exception:
if filepath.exists():
filepath.unlink()
raise HTTPException(
status_code=500,
detail={"success": False},
)
return {"success": True}
def _get_custom_icons(self) -> dict[str, list[dict[str, str]]]:
custom_icons_dir = self._get_custom_icons_dir()
filenames = []
if custom_icons_dir.exists():
for item in custom_icons_dir.iterdir():
if item.is_file():
filenames.append({"filename": item.name})
return {"icons": filenames}
def _get_custom_icon(self, filename: str) -> FileResponse:
filename = os.path.basename(filename)
custom_icons_dir = self._get_custom_icons_dir()
filepath = custom_icons_dir / filename
if not filepath.is_file():
raise HTTPException(
status_code=404,
detail=f"File '{filename}' not found"
)
return FileResponse(filepath)
def _delete_custom_icon(self, filename: str) -> dict[str, bool]:
filename = os.path.basename(filename)
custom_icons_dir = self._get_custom_icons_dir()
filepath = custom_icons_dir / filename
if not filepath.is_file():
raise HTTPException(
status_code=404,
detail={
"success": False,
"message": f"File '{filename}' not found",
}
)
filepath.unlink()
return {"success": True}
|