-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathutils.py
More file actions
1393 lines (1080 loc) · 35.5 KB
/
Copy pathutils.py
File metadata and controls
1393 lines (1080 loc) · 35.5 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
from __future__ import annotations
import functools
import os
import re
import datetime
from dataclasses import dataclass
import copy
import logging
import json
import uuid
import string
import platform
import traceback
import collections
import itertools
from urllib.parse import urlparse, urlencode, ParseResult
import typing
from typing import Any, Iterable
import warnings
from enum import IntEnum
import requests
import unidecode
from .constants import (
SERVER_TIMEOUT_ENV_KEY,
DEFAULT_VARIANT_ENV_KEY,
SITE_ID_ENV_KEY,
)
from .exceptions import (
UrlError,
UrlNotReached,
ServerError,
UnauthorizedError,
HTTPRequestError,
RequestsJSONDecodeError,
)
try:
from http import HTTPStatus
except ImportError:
HTTPStatus = None
if typing.TYPE_CHECKING:
from .typing import AnyEntityDict, StreamType
REMOVED_VALUE = object()
NOT_SET = object()
SLUGIFY_WHITELIST = string.ascii_letters + string.digits
SLUGIFY_SEP_WHITELIST = " ,./\\;:!|*^#@~+-_="
PatternType = type(re.compile(""))
RepresentationParents = collections.namedtuple(
"RepresentationParents",
("version", "product", "folder", "project")
)
RepresentationHierarchy = collections.namedtuple(
"RepresentationHierarchy",
(
"project",
"folder",
"task",
"product",
"version",
"representation",
)
)
@dataclass
class _TimeoutWrapInfo:
func = None
args_pos = 2
def _timeout_kwarg_deprecation(arg):
"""Decorator to add timeout kwarg to function."""
# TODO remove this deprecation
wrap_info = _TimeoutWrapInfo()
def wrapper(*args, **kwargs):
if len(args) > wrap_info.args_pos:
warnings.warn(
"Timeout was passed as a positional argument please"
" use timeout=... keyword argument instead. This will stop"
" working in future versions on ayon-api.",
category=FutureWarning,
stacklevel=2,
)
return wrap_info.func(*args, **kwargs)
if not isinstance(arg, int):
wrap_info.func = arg
return functools.wraps(arg)(wrapper)
wrap_info.args_pos = arg
def main_wrapper(func):
wrap_info.func = func
return functools.wraps(func)(wrapper)
return main_wrapper
class SortOrder(IntEnum):
"""Sort order for GraphQl requests."""
ascending = 0
descending = 1
@classmethod
def parse_value(cls, value, default=None):
if value in (cls.ascending, "ascending", "asc"):
return cls.ascending
if value in (cls.descending, "descending", "desc"):
return cls.descending
return default
class RequestType:
def __init__(self, name: str):
self.name: str = name
def __hash__(self):
return self.name.__hash__()
class RequestTypes:
get = RequestType("GET")
post = RequestType("POST")
put = RequestType("PUT")
patch = RequestType("PATCH")
delete = RequestType("DELETE")
def _get_description(response):
if HTTPStatus is None:
return str(response.orig_response)
return HTTPStatus(response.status).description
class RestApiResponse:
"""API Response."""
log = logging.getLogger("RestApiResponse")
def __init__(self, response, data=None):
if response is None:
status_code = 500
else:
status_code = response.status_code
self._response = response
self.status = status_code
self._data = data
@property
def text(self):
if self._response is None:
return self.detail
return self._response.text
@property
def orig_response(self):
return self._response
@property
def headers(self):
if self._response is None:
return {}
return self._response.headers
@property
def data(self):
if self._data is None:
try:
self._data = self.orig_response.json()
except (AttributeError, RequestsJSONDecodeError):
self._data = {}
return self._data
@property
def content(self):
if self._response is None:
return b""
return self._response.content
@property
def content_type(self) -> str | None:
return self.headers.get("Content-Type")
@property
def detail(self):
detail = self.get("detail")
if detail:
return detail
return _get_description(self)
@property
def status_code(self) -> int:
return self.status
@property
def ok(self) -> bool:
if self._response is not None:
return self._response.ok
return False
def raise_for_status(self, message=None):
if self._response is None:
if self._data and self._data.get("detail"):
if self.status_code == 401:
raise UnauthorizedError(self._data["detail"])
raise ServerError(self._data["detail"])
raise ValueError("Response is not available.")
try:
self._response.raise_for_status()
except requests.exceptions.HTTPError as exc:
if message is None:
message = str(exc)
submsg = ""
if self.data:
submsg = json.dumps(self.data, indent=4)
self.log.warning(
"HTTP request error: %s%s%s",
message,
"\n" if submsg else "",
submsg,
)
detail = self.data.get("detail")
if detail:
message = f"{message} ({detail})"
if self.status_code == 401:
raise UnauthorizedError(message, exc.response)
raise HTTPRequestError(message, exc.response)
def __enter__(self, *args, **kwargs):
return self._response.__enter__(*args, **kwargs)
def __contains__(self, key):
return key in self.data
def __repr__(self):
return f"<{self.__class__.__name__} [{self.status}]>"
def __len__(self):
return int(200 <= self.status < 400)
def __bool__(self):
return 200 <= self.status < 400
def __getitem__(self, key):
return self.data[key]
def get(self, key, default=None):
data = self.data
if isinstance(data, dict):
return self.data.get(key, default)
return default
def fill_own_attribs(entity: AnyEntityDict) -> None:
"""Fill own attributes.
Prepare data with own attributes. Prepare data based on a list of
attribute names in 'ownAttrib' and 'attrib'. If is not attribute in
'ownAttrib' then it's value is set to 'None'.
This can be used with a project, folder or task entity. All other entities
don't use hierarchical attributes and 'attrib' values are
"real values".
Args:
entity (dict): Entity dictionary.
"""
if not entity or not entity.get("attrib"):
return
attributes = entity.get("ownAttrib")
if attributes is None:
return
attributes = set(attributes)
own_attrib = {}
entity["ownAttrib"] = own_attrib
for key, value in entity["attrib"].items():
if key not in attributes:
own_attrib[key] = None
else:
own_attrib[key] = copy.deepcopy(value)
def _convert_filter_value(value: Any) -> list[Any] | None:
if value is None:
return None
if isinstance(value, PatternType):
return [value.pattern]
if isinstance(value, (int, float, str, bool)):
return [value]
return list(set(value))
def prepare_list_filters(
output: dict[str, Any], *args: tuple[str, Any], **kwargs: Any
) -> bool:
for key, value in itertools.chain(args, kwargs.items()):
value = _convert_filter_value(value)
if value is None:
continue
if not value:
return False
output[key] = value
return True
def get_default_timeout() -> float:
"""Default value for requests timeout.
First looks for environment variable SERVER_TIMEOUT_ENV_KEY which
can affect timeout value. If not available then use 10.0 s.
Returns:
float: Timeout value in seconds.
"""
try:
return float(os.environ.get(SERVER_TIMEOUT_ENV_KEY))
except (ValueError, TypeError):
pass
return 10.0
def get_default_settings_variant() -> str:
"""Default settings variant.
Returns:
str: Settings variant from environment variable or 'production'.
"""
return os.environ.get(DEFAULT_VARIANT_ENV_KEY) or "production"
def get_machine_name() -> str:
"""Get machine name.
Returns:
str: Machine name.
"""
return unidecode.unidecode(platform.node())
def get_default_site_id() -> str | None:
"""Site id used for server connection.
Returns:
str | None: Site id from environment variable or None.
"""
return os.environ.get(SITE_ID_ENV_KEY)
class ThumbnailContent:
"""Wrapper for thumbnail content.
Args:
project_name (str): Project name.
thumbnail_id (str | None): Thumbnail id.
content (bytes | None): Thumbnail content.
content_type (str | None): Content type e.g. 'image/png'.
"""
def __init__(
self,
project_name: str,
thumbnail_id: str | None,
content: bytes | None,
content_type: str | None,
):
self.project_name: str = project_name
self.thumbnail_id: str | None = thumbnail_id
self.content_type: str | None = content_type
self.content: bytes = content or b""
@property
def id(self) -> str | None:
"""Wrapper for thumbnail id."""
return self.thumbnail_id
@property
def is_valid(self) -> bool:
"""Content of thumbnail is valid.
Returns:
bool: Content is valid and can be used.
"""
return (
self.thumbnail_id is not None
and self.content_type is not None
)
def prepare_query_string(
key_values: dict[str, Any], skip_none: bool = True
) -> str:
"""Prepare data to query string.
If there are any values a query starting with '?' is returned otherwise
an empty string.
Args:
key_values (dict[str, Any]): Query values.
skip_none (bool): Filter values which are 'None'.
Returns:
str: Query string.
"""
if skip_none:
key_values = {
key: value
for key, value in key_values.items()
if value is not None
}
if not key_values:
return ""
return f"?{urlencode(key_values)}"
def create_entity_id() -> str:
return uuid.uuid1().hex
def convert_entity_id(entity_id) -> str | None:
if not entity_id:
return None
if isinstance(entity_id, uuid.UUID):
return entity_id.hex
try:
return uuid.UUID(entity_id).hex
except (TypeError, ValueError, AttributeError):
pass
return None
def convert_or_create_entity_id(entity_id: str | None = None) -> str:
output = convert_entity_id(entity_id)
if output is None:
output = create_entity_id()
return output
def entity_data_json_default(value: Any) -> Any:
if isinstance(value, datetime.datetime):
return int(value.timestamp())
raise TypeError(
f"Object of type {type(value)} is not JSON serializable"
)
def slugify_string(
input_string: str,
separator: str = "_",
slug_whitelist: Iterable[str] = SLUGIFY_WHITELIST,
split_chars: Iterable[str] = SLUGIFY_SEP_WHITELIST,
min_length: int = 1,
lower: bool = False,
make_set: bool = False,
) -> str | set[str]:
"""Slugify a text string.
This function removes transliterates input string to ASCII, removes
special characters and use join resulting elements using
specified separator.
Args:
input_string (str): Input string to slugify
separator (str): A string used to separate returned elements
(default: "_")
slug_whitelist (str): Characters allowed in the output
(default: ascii letters, digits and the separator)
split_chars (str): Set of characters used for word splitting
(there is a sane default)
lower (bool): Convert to lower-case (default: False)
make_set (bool): Return "set" object instead of string.
min_length (int): Minimal length of an element (word).
Returns:
str | set[str]: Based on 'make_set' value returns slugified string.
"""
tmp_string = unidecode.unidecode(input_string)
if lower:
tmp_string = tmp_string.lower()
parts = [
# Remove all characters that are not in whitelist
re.sub("[^{}]".format(re.escape(slug_whitelist)), "", part)
# Split text into part by split characters
for part in re.split("[{}]".format(re.escape(split_chars)), tmp_string)
]
# Filter text parts by length
filtered_parts = [
part
for part in parts
if len(part) >= min_length
]
if make_set:
return set(filtered_parts)
return separator.join(filtered_parts)
def failed_json_default(value: Any) -> str:
return f"< Failed value {type(value)} > {value}"
def prepare_attribute_changes(
old_entity: AnyEntityDict,
new_entity: AnyEntityDict,
replace: int = False,
) -> dict[str, Any]:
attrib_changes = {}
new_attrib = new_entity.get("attrib")
old_attrib = old_entity.get("attrib")
if new_attrib is None:
if not replace:
return attrib_changes
new_attrib = {}
if old_attrib is None:
return new_attrib
for attr, new_attr_value in new_attrib.items():
old_attr_value = old_attrib.get(attr)
if old_attr_value != new_attr_value:
attrib_changes[attr] = new_attr_value
if replace:
for attr in old_attrib:
if attr not in new_attrib:
attrib_changes[attr] = REMOVED_VALUE
return attrib_changes
def prepare_entity_changes(
old_entity: AnyEntityDict,
new_entity: AnyEntityDict,
replace: bool = False,
) -> dict[str, Any]:
"""Prepare changes of entities."""
changes = {}
for key, new_value in new_entity.items():
if key == "attrib":
continue
old_value = old_entity.get(key)
if old_value != new_value:
changes[key] = new_value
if replace:
for key in old_entity:
if key not in new_entity:
changes[key] = REMOVED_VALUE
attr_changes = prepare_attribute_changes(old_entity, new_entity, replace)
if attr_changes:
changes["attrib"] = attr_changes
return changes
def _try_parse_url(url: str) -> ParseResult | None:
try:
return urlparse(url)
except BaseException:
return None
def _try_connect_to_server(
url: str,
timeout: float | None,
verify: str | bool | None,
cert: str | None,
) -> str | None:
if timeout is None:
timeout = get_default_timeout()
if verify is None:
verify = os.environ.get("AYON_CA_FILE") or True
if cert is None:
cert = os.environ.get("AYON_CERT_FILE") or None
try:
# TODO add validation if the url lead to AYON server
# - this won't validate if the url lead to 'google.com'
response = requests.get(
f"{url}/api/info",
timeout=timeout,
verify=verify,
cert=cert,
)
_ = response.json()
if response.history:
return response.history[-1].headers["location"].rstrip("/")
return url
except Exception:
print(f"Failed to connect to '{url}'")
traceback.print_exc()
return None
@_timeout_kwarg_deprecation(3)
def login_to_server(
url: str,
username: str,
password: str,
timeout: float | None = None,
) -> str | None:
"""Use login to the server to receive token.
Args:
url (str): Server url.
username (str): User's username.
password (str): User's password.
timeout (float | None): Timeout for request. Value from
'get_default_timeout' is used if not specified.
Returns:
str | None: User's token if login was successfull.
Otherwise 'None'.
"""
if timeout is None:
timeout = get_default_timeout()
headers = {"Content-Type": "application/json"}
response = requests.post(
f"{url}/api/auth/login",
headers=headers,
json={
"name": username,
"password": password
},
timeout=timeout,
)
token = None
# 200 - success
# 401 - invalid credentials
# * - other issues
if response.status_code == 200:
token = response.json()["token"]
return token
@_timeout_kwarg_deprecation
def logout_from_server(
url: str,
token: str,
timeout: float | None = None,
) -> None:
"""Logout from server and throw token away.
Args:
url (str): Url from which should be logged out.
token (str): Token which should be used to log out.
timeout (float | None): Timeout for request. Value from
'get_default_timeout' is used if not specified.
"""
if timeout is None:
timeout = get_default_timeout()
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {token}",
}
requests.post(
f"{url}/api/auth/logout",
headers=headers,
timeout=timeout,
)
@dataclass
class UserInfo:
"""User information."""
is_valid: bool = False
is_service: bool = False
response: requests.Response | None = None
def get_user_info_by_token(
url: str,
token: str,
*,
verify: str | bool | None = None,
cert: str | None = None,
timeout: float | None = None,
) -> UserInfo:
"""Get user information by url and token.
Args:
url (str): Server url.
token (str): User's token.
verify (str | bool | None): SSL verification for request. Value from
'AYON_CA_FILE' environment variable is used if not specified.
cert (str | None): SSL certificate for request. Value from
'AYON_CERT_FILE' environment variable is used if not specified.
timeout (float | None): Timeout for request. Value from
'get_default_timeout' is used if not specified.
Returns:
UserInfo: User information if url and token are valid.
"""
output = UserInfo()
if not token:
return output
if timeout is None:
timeout = get_default_timeout()
if verify is None:
verify = os.environ.get("AYON_CA_FILE") or True
if cert is None:
cert = os.environ.get("AYON_CERT_FILE") or None
base_headers = {
"Content-Type": "application/json",
}
for header_value, is_service in (
({"Authorization": f"Bearer {token}"}, False),
({"X-Api-Key": token}, True),
):
headers = base_headers.copy()
headers.update(header_value)
response = requests.get(
f"{url}/api/users/me",
headers=headers,
timeout=timeout,
verify=verify,
cert=cert,
)
output = UserInfo(
is_valid=response.status_code == 200,
is_service=is_service,
response=response,
)
if output.is_valid:
break
return output
@_timeout_kwarg_deprecation
def get_user_by_token(
url: str,
token: str,
timeout: float | None = None,
*,
verify: str | bool | None = None,
cert: str | None = None,
) -> dict[str, Any] | None:
"""Get user information by url and token.
Args:
url (str): Server url.
token (str): User's token.
timeout (float | None): Timeout for request. Value from
'get_default_timeout' is used if not specified.
verify (str | bool | None): SSL verification for request. Value from
'AYON_CA_FILE' environment variable is used if not specified.
cert (str | None): SSL certificate for request. Value from
'AYON_CERT_FILE' environment variable is used if not specified.
Returns:
dict[str, Any] | None: User information if url and token are valid.
"""
user_info = get_user_info_by_token(
url, token, timeout=timeout, verify=verify, cert=cert,
)
if user_info.is_valid:
return user_info.data
return None
@_timeout_kwarg_deprecation
def is_token_valid(
url: str,
token: str,
timeout: float | None = None,
*,
verify: str | bool | None = None,
cert: str | None = None,
) -> bool:
"""Check if token is valid.
Token can be a user token or service api key.
Args:
url (str): Server url.
token (str): User's token.
timeout (float | None): Timeout for request. Value from
'get_default_timeout' is used if not specified.
verify (str | bool | None): SSL verification for request. Value from
'AYON_CA_FILE' environment variable is used if not specified.
cert (str | None): SSL certificate for request. Value from
'AYON_CERT_FILE' environment variable is used if not specified.
Returns:
bool: True if token is valid.
"""
user_info = get_user_info_by_token(
url, token, timeout=timeout, verify=verify, cert=cert
)
return user_info.is_valid
@_timeout_kwarg_deprecation(1)
def validate_url(
url: str,
timeout: int | None = None,
verify: str | bool | None = None,
cert: str | None = None,
) -> str:
"""Validate url if is valid and server is available.
Validation checks if can be parsed as url and contains scheme.
Function will try to autofix url thus will return modified url when
connection to server works.
.. highlight:: python
.. code-block:: python
my_url = "my.server.url"
try:
# Store new url
validated_url = validate_url(my_url)
except UrlError:
# Handle invalid url
...
Args:
url (str): Server url.
timeout (int | None): Timeout in seconds for connection to server.
Returns:
Url which was used to connect to server.
Raises:
UrlError: Error with short description and hints for user.
"""
stripped_url = url.strip()
if not stripped_url:
raise UrlError(
"Invalid url format. Url is empty.",
title="Invalid url format",
hints=["url seems to be empty"]
)
# Not sure if this is good idea?
modified_url = stripped_url.rstrip("/")
# Make sure url has http scheme
if not modified_url.lower().startswith("http"):
modified_url = f"http://{modified_url}"
parsed_url = _try_parse_url(modified_url)
universal_hints = [
"does the url work in browser?"
]
if parsed_url is None:
raise UrlError(
(
"Invalid url format. Url cannot be parsed"
f" as url \"{modified_url}\"."
),
title="Invalid url format",
hints=universal_hints
)
pathless_url = f"{parsed_url.scheme}://{parsed_url.netloc}"
if parsed_url.path:
new_url = _try_connect_to_server(
pathless_url,
timeout=timeout,
verify=verify,
cert=cert,
)
if new_url:
return new_url
new_url = _try_connect_to_server(
modified_url,
timeout=timeout,
verify=verify,
cert=cert,
)
if new_url:
return new_url
hints = []
if parsed_url.path:
hints.append(f"did you mean \"{pathless_url}\"?")
raise UrlNotReached(
f"Couldn't connect to server on \"{url}\"",
title="Couldn't connect to server",
hints=hints + universal_hints
)
class TransferProgress:
"""Object to store progress of download/upload from/to server."""
def __init__(self):
self._attempt: int = 0
self._started: bool = False
self._transfer_done: bool = False
self._transferred: int = 0
self._content_size: int | None = None
self._failed: bool = False
self._fail_reason: str | None = None
self._source_url: str = "N/A"
self._destination_url: str = "N/A"
def get_content_size(self) -> int | None:
"""Content size in bytes.
Returns:
int | None: Content size in bytes or None
if is unknown.
"""
return self._content_size
def set_content_size(self, content_size: int) -> None:
"""Set content size in bytes.
Args:
content_size (int): Content size in bytes.
Raises:
ValueError: If content size was already set.
"""
if self._content_size is not None:
raise ValueError("Content size was set more then once")
self._content_size = content_size
def get_started(self) -> bool:
"""Transfer was started.
Returns:
bool: True if transfer started.
"""
return self._started
def set_started(self) -> None:
"""Mark that transfer started.
Raises:
ValueError: If transfer was already started.
"""
if self._started:
raise ValueError("Progress already started")
self._started = True
self._attempt = 1
def get_attempt(self) -> int:
"""Find out which attempt of progress it is."""
return self._attempt
def next_attempt(self) -> None:
"""Start new attempt of progress."""
if not self._started:
raise ValueError("Progress did not start yet")