-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathlinks.py
More file actions
739 lines (622 loc) · 24 KB
/
Copy pathlinks.py
File metadata and controls
739 lines (622 loc) · 24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
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
from __future__ import annotations
import collections
import typing
from typing import Optional, Any, Iterable
from ayon_api.graphql_queries import (
folders_graphql_query,
tasks_graphql_query,
products_graphql_query,
versions_graphql_query,
representations_graphql_query,
)
from .base import BaseServerAPI
if typing.TYPE_CHECKING:
from ayon_api.typing import LinkDirection, CreateLinkData
class LinksAPI(BaseServerAPI):
def get_full_link_type_name(
self, link_type_name: str, input_type: str, output_type: str
) -> str:
"""Calculate full link type name used for query from server.
Args:
link_type_name (str): Type of link.
input_type (str): Input entity type of link.
output_type (str): Output entity type of link.
Returns:
str: Full name of link type used for query from server.
"""
return "|".join([link_type_name, input_type, output_type])
def get_link_types(self, project_name: str) -> list[dict[str, Any]]:
"""All link types available on a project.
Example output:
[
{
"name": "reference|folder|folder",
"link_type": "reference",
"input_type": "folder",
"output_type": "folder",
"data": {}
}
]
Args:
project_name (str): Name of project where to look for link types.
Returns:
list[dict[str, Any]]: Link types available on project.
"""
response = self.get(f"projects/{project_name}/links/types")
response.raise_for_status()
return response.data["types"]
def get_link_type(
self,
project_name: str,
link_type_name: str,
input_type: str,
output_type: str,
) -> Optional[dict[str, Any]]:
"""Get link type data.
There is not dedicated REST endpoint to get single link type,
so method 'get_link_types' is used.
Example output:
{
"name": "reference|folder|folder",
"link_type": "reference",
"input_type": "folder",
"output_type": "folder",
"data": {}
}
Args:
project_name (str): Project where link type is available.
link_type_name (str): Name of link type.
input_type (str): Input entity type of link.
output_type (str): Output entity type of link.
Returns:
Optional[dict[str, Any]]: Link type information.
"""
full_type_name = self.get_full_link_type_name(
link_type_name, input_type, output_type
)
for link_type in self.get_link_types(project_name):
if link_type["name"] == full_type_name:
return link_type
return None
def create_link_type(
self,
project_name: str,
link_type_name: str,
input_type: str,
output_type: str,
data: Optional[dict[str, Any]] = None,
) -> None:
"""Create or update link type on server.
Warning:
Because PUT is used for creation it is also used for update.
Args:
project_name (str): Project where link type is created.
link_type_name (str): Name of link type.
input_type (str): Input entity type of link.
output_type (str): Output entity type of link.
data (Optional[dict[str, Any]]): Additional data related to link.
Raises:
HTTPRequestError: Server error happened.
"""
if data is None:
data = {}
full_type_name = self.get_full_link_type_name(
link_type_name, input_type, output_type
)
response = self.put(
f"projects/{project_name}/links/types/{full_type_name}",
**data
)
response.raise_for_status()
def delete_link_type(
self,
project_name: str,
link_type_name: str,
input_type: str,
output_type: str,
) -> None:
"""Remove link type from project.
Args:
project_name (str): Project where link type is created.
link_type_name (str): Name of link type.
input_type (str): Input entity type of link.
output_type (str): Output entity type of link.
Raises:
HTTPRequestError: Server error happened.
"""
full_type_name = self.get_full_link_type_name(
link_type_name, input_type, output_type
)
response = self.delete(
f"projects/{project_name}/links/types/{full_type_name}"
)
response.raise_for_status()
def make_sure_link_type_exists(
self,
project_name: str,
link_type_name: str,
input_type: str,
output_type: str,
data: Optional[dict[str, Any]] = None,
) -> None:
"""Make sure link type exists on a project.
Args:
project_name (str): Name of project.
link_type_name (str): Name of link type.
input_type (str): Input entity type of link.
output_type (str): Output entity type of link.
data (Optional[dict[str, Any]]): Link type related data.
"""
link_type = self.get_link_type(
project_name, link_type_name, input_type, output_type)
if (
link_type
and (data is None or data == link_type["data"])
):
return
self.create_link_type(
project_name, link_type_name, input_type, output_type, data
)
def create_link(
self,
project_name: str,
link_type_name: str,
input_id: str,
input_type: str,
output_id: str,
output_type: str,
link_name: Optional[str] = None,
data: Optional[dict[str, Any]] = None,
) -> CreateLinkResponseData:
"""Create link between 2 entities.
Link has a type which must already exists on a project.
Example output::
{
"id": "59a212c0d2e211eda0e20242ac120002"
}
Args:
project_name (str): Project where the link is created.
link_type_name (str): Type of link.
input_id (str): Input entity id.
input_type (str): Entity type of input entity.
output_id (str): Output entity id.
output_type (str): Entity type of output entity.
link_name (Optional[str]): Name of link.
data (Optional[dict[str, Any]]): Additional data to be stored
with the link.
Returns:
CreateLinkResponseData: Information about link.
Raises:
HTTPRequestError: Server error happened.
"""
full_link_type_name = self.get_full_link_type_name(
link_type_name, input_type, output_type)
kwargs = {
"input": input_id,
"output": output_id,
"linkType": full_link_type_name,
}
if link_name:
kwargs["name"] = link_name
if data:
kwargs["data"] = data
response = self.post(
f"projects/{project_name}/links", **kwargs
)
response.raise_for_status()
return response.data
def create_links(
self,
project_name: str,
links: list[dict[str, Any]],
) -> None:
"""Create multiple links in a single request.
Example of link data::
[
{
"input": "59a212c0d2e211eda0e20242ac120001",
"output": "59a212c0d2e211eda0e20242ac120002",
"linkType": "reference|folder|folder",
"name": "my_link",
"data": {"key": "value"}
}
]
Args:
project_name (str): Project where links are created.
links (list[dict[str, Any]]): List of link data.
Raises:
ValueError: Link data is invalid.
"""
if not links:
return
for link in links:
self._validate_link_data(link)
if self.get_server_version_tuple() < (1, 15, 8):
for link in links:
link_type, in_type, out_type = link["linkType"].split("|")
self.create_link(
project_name,
link_type,
link["input"],
in_type,
link["output"],
out_type,
link_name=link.get("name") or None,
data=link.get("data") or None,
)
return
response = self.post(
f"projects/{project_name}/links/bulk",
links=links
)
response.raise_for_status()
def delete_link(self, project_name: str, link_id: str) -> None:
"""Remove link by id.
Args:
project_name (str): Project where link exists.
link_id (str): Id of link.
Raises:
HTTPRequestError: Server error happened.
"""
response = self.delete(
f"projects/{project_name}/links/{link_id}"
)
response.raise_for_status()
def get_entities_links(
self,
project_name: str,
entity_type: str,
entity_ids: Optional[Iterable[str]] = None,
link_types: Optional[Iterable[str]] = None,
link_direction: Optional[LinkDirection] = None,
link_names: Optional[Iterable[str]] = None,
link_name_regex: Optional[str] = None,
) -> dict[str, list[dict[str, Any]]]:
"""Helper method to get links from server for entity types.
.. highlight:: text
.. code-block:: text
Example output:
{
"59a212c0d2e211eda0e20242ac120001": [
{
"id": "59a212c0d2e211eda0e20242ac120002",
"linkType": "reference",
"description": "reference link between folders",
"projectName": "my_project",
"author": "frantadmin",
"entityId": "b1df109676db11ed8e8c6c9466b19aa8",
"entityType": "folder",
"direction": "out"
},
...
],
...
}
Args:
project_name (str): Project where links are.
entity_type (Literal["folder", "task", "product",
"version", "representations"]): Entity type.
entity_ids (Optional[Iterable[str]]): Ids of entities for which
links should be received.
link_types (Optional[Iterable[str]]): Link type filters.
link_direction (Optional[Literal["in", "out"]]): Link direction
filter.
link_names (Optional[Iterable[str]]): Link name filters.
link_name_regex (Optional[str]): Regex filter for link name.
Returns:
dict[str, list[dict[str, Any]]]: Link info by entity ids.
"""
if entity_type == "folder":
query_func = folders_graphql_query
id_filter_key = "folderIds"
project_sub_key = "folders"
elif entity_type == "task":
query_func = tasks_graphql_query
id_filter_key = "taskIds"
project_sub_key = "tasks"
elif entity_type == "product":
query_func = products_graphql_query
id_filter_key = "productIds"
project_sub_key = "products"
elif entity_type == "version":
query_func = versions_graphql_query
id_filter_key = "versionIds"
project_sub_key = "versions"
elif entity_type == "representation":
query_func = representations_graphql_query
id_filter_key = "representationIds"
project_sub_key = "representations"
else:
raise ValueError("Unknown type \"{}\". Expected {}".format(
entity_type,
", ".join(
("folder", "task", "product", "version", "representation")
)
))
output = collections.defaultdict(list)
filters = {
"projectName": project_name
}
if entity_ids is not None:
entity_ids = set(entity_ids)
if not entity_ids:
return output
filters[id_filter_key] = list(entity_ids)
if not self._prepare_link_filters(
filters, link_types, link_direction, link_names, link_name_regex
):
return output
link_fields = {"id", "links"}
self._prepare_link_fields(link_fields)
query = query_func(link_fields)
for attr, filter_value in filters.items():
query.set_variable_value(attr, filter_value)
for parsed_data in query.continuous_query(self):
for entity in parsed_data["project"][project_sub_key]:
entity_id = entity["id"]
output[entity_id].extend(entity["links"])
return output
def get_folders_links(
self,
project_name: str,
folder_ids: Optional[Iterable[str]] = None,
link_types: Optional[Iterable[str]] = None,
link_direction: Optional[LinkDirection] = None,
) -> dict[str, list[dict[str, Any]]]:
"""Query folders links from server.
Args:
project_name (str): Project where links are.
folder_ids (Optional[Iterable[str]]): Ids of folders for which
links should be received.
link_types (Optional[Iterable[str]]): Link type filters.
link_direction (Optional[Literal["in", "out"]]): Link direction
filter.
Returns:
dict[str, list[dict[str, Any]]]: Link info by folder ids.
"""
return self.get_entities_links(
project_name, "folder", folder_ids, link_types, link_direction
)
def get_folder_links(
self,
project_name: str,
folder_id: str,
link_types: Optional[Iterable[str]] = None,
link_direction: Optional[LinkDirection] = None,
) -> list[dict[str, Any]]:
"""Query folder links from server.
Args:
project_name (str): Project where links are.
folder_id (str): Folder id for which links should be received.
link_types (Optional[Iterable[str]]): Link type filters.
link_direction (Optional[Literal["in", "out"]]): Link direction
filter.
Returns:
list[dict[str, Any]]: Link info of folder.
"""
return self.get_folders_links(
project_name, [folder_id], link_types, link_direction
)[folder_id]
def get_tasks_links(
self,
project_name: str,
task_ids: Optional[Iterable[str]] = None,
link_types: Optional[Iterable[str]] = None,
link_direction: Optional[LinkDirection] = None,
) -> dict[str, list[dict[str, Any]]]:
"""Query tasks links from server.
Args:
project_name (str): Project where links are.
task_ids (Optional[Iterable[str]]): Ids of tasks for which
links should be received.
link_types (Optional[Iterable[str]]): Link type filters.
link_direction (Optional[Literal["in", "out"]]): Link direction
filter.
Returns:
dict[str, list[dict[str, Any]]]: Link info by task ids.
"""
return self.get_entities_links(
project_name, "task", task_ids, link_types, link_direction
)
def get_task_links(
self,
project_name: str,
task_id: str,
link_types: Optional[Iterable[str]] = None,
link_direction: Optional[LinkDirection] = None,
) -> list[dict[str, Any]]:
"""Query task links from server.
Args:
project_name (str): Project where links are.
task_id (str): Task id for which links should be received.
link_types (Optional[Iterable[str]]): Link type filters.
link_direction (Optional[Literal["in", "out"]]): Link direction
filter.
Returns:
list[dict[str, Any]]: Link info of task.
"""
return self.get_tasks_links(
project_name, [task_id], link_types, link_direction
)[task_id]
def get_products_links(
self,
project_name: str,
product_ids: Optional[Iterable[str]] = None,
link_types: Optional[Iterable[str]] = None,
link_direction: Optional[LinkDirection] = None,
) -> dict[str, list[dict[str, Any]]]:
"""Query products links from server.
Args:
project_name (str): Project where links are.
product_ids (Optional[Iterable[str]]): Ids of products for which
links should be received.
link_types (Optional[Iterable[str]]): Link type filters.
link_direction (Optional[Literal["in", "out"]]): Link direction
filter.
Returns:
dict[str, list[dict[str, Any]]]: Link info by product ids.
"""
return self.get_entities_links(
project_name, "product", product_ids, link_types, link_direction
)
def get_product_links(
self,
project_name: str,
product_id: str,
link_types: Optional[Iterable[str]] = None,
link_direction: Optional[LinkDirection] = None,
) -> list[dict[str, Any]]:
"""Query product links from server.
Args:
project_name (str): Project where links are.
product_id (str): Product id for which links should be received.
link_types (Optional[Iterable[str]]): Link type filters.
link_direction (Optional[Literal["in", "out"]]): Link direction
filter.
Returns:
list[dict[str, Any]]: Link info of product.
"""
return self.get_products_links(
project_name, [product_id], link_types, link_direction
)[product_id]
def get_versions_links(
self,
project_name: str,
version_ids: Optional[Iterable[str]] = None,
link_types: Optional[Iterable[str]] = None,
link_direction: Optional[LinkDirection] = None,
) -> dict[str, list[dict[str, Any]]]:
"""Query versions links from server.
Args:
project_name (str): Project where links are.
version_ids (Optional[Iterable[str]]): Ids of versions for which
links should be received.
link_types (Optional[Iterable[str]]): Link type filters.
link_direction (Optional[Literal["in", "out"]]): Link direction
filter.
Returns:
dict[str, list[dict[str, Any]]]: Link info by version ids.
"""
return self.get_entities_links(
project_name, "version", version_ids, link_types, link_direction
)
def get_version_links(
self,
project_name: str,
version_id: str,
link_types: Optional[Iterable[str]] = None,
link_direction: Optional[LinkDirection] = None,
) -> list[dict[str, Any]]:
"""Query version links from server.
Args:
project_name (str): Project where links are.
version_id (str): Version id for which links should be received.
link_types (Optional[Iterable[str]]): Link type filters.
link_direction (Optional[Literal["in", "out"]]): Link direction
filter.
Returns:
list[dict[str, Any]]: Link info of version.
"""
return self.get_versions_links(
project_name, [version_id], link_types, link_direction
)[version_id]
def get_representations_links(
self,
project_name: str,
representation_ids: Optional[Iterable[str]] = None,
link_types: Optional[Iterable[str]] = None,
link_direction: Optional[LinkDirection] = None,
) -> dict[str, list[dict[str, Any]]]:
"""Query representations links from server.
Args:
project_name (str): Project where links are.
representation_ids (Optional[Iterable[str]]): Ids of
representations for which links should be received.
link_types (Optional[Iterable[str]]): Link type filters.
link_direction (Optional[Literal["in", "out"]]): Link direction
filter.
Returns:
dict[str, list[dict[str, Any]]]: Link info by representation ids.
"""
return self.get_entities_links(
project_name,
"representation",
representation_ids,
link_types,
link_direction
)
def get_representation_links(
self,
project_name: str,
representation_id: str,
link_types: Optional[Iterable[str]] = None,
link_direction: Optional[LinkDirection] = None
) -> list[dict[str, Any]]:
"""Query representation links from server.
Args:
project_name (str): Project where links are.
representation_id (str): Representation id for which links
should be received.
link_types (Optional[Iterable[str]]): Link type filters.
link_direction (Optional[Literal["in", "out"]]): Link direction
filter.
Returns:
list[dict[str, Any]]: Link info of representation.
"""
return self.get_representations_links(
project_name, [representation_id], link_types, link_direction
)[representation_id]
def _validate_link_data(self, link_data: dict[str, Any]) -> None:
"""Validate link data before sending to server.
Args:
link_data (dict[str, Any]): Link data to validate.
Raises:
ValueError: Link data is invalid.
"""
required_keys = {"input", "output", "linkType"}
missing_keys = required_keys - link_data.keys()
if missing_keys:
mk = ", ".join((f"'{key}'" for key in missing_keys))
raise ValueError(f"Missing required keys in link data {mk}")
link_type_parts = link_data["linkType"].split("|")
if len(link_type_parts) != 3:
raise ValueError(
f"Invalid linkType format: {link_data['linkType']}. "
"Expected format: 'link_type|input_type|output_type'"
)
def _prepare_link_filters(
self,
filters: dict[str, Any],
link_types: Optional[Iterable[str], None],
link_direction: Optional[LinkDirection],
link_names: Optional[Iterable[str]],
link_name_regex: Optional[str],
) -> bool:
"""Add links filters for GraphQl queries.
Args:
filters (dict[str, Any]): Object where filters will be added.
link_types (Optional[Iterable[str]]): Link types filters.
link_direction (Optional[Literal["in", "out"]]): Direction of
link "in", "out" or 'None' for both.
link_names (Optional[Iterable[str]]): Link name filters.
link_name_regex (Optional[str]): Regex filter for link name.
Returns:
bool: Links are valid, and query from server can happen.
"""
if link_types is not None:
link_types = set(link_types)
if not link_types:
return False
filters["linkTypes"] = list(link_types)
if link_names is not None:
link_names = set(link_names)
if not link_names:
return False
filters["linkNames"] = list(link_names)
if link_direction is not None:
if link_direction not in ("in", "out"):
return False
filters["linkDirection"] = link_direction
if link_name_regex is not None:
filters["linkNameRegex"] = link_name_regex
return True