-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathentity_hub.py
More file actions
3828 lines (3062 loc) · 117 KB
/
entity_hub.py
File metadata and controls
3828 lines (3062 loc) · 117 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
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
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Entity hub is a helper for AYON project entities.
It provides a way to create new entities and to manage existing ones.
Note @iLLiCiTiT this really needs cleanup.
- Remove optional arguments and attributes from 'BaseEntity'.
- More reasonable order of attributes and require positional arguments in
some cases.
- Make clear why UNKNOWN_VALUE is used in some default values for arguments.
"""
from __future__ import annotations
import re
import copy
import collections
import warnings
from abc import ABC, abstractmethod
import typing
from typing import Optional, Iterable, Any, Generator
from .server_api import ServerAPI
from ._api import get_server_api_connection
from .utils import create_entity_id, convert_entity_id, slugify_string
if typing.TYPE_CHECKING:
from typing import Literal, Union, TypedDict, NotRequired
from .typing import (
AttributeSchemaDict,
FolderDict,
TaskDict,
ProductDict,
VersionDict,
)
StatusState = Literal["not_started", "in_progress", "done", "blocked"]
StatusEntityType = Literal[
"folder",
"task",
"product",
"version",
"representation",
"workfile"
]
EntityType = Literal["project", "folder", "task", "product", "version"]
AttributeValueType = Union[bool, str, int, float, list[str]]
class ProjectStatusDict(TypedDict):
name: str
shortName: Optional[str]
state: Optional[StatusState]
icon: Optional[str]
color: Optional[str]
scope: NotRequired[Optional[StatusEntityType]]
class _CustomNone:
def __init__(self, name: Optional[str] = None) -> None:
self._name = name or "CustomNone"
def __repr__(self) -> str:
return f"<{self._name}>"
def __bool__(self) -> bool:
return False
UNKNOWN_VALUE = _CustomNone("UNKNOWN_VALUE")
PROJECT_PARENT_ID = _CustomNone("PROJECT_PARENT_ID")
_NOT_SET = _CustomNone("_NOT_SET")
class EntityHub:
"""Helper to create, update or remove entities in project.
The hub is a guide to operation with folder entities and update of project.
Project entity must already exist on server (can be only updated).
Object is caching entities queried from server. They won't be required once
they were queried, so it is recommended to create new hub or clear cache
frequently.
Todos:
Listen to server events about entity changes to be able to update
already queried entities.
Args:
project_name (str): Name of project where changes will happen.
connection (ServerAPI): Connection to server with logged user.
"""
def __init__(
self,
project_name: str,
connection: Optional[ServerAPI] = None
) -> None:
if connection is None:
connection = get_server_api_connection()
self._connection = connection
self._project_name = project_name
self._entities_by_id = {}
self._entities_by_parent_id = collections.defaultdict(list)
self._project_entity = UNKNOWN_VALUE
self._path_reset_queue = None
@property
def project_name(self) -> str:
"""Project name which is maintained by hub.
Returns:
str: Name of project.
"""
return self._project_name
@property
def project_entity(self) -> ProjectEntity:
"""Project entity.
Returns:
ProjectEntity: Project entity.
"""
if self._project_entity is UNKNOWN_VALUE:
self.fill_project_from_server()
return self._project_entity
def is_product_base_type_supported(self) -> bool:
return self._connection.is_product_base_type_supported()
def get_attributes_for_type(
self, entity_type: EntityType
) -> dict[str, AttributeSchemaDict]:
"""Get attributes available for a type.
Attributes are based on entity types.
Todos:
Use attribute schema to validate values on entities.
Args:
entity_type (EntityType): Entity type for which should
be attributes received.
Returns:
dict[str, AttributeSchemaDict]: Attribute schemas that
are available for entered entity type.
"""
return self._connection.get_attributes_for_type(entity_type)
def get_entity_by_id(self, entity_id: str) -> Optional[BaseEntity]:
"""Receive entity by its id without entity type.
The entity must be already existing in cached objects.
Args:
entity_id (str): Id of entity.
Returns:
Optional[BaseEntity]: Entity object or None.
"""
return self._entities_by_id.get(entity_id)
def get_folder_by_id(
self,
entity_id: str,
allow_fetch: bool = True,
) -> Optional[FolderEntity]:
"""Get folder entity by id.
Args:
entity_id (str): Folder entity id.
allow_fetch (bool): Try to fetch entity from server if is not
available in cache.
Returns:
Optional[FolderEntity]: Folder entity object.
"""
if allow_fetch:
return self.get_or_fetch_entity_by_id(entity_id, ["folder"])
return self._entities_by_id.get(entity_id)
def get_task_by_id(
self,
entity_id: str,
allow_fetch: bool = True,
) -> Optional[TaskEntity]:
"""Get task entity by id.
Args:
entity_id (str): Id of task entity.
allow_fetch (bool): Try to fetch entity from server if is not
available in cache.
Returns:
Optional[TaskEntity]: Task entity object or None.
"""
if allow_fetch:
return self.get_or_fetch_entity_by_id(entity_id, ["task"])
return self._entities_by_id.get(entity_id)
def get_product_by_id(
self,
entity_id: str,
allow_fetch: bool = True,
) -> Optional[ProductEntity]:
"""Get product entity by id.
Args:
entity_id (str): Product id.
allow_fetch (bool): Try to fetch entity from server if is not
available in cache.
Returns:
Optional[ProductEntity]: Product entity object or None.
"""
if allow_fetch:
return self.get_or_fetch_entity_by_id(entity_id, ["product"])
return self._entities_by_id.get(entity_id)
def get_version_by_id(
self,
entity_id: str,
allow_fetch: bool = True,
) -> Optional[VersionEntity]:
"""Get version entity by id.
Args:
entity_id (str): Version id.
allow_fetch (bool): Try to fetch entity from server if is not
available in cache.
Returns:
Optional[VersionEntity]: Version entity object or None.
"""
if allow_fetch:
return self.get_or_fetch_entity_by_id(entity_id, ["version"])
return self._entities_by_id.get(entity_id)
def get_or_fetch_entity_by_id(
self,
entity_id: str,
entity_types: list[EntityType],
) -> Union[
ProjectEntity,
FolderEntity,
TaskEntity,
ProductEntity,
VersionEntity,
None
]:
"""Get or query entity based on it's id and possible entity types.
This is a helper function when entity id is known but entity type may
have multiple possible options.
Args:
entity_id (str): Entity id.
entity_types (Iterable[str]): Possible entity types that can the id
represent. e.g. '["folder", "project"]'
"""
existing_entity = self._entities_by_id.get(entity_id)
if existing_entity is not None:
return existing_entity
if not entity_types:
return None
entity_type = None
entity_data = None
for entity_type in entity_types:
if entity_type == "folder":
entity_data = self._connection.get_folder_by_id(
self.project_name,
entity_id,
fields=self._get_folder_fields(),
own_attributes=True,
)
elif entity_type == "task":
entity_data = self._connection.get_task_by_id(
self.project_name,
entity_id,
fields=self._get_task_fields(),
own_attributes=True,
)
elif entity_type == "product":
entity_data = self._connection.get_product_by_id(
self.project_name,
entity_id,
fields=self._get_product_fields(),
)
elif entity_type == "version":
entity_data = self._connection.get_version_by_id(
self.project_name,
entity_id,
fields=self._get_version_fields(),
)
else:
raise ValueError(f"Unknown entity type \"{entity_type}\"")
if entity_data:
break
if not entity_data:
return None
if entity_type == "folder":
folder_entity = self.add_folder(entity_data)
folder_entity.has_published_content = entity_data["hasProducts"]
return folder_entity
if entity_type == "task":
return self.add_task(entity_data)
if entity_type == "product":
return self.add_product(entity_data)
if entity_type == "version":
return self.add_version(entity_data)
return None
def get_or_query_entity_by_id(
self,
entity_id: str,
entity_types: list[EntityType],
) -> Union[
ProjectEntity,
FolderEntity,
TaskEntity,
ProductEntity,
VersionEntity,
None
]:
"""Get or query entity based on it's id and possible entity types."""
warnings.warn(
"Method 'get_or_query_entity_by_id' is deprecated. "
"Please use 'get_or_fetch_entity_by_id' instead.",
DeprecationWarning
)
return self.get_or_fetch_entity_by_id(entity_id, entity_types)
@property
def entities(self) -> Generator[BaseEntity, None, None]:
"""Iterator over available entities.
Returns:
Generator[BaseEntity, None, None]: All queried/created entities
cached in hub.
"""
for entity in self._entities_by_id.values():
yield entity
def add_new_folder(
self,
name: str,
folder_type: str,
parent_id: Optional[str] = UNKNOWN_VALUE,
label: Optional[str] = None,
path: Optional[str] = None,
status: Optional[str] = UNKNOWN_VALUE,
tags: Optional[Iterable[str]] = None,
attribs: Optional[dict[str, Any]] = None,
data: Optional[dict[str, Any]] = UNKNOWN_VALUE,
thumbnail_id: Optional[str] = UNKNOWN_VALUE,
active: Optional[bool] = UNKNOWN_VALUE,
entity_id: Optional[str] = None,
created: Optional[bool] = True,
) -> FolderEntity:
"""Create folder object and add it to entity hub.
Args:
name (str): Name of entity.
folder_type (str): Type of folder. Folder type must be available in
config of project folder types.
parent_id (Optional[str]): Id of parent entity.
label (Optional[str]): Folder label.
path (Optional[str]): Folder path. Path consist of all parent names
with slash('/') used as separator.
status (Optional[str]): Folder status.
tags (Optional[Iterable[str]]): Folder tags.
attribs (Optional[dict[str, Any]]): Attribute values.
data (dict[str, Any]): Entity data (custom data).
thumbnail_id (Optional[str]): Id of entity's thumbnail.
active (Optional[bool]): Is entity active.
entity_id (Optional[str]): Id of the entity. New id is created if
not passed.
created (Optional[bool]): Entity is new. When 'None' is passed the
value is defined based on value of 'entity_id'.
Returns:
FolderEntity: Added folder entity.
"""
folder_entity = FolderEntity(
name=name,
folder_type=folder_type,
parent_id=parent_id,
label=label,
path=path,
status=status,
tags=tags,
attribs=attribs,
data=data,
thumbnail_id=thumbnail_id,
active=active,
entity_id=entity_id,
created=created,
entity_hub=self
)
self.add_entity(folder_entity)
return folder_entity
def add_new_task(
self,
name: str,
task_type: str,
folder_id: Optional[str] = UNKNOWN_VALUE,
label: Optional[str] = None,
status: Optional[str] = UNKNOWN_VALUE,
tags: Optional[Iterable[str]] = None,
attribs: Optional[dict[str, Any]] = None,
data: Optional[dict[str, Any]] = UNKNOWN_VALUE,
assignees: Optional[Iterable[str]] = None,
thumbnail_id: Optional[str] = UNKNOWN_VALUE,
active: Optional[bool] = UNKNOWN_VALUE,
entity_id: Optional[str] = None,
created: Optional[bool] = True,
parent_id: Optional[str] = UNKNOWN_VALUE,
) -> TaskEntity:
"""Create task object and add it to entity hub.
Args:
name (str): Name of entity.
task_type (str): Type of task. Task type must be available in
config of project task types.
folder_id (Optional[str]): Parent folder id.
label (Optional[str]): Task label.
status (Optional[str]): Task status.
tags (Optional[Iterable[str]]): Folder tags.
attribs (Optional[dict[str, Any]]): Attribute values.
data (dict[str, Any]): Entity data (custom data).
assignees (Optional[Iterable[str]]): User assignees to the task.
thumbnail_id (Optional[str]): Id of entity's thumbnail.
active (bool): Is entity active.
entity_id (Optional[str]): Id of the entity. New id is created if
not passed.
created (Optional[bool]): Entity is new. When 'None' is passed the
value is defined based on value of 'entity_id'.
parent_id (Optional[str]): DEPRECATED Parent folder id.
Returns:
TaskEntity: Added task entity.
"""
if parent_id is not UNKNOWN_VALUE:
warnings.warn(
"Used deprecated argument 'parent_id'."
" Use 'folder_id' instead.",
DeprecationWarning
)
folder_id = parent_id
task_entity = TaskEntity(
name=name,
task_type=task_type,
folder_id=folder_id,
label=label,
status=status,
tags=tags,
attribs=attribs,
data=data,
assignees=assignees,
thumbnail_id=thumbnail_id,
active=active,
entity_id=entity_id,
created=created,
entity_hub=self,
)
self.add_entity(task_entity)
return task_entity
def add_new_product(
self,
name: str,
product_type: str,
product_base_type: Optional[str] = None,
folder_id: Optional[str] = UNKNOWN_VALUE,
tags: Optional[Iterable[str]] = None,
attribs: Optional[dict[str, Any]] = None,
data: Optional[dict[str, Any]] = UNKNOWN_VALUE,
active: Optional[bool] = UNKNOWN_VALUE,
entity_id: Optional[str] = None,
created: Optional[bool] = True,
) -> ProductEntity:
"""Create a product object and add it to the entity hub.
Args:
name (str): Name of entity.
product_base_type (str): Base type of product.
product_type (str): Type of product.
folder_id (Optional[str]): Parent folder id.
tags (Optional[Iterable[str]]): Folder tags.
attribs (Optional[dict[str, Any]]): Attribute values.
data (dict[str, Any]): Entity data (custom data).
active (bool): Is entity active.
entity_id (Optional[str]): Id of the entity. New id is created if
not passed.
created (Optional[bool]): Entity is new. When 'None' is passed the
value is defined based on value of 'entity_id'.
Todo:
- Once the product base type is implemented and established,
it should be made mandatory to pass it and product_type
itself should be optional.
Returns:
ProductEntity: Added product entity.
"""
product_entity = ProductEntity(
name=name,
product_type=product_type,
product_base_type=product_base_type,
folder_id=folder_id,
tags=tags,
attribs=attribs,
data=data,
active=active,
entity_id=entity_id,
created=created,
entity_hub=self,
)
self.add_entity(product_entity)
return product_entity
def add_new_version(
self,
version: int,
product_id: Optional[str] = UNKNOWN_VALUE,
task_id: Optional[str] = UNKNOWN_VALUE,
status: Optional[str] = UNKNOWN_VALUE,
tags: Optional[Iterable[str]] = None,
attribs: Optional[dict[str, Any]] = None,
data: Optional[dict[str, Any]] = UNKNOWN_VALUE,
thumbnail_id: Optional[str] = UNKNOWN_VALUE,
active: Optional[bool] = UNKNOWN_VALUE,
entity_id: Optional[str] = None,
created: Optional[bool] = True,
) -> VersionEntity:
"""Create task object and add it to entity hub.
Args:
version (int): Version.
product_id (Optional[str]): Parent product id.
task_id (Optional[str]): Parent task id.
status (Optional[str]): Task status.
tags (Optional[Iterable[str]]): Folder tags.
attribs (Optional[dict[str, Any]]): Attribute values.
data (dict[str, Any]): Entity data (custom data).
thumbnail_id (Optional[str]): Id of entity's thumbnail.
active (bool): Is entity active.
entity_id (Optional[str]): Id of the entity. New id is created if
not passed.
created (Optional[bool]): Entity is new. When 'None' is passed the
value is defined based on value of 'entity_id'.
Returns:
VersionEntity: Added version entity.
"""
version_entity = VersionEntity(
version=version,
product_id=product_id,
task_id=task_id,
status=status,
tags=tags,
attribs=attribs,
data=data,
thumbnail_id=thumbnail_id,
active=active,
entity_id=entity_id,
created=created,
entity_hub=self,
)
self.add_entity(version_entity)
return version_entity
def add_folder(self, folder: FolderDict) -> FolderEntity:
"""Create folder object and add it to entity hub.
Args:
folder (FolderDict): Folder entity data.
Returns:
FolderEntity: Added folder entity.
"""
folder_entity = FolderEntity.from_entity_data(folder, entity_hub=self)
self.add_entity(folder_entity)
return folder_entity
def add_task(self, task: TaskDict) -> TaskEntity:
"""Create task object and add it to entity hub.
Args:
task (TaskDict): Task entity data.
Returns:
TaskEntity: Added task entity.
"""
task_entity = TaskEntity.from_entity_data(task, entity_hub=self)
self.add_entity(task_entity)
return task_entity
def add_product(self, product: ProductDict) -> ProductEntity:
"""Create version object and add it to entity hub.
Args:
product (ProductDict): Version entity data.
Returns:
ProductEntity: Added version entity.
"""
product_entity = ProductEntity.from_entity_data(
product, entity_hub=self
)
self.add_entity(product_entity)
return product_entity
def add_version(self, version: VersionDict) -> VersionEntity:
"""Create version object and add it to entity hub.
Args:
version (dict[str, Any]): Version entity data.
Returns:
VersionEntity: Added version entity.
"""
version_entity = VersionEntity.from_entity_data(
version, entity_hub=self
)
self.add_entity(version_entity)
return version_entity
def add_entity(self, entity: BaseEntity) -> None:
"""Add entity to hub cache.
Args:
entity (BaseEntity): Entity that should be added to hub's cache.
"""
self._entities_by_id[entity.id] = entity
parent_children = self._entities_by_parent_id[entity.parent_id]
if entity not in parent_children:
parent_children.append(entity)
if entity.parent_id is PROJECT_PARENT_ID:
return
parent = self._entities_by_id.get(entity.parent_id)
if parent is not None:
parent.add_child(entity.id)
def folder_path_reseted(self, folder_id: str) -> None:
"""Method called from 'FolderEntity' on path reset.
This should reset cache of folder paths on all children entities.
The path cache is always propagated from top to bottom so if an entity
has not cached path it means that any children can't have it cached.
"""
if self._path_reset_queue is not None:
self._path_reset_queue.append(folder_id)
return
self._path_reset_queue = collections.deque()
self._path_reset_queue.append(folder_id)
while self._path_reset_queue:
children = self._entities_by_parent_id[folder_id]
for child in children:
# Get child path but don't trigger cache
path = child.get_path(False)
if path is not None:
# Reset it's path cache if is set
child.reset_path()
else:
self._path_reset_queue.append(child.id)
self._path_reset_queue = None
def unset_entity_parent(self, entity_id: str, parent_id: str) -> None:
entity = self._entities_by_id.get(entity_id)
parent = self._entities_by_id.get(parent_id)
children_ids = UNKNOWN_VALUE
if parent is not None:
children_ids = parent.get_children_ids(False)
has_set_parent = False
if entity is not None:
has_set_parent = entity.parent_id == parent_id
new_parent_id = None
if has_set_parent:
entity.parent_id = new_parent_id
if children_ids is not UNKNOWN_VALUE and entity_id in children_ids:
parent.remove_child(entity_id)
if entity is None or not has_set_parent:
self.reset_immutable_for_hierarchy_cache(parent_id)
return
orig_parent_children = self._entities_by_parent_id[parent_id]
if entity in orig_parent_children:
orig_parent_children.remove(entity)
new_parent_children = self._entities_by_parent_id[new_parent_id]
if entity not in new_parent_children:
new_parent_children.append(entity)
self.reset_immutable_for_hierarchy_cache(parent_id)
def set_entity_parent(
self,
entity_id: str,
parent_id: str,
orig_parent_id: Optional[str] = _NOT_SET,
) -> None:
parent = self._entities_by_id.get(parent_id)
entity = self._entities_by_id.get(entity_id)
if entity is None:
if parent is not None:
children_ids = parent.get_children_ids(False)
if (
children_ids is not UNKNOWN_VALUE
and entity_id in children_ids
):
parent.remove_child(entity_id)
self.reset_immutable_for_hierarchy_cache(parent.id)
return
if orig_parent_id is _NOT_SET:
orig_parent_id = entity.parent_id
if orig_parent_id == parent_id:
return
orig_parent_children = self._entities_by_parent_id[orig_parent_id]
if entity in orig_parent_children:
orig_parent_children.remove(entity)
self.reset_immutable_for_hierarchy_cache(orig_parent_id)
orig_parent = self._entities_by_id.get(orig_parent_id)
if orig_parent is not None:
orig_parent.remove_child(entity_id)
parent_children = self._entities_by_parent_id[parent_id]
if entity not in parent_children:
parent_children.append(entity)
entity.parent_id = parent_id
if parent is None or parent.get_children_ids(False) is UNKNOWN_VALUE:
return
parent.add_child(entity_id)
self.reset_immutable_for_hierarchy_cache(parent_id)
def _fetch_entity_children(self, entity: BaseEntity) -> None:
folder_fields = self._get_folder_fields()
task_fields = self._get_task_fields()
tasks = []
folders = []
if entity.entity_type == "project":
folders = list(self._connection.get_folders(
entity["name"],
parent_ids=[entity.id],
fields=folder_fields,
own_attributes=True,
active=None,
))
elif entity.entity_type == "folder":
folders = list(self._connection.get_folders(
self.project_entity["name"],
parent_ids=[entity.id],
fields=folder_fields,
own_attributes=True,
active=None,
))
tasks = list(self._connection.get_tasks(
self.project_entity["name"],
folder_ids=[entity.id],
fields=task_fields,
own_attributes=True,
active=None,
))
children_ids = {
child.id
for child in self._entities_by_parent_id[entity.id]
}
for folder in folders:
folder_entity = self._entities_by_id.get(folder["id"])
if folder_entity is None:
folder_entity = self.add_folder(folder)
children_ids.add(folder_entity.id)
elif folder_entity.parent_id == entity.id:
children_ids.add(folder_entity.id)
folder_entity.has_published_content = folder["hasProducts"]
for task in tasks:
task_entity = self._entities_by_id.get(task["id"])
if task_entity is not None:
if task_entity.parent_id == entity.id:
children_ids.add(task_entity.id)
continue
task_entity = self.add_task(task)
children_ids.add(task_entity.id)
entity.fill_children_ids(children_ids)
def get_entity_children(
self, entity: BaseEntity, allow_fetch: bool = True
) -> Union[list[BaseEntity], _CustomNone]:
children_ids = entity.get_children_ids(allow_fetch=False)
if children_ids is not UNKNOWN_VALUE:
return entity.get_children()
if children_ids is UNKNOWN_VALUE and not allow_fetch:
return UNKNOWN_VALUE
self._fetch_entity_children(entity)
return entity.get_children()
def delete_entity(self, entity: BaseEntity) -> None:
parent_id = entity.parent_id
if parent_id is None:
return
parent = self._entities_by_id.get(parent_id)
if parent is not None:
parent.remove_child(entity.id)
else:
self.unset_entity_parent(entity.id, parent_id)
def reset_immutable_for_hierarchy_cache(
self,
entity_id: Optional[str],
bottom_to_top: Optional[bool] = True,
) -> None:
if bottom_to_top is None or entity_id is None:
return
reset_queue = collections.deque()
reset_queue.append(entity_id)
if bottom_to_top:
while reset_queue:
entity_id: str = reset_queue.popleft()
entity: Optional[BaseEntity] = self.get_entity_by_id(
entity_id
)
if entity is None:
continue
entity.reset_immutable_for_hierarchy_cache(None)
reset_queue.append(entity.parent_id)
else:
while reset_queue:
entity_id: str = reset_queue.popleft()
entity: Optional[BaseEntity] = self.get_entity_by_id(
entity_id
)
if entity is None:
continue
entity.reset_immutable_for_hierarchy_cache(None)
for child in self._entities_by_parent_id[entity.id]:
reset_queue.append(child.id)
def fill_project_from_server(self) -> ProjectEntity:
"""Query project data from server and create project entity.
This method will invalidate previous object of Project entity.
Returns:
ProjectEntity: Entity that was updated with server data.
Raises:
ValueError: When project was not found on server.
"""
project_name = self.project_name
project = self._connection.get_project(
project_name,
own_attributes=True,
)
if not project:
raise ValueError(f"Project \"{project_name}\" was not found.")
major, minor, _, _, _ = self._connection.get_server_version_tuple()
status_scope_supported = True
if (major, minor) < (1, 5):
status_scope_supported = False
self._project_entity = ProjectEntity.from_entity_data(
project, self
)
self._project_entity.set_status_scope_supported(
status_scope_supported
)
self.add_entity(self._project_entity)
return self._project_entity
def _get_folder_fields(self) -> set[str]:
folder_fields = set(
self._connection.get_default_fields_for_type("folder")
)
folder_fields.add("hasProducts")
folder_fields.add("data")
return folder_fields
def _get_task_fields(self) -> set[str]:
return set(
self._connection.get_default_fields_for_type("task")
)
def _get_product_fields(self) -> set[str]:
return set(
self._connection.get_default_fields_for_type("product")
)
def _get_version_fields(self) -> set[str]:
return set(
self._connection.get_default_fields_for_type("version")
)
def fetch_hierarchy_entities(self) -> None:
"""Query whole project at once."""
project_entity = self.fill_project_from_server()
folder_fields = self._get_folder_fields()
task_fields = self._get_task_fields()
folders = self._connection.get_folders(
project_entity.name,
fields=folder_fields,
own_attributes=True,
active=None,
)
tasks = self._connection.get_tasks(
project_entity.name,
fields=task_fields,
own_attributes=True,
active=None,
)
folders_by_parent_id = collections.defaultdict(list)
for folder in folders:
parent_id = folder["parentId"]
folders_by_parent_id[parent_id].append(folder)
tasks_by_parent_id = collections.defaultdict(list)
for task in tasks:
parent_id = task["folderId"]
tasks_by_parent_id[parent_id].append(task)
lock_queue = collections.deque()
hierarchy_queue = collections.deque()
hierarchy_queue.append((None, project_entity))
while hierarchy_queue:
item = hierarchy_queue.popleft()
parent_id, parent_entity = item
lock_queue.append(parent_entity)
children_ids = set()
for folder in folders_by_parent_id[parent_id]:
folder_entity = self.add_folder(folder)
children_ids.add(folder_entity.id)
folder_entity.has_published_content = folder["hasProducts"]
hierarchy_queue.append((folder_entity.id, folder_entity))
for task in tasks_by_parent_id[parent_id]: