alfred-python 0.6.4__py3-none-any.whl → 0.7.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- alfred/base/config.py +2 -1
- alfred/base/constants.py +98 -33
- alfred/base/exceptions.py +4 -10
- alfred/exceptions/__init__.py +465 -2
- alfred/http/http_client.py +255 -73
- alfred/http/typed.py +1 -0
- alfred/realtime/__init__.py +140 -27
- alfred/rest/__init__.py +14 -0
- alfred/rest/classifications/__init__.py +15 -0
- alfred/rest/classifications/base.py +55 -0
- alfred/rest/classifications/typed.py +145 -0
- alfred/rest/classifications/v1.py +77 -0
- alfred/rest/data_points/__init__.py +1 -0
- alfred/rest/data_points/base.py +9 -2
- alfred/rest/data_points/typed.py +109 -0
- alfred/rest/data_points/v1.py +12 -2
- alfred/rest/files/base.py +4 -2
- alfred/rest/files/typed.py +91 -18
- alfred/rest/files/v1.py +47 -13
- alfred/rest/jobs/base.py +102 -10
- alfred/rest/jobs/typed.py +160 -2
- alfred/rest/jobs/v1.py +316 -41
- alfred_python-0.7.0.dist-info/METADATA +148 -0
- alfred_python-0.7.0.dist-info/RECORD +40 -0
- {alfred_python-0.6.4.dist-info → alfred_python-0.7.0.dist-info}/WHEEL +1 -1
- {alfred_python-0.6.4.dist-info → alfred_python-0.7.0.dist-info/licenses}/LICENSE +1 -1
- alfred_python-0.6.4.dist-info/METADATA +0 -416
- alfred_python-0.6.4.dist-info/RECORD +0 -35
- {alfred_python-0.6.4.dist-info → alfred_python-0.7.0.dist-info}/top_level.txt +0 -0
alfred/base/config.py
CHANGED
alfred/base/constants.py
CHANGED
|
@@ -19,76 +19,141 @@ class EventType(Enum):
|
|
|
19
19
|
|
|
20
20
|
|
|
21
21
|
class FileEvent(Enum):
|
|
22
|
+
"""
|
|
23
|
+
Events of the file event stream (`file_event`). Each value is the
|
|
24
|
+
`event_name` Alfred puts in the event data, except FILE_REMOVE_TAG_EVENT,
|
|
25
|
+
which Alfred sends under the name of another event (see its comment).
|
|
26
|
+
"""
|
|
27
|
+
# Defined by the platform; Alfred 1.130.0 does not send it.
|
|
28
|
+
FILE_CREATE_EVENT = "alfred_event_file_create"
|
|
29
|
+
|
|
22
30
|
# Triggered when a file is added to a job for processing.
|
|
23
|
-
FILE_ADD_TO_JOB_EVENT = "
|
|
31
|
+
FILE_ADD_TO_JOB_EVENT = "alfred_event_file_added_to_job"
|
|
24
32
|
|
|
25
33
|
# Occurs when a new category is created for a file.
|
|
26
|
-
FILE_CATEGORY_CREATE_EVENT = "
|
|
34
|
+
FILE_CATEGORY_CREATE_EVENT = "alfred_event_file_category_create"
|
|
27
35
|
|
|
28
36
|
# Signals the deletion of a file's category.
|
|
29
|
-
FILE_CATEGORY_DELETE_EVENT = "
|
|
37
|
+
FILE_CATEGORY_DELETE_EVENT = "alfred_event_file_category_delete"
|
|
30
38
|
|
|
31
|
-
# Indicates a change in the tag associated with a file.
|
|
32
|
-
|
|
39
|
+
# Indicates a change in the tag associated with a file. Alfred sends tag
|
|
40
|
+
# removals under this name too (see FILE_REMOVE_TAG_EVENT).
|
|
41
|
+
FILE_CHANGE_TAG_EVENT = "alfred_event_file_change_tag"
|
|
42
|
+
|
|
43
|
+
# Signals that a file was decomposed into other files.
|
|
44
|
+
FILE_DECOMPOSED_EVENT = "alfred_event_file_decomposed"
|
|
33
45
|
|
|
34
46
|
# Marks the completion of file processing.
|
|
35
|
-
FILE_DONE_EVENT = "
|
|
47
|
+
FILE_DONE_EVENT = "alfred_event_file_done"
|
|
36
48
|
|
|
37
49
|
# Triggered when new data is extracted from a file.
|
|
38
|
-
FILE_EXTRACTED_DATA_CREATE_EVENT = "
|
|
50
|
+
FILE_EXTRACTED_DATA_CREATE_EVENT = "alfred_event_file_extracted_data_create"
|
|
39
51
|
|
|
40
52
|
# Occurs when extracted data from a file is deleted.
|
|
41
|
-
FILE_EXTRACTED_DATA_DELETE_EVENT = "
|
|
53
|
+
FILE_EXTRACTED_DATA_DELETE_EVENT = "alfred_event_file_extracted_data_delete"
|
|
42
54
|
|
|
43
55
|
# Indicates a failure in file processing.
|
|
44
|
-
FILE_FAILED_EVENT = "
|
|
56
|
+
FILE_FAILED_EVENT = "alfred_event_file_failed"
|
|
45
57
|
|
|
46
58
|
# Signals the movement of a file within the system.
|
|
47
|
-
FILE_MOVE_EVENT = "
|
|
59
|
+
FILE_MOVE_EVENT = "alfred_event_file_move"
|
|
60
|
+
|
|
61
|
+
# Triggered when a file is moved to the decomposed state.
|
|
62
|
+
FILE_MOVE_TO_DECOMPOSED_EVENT = "alfred_event_file_move_to_decomposed"
|
|
48
63
|
|
|
49
64
|
# Triggered when a file is moved to a pending state.
|
|
50
|
-
FILE_MOVE_TO_PENDING_EVENT = "
|
|
65
|
+
FILE_MOVE_TO_PENDING_EVENT = "alfred_event_file_move_to_pending"
|
|
51
66
|
|
|
52
67
|
# Indicates movement of a file to the recycle bin.
|
|
53
|
-
FILE_MOVE_TO_RECYCLE_BIN_EVENT = "
|
|
68
|
+
FILE_MOVE_TO_RECYCLE_BIN_EVENT = "alfred_event_file_move_to_recycle_bin"
|
|
54
69
|
|
|
55
70
|
# Reflects the creation of a file property.
|
|
56
|
-
FILE_PROPERTY_CREATE_EVENT = "
|
|
71
|
+
FILE_PROPERTY_CREATE_EVENT = "alfred_event_file_property_create"
|
|
57
72
|
|
|
58
73
|
# Signals the deletion of a file property.
|
|
59
|
-
FILE_PROPERTY_DELETE_EVENT = "
|
|
74
|
+
FILE_PROPERTY_DELETE_EVENT = "alfred_event_file_property_delete"
|
|
60
75
|
|
|
61
|
-
# Signals the removal of a tag from a file.
|
|
62
|
-
|
|
76
|
+
# Signals the removal of a tag from a file. Alfred has no event name of its
|
|
77
|
+
# own for this: it sends `alfred_event_file_change_tag` with
|
|
78
|
+
# `tag_being_removed_id` in the data. The value below is the SDK's name for
|
|
79
|
+
# the subscription, and the real-time client delivers those events to it.
|
|
80
|
+
FILE_REMOVE_TAG_EVENT = "alfred_event_file_remove_tag"
|
|
63
81
|
|
|
64
82
|
# Indicates an update in the file's status.
|
|
65
|
-
FILE_STATUS_UPDATE_EVENT = "
|
|
83
|
+
FILE_STATUS_UPDATE_EVENT = "alfred_event_file_status_update"
|
|
66
84
|
|
|
67
|
-
#
|
|
68
|
-
FILE_UPDATE_EVENT = "
|
|
85
|
+
# Defined by the platform; Alfred 1.130.0 does not send it.
|
|
86
|
+
FILE_UPDATE_EVENT = "alfred_event_file_update"
|
|
69
87
|
|
|
70
88
|
|
|
71
89
|
class JobEvent(Enum):
|
|
90
|
+
"""
|
|
91
|
+
Events of the job event stream (`job_event`). Each value is the
|
|
92
|
+
`event_name` Alfred puts in the event data, except
|
|
93
|
+
JOB_EXCEEDED_RETRIES_EVENT, which Alfred sends under the name of another
|
|
94
|
+
event (see its comment).
|
|
95
|
+
"""
|
|
72
96
|
# Triggered when a new job is instantiated for file operations.
|
|
73
|
-
JOB_CREATE_EVENT = "
|
|
97
|
+
JOB_CREATE_EVENT = "alfred_event_job_create"
|
|
74
98
|
|
|
75
|
-
#
|
|
76
|
-
|
|
99
|
+
# Triggered when job begins its workflow and state machine.
|
|
100
|
+
JOB_START_EVENT = "alfred_event_job_start"
|
|
77
101
|
|
|
78
|
-
# Occurs when
|
|
79
|
-
|
|
102
|
+
# Occurs when job transitions from one workflow stage to another.
|
|
103
|
+
JOB_STAGE_UPDATE_EVENT = "alfred_event_job_stage_update"
|
|
80
104
|
|
|
81
|
-
#
|
|
82
|
-
|
|
105
|
+
# Every event Alfred names `alfred_event_job_retry`. Alfred 1.130.0 sends
|
|
106
|
+
# it only after JOB_FAILED_EVENT, when the job has used up its retries
|
|
107
|
+
# (see JOB_EXCEEDED_RETRIES_EVENT), and not when a job is retried.
|
|
108
|
+
JOB_RETRY_EVENT = "alfred_event_job_retry"
|
|
109
|
+
|
|
110
|
+
# Fires when a job has used up its retries. Alfred has no event name of its
|
|
111
|
+
# own for this: it sends `alfred_event_job_retry` with `exceeded_retries`
|
|
112
|
+
# set to true. The value below is the SDK's name for the subscription, and
|
|
113
|
+
# the real-time client delivers those events to it.
|
|
114
|
+
JOB_EXCEEDED_RETRIES_EVENT = "alfred_event_job_exceeded_retries"
|
|
83
115
|
|
|
84
116
|
# Fires when job fails initial validation of input files or parameters.
|
|
85
|
-
JOB_INVALID_EVENT = "
|
|
117
|
+
JOB_INVALID_EVENT = "alfred_event_job_invalid"
|
|
86
118
|
|
|
87
|
-
#
|
|
88
|
-
|
|
119
|
+
# Occurs when a job halts due to an unrecoverable error.
|
|
120
|
+
JOB_FAILED_EVENT = "alfred_event_job_failed"
|
|
89
121
|
|
|
90
|
-
#
|
|
91
|
-
|
|
122
|
+
# Triggered when a job is cancelled.
|
|
123
|
+
JOB_CANCELLED_EVENT = "alfred_event_job_cancelled"
|
|
92
124
|
|
|
93
|
-
# Triggered when job
|
|
94
|
-
|
|
125
|
+
# Triggered when a job expires.
|
|
126
|
+
JOB_EXPIRED_EVENT = "alfred_event_job_expired"
|
|
127
|
+
|
|
128
|
+
# Triggered when job successfully completes all workflow stages.
|
|
129
|
+
JOB_FINISHED_EVENT = "alfred_event_job_finished"
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# Event names used by earlier SDK versions, mapped to the values of the
|
|
133
|
+
# members above.
|
|
134
|
+
LEGACY_EVENT_NAMES = {
|
|
135
|
+
"file_add_to_job_event": "alfred_event_file_added_to_job",
|
|
136
|
+
"file_category_create_event": "alfred_event_file_category_create",
|
|
137
|
+
"file_category_delete_event": "alfred_event_file_category_delete",
|
|
138
|
+
"file_change_tag_event": "alfred_event_file_change_tag",
|
|
139
|
+
"file_done_event": "alfred_event_file_done",
|
|
140
|
+
"file_extracted_data_create_event": "alfred_event_file_extracted_data_create",
|
|
141
|
+
"file_extracted_data_delete_event": "alfred_event_file_extracted_data_delete",
|
|
142
|
+
"file_failed_event": "alfred_event_file_failed",
|
|
143
|
+
"file_move_event": "alfred_event_file_move",
|
|
144
|
+
"file_move_to_pending_event": "alfred_event_file_move_to_pending",
|
|
145
|
+
"file_move_to_recycle_bin_event": "alfred_event_file_move_to_recycle_bin",
|
|
146
|
+
"file_property_create_event": "alfred_event_file_property_create",
|
|
147
|
+
"file_property_delete_event": "alfred_event_file_property_delete",
|
|
148
|
+
"file_remove_tag_event": "alfred_event_file_remove_tag",
|
|
149
|
+
"file_status_update_event": "alfred_event_file_status_update",
|
|
150
|
+
"file_update_event": "alfred_event_file_update",
|
|
151
|
+
"job_create_event": "alfred_event_job_create",
|
|
152
|
+
"job_exceeded_retries_event": "alfred_event_job_exceeded_retries",
|
|
153
|
+
"job_failed_event": "alfred_event_job_failed",
|
|
154
|
+
"job_finished_event": "alfred_event_job_finished",
|
|
155
|
+
"job_invalid_event": "alfred_event_job_invalid",
|
|
156
|
+
"job_retry_event": "alfred_event_job_retry",
|
|
157
|
+
"job_stage_update_event": "alfred_event_job_stage_update",
|
|
158
|
+
"job_start_event": "alfred_event_job_start",
|
|
159
|
+
}
|
alfred/base/exceptions.py
CHANGED
|
@@ -1,11 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
"""
|
|
1
|
+
# The classes live in ``alfred.exceptions``; these names stay importable from
|
|
2
|
+
# here for existing code.
|
|
3
|
+
from alfred.exceptions import AlfredMissingArgument, AlfredMissingAuthException
|
|
5
4
|
|
|
6
|
-
|
|
7
|
-
class AlfredMissingArgument(Exception):
|
|
8
|
-
"""
|
|
9
|
-
Raised when a payload is missing a required argument based on the whole context
|
|
10
|
-
of the operation.
|
|
11
|
-
"""
|
|
5
|
+
__all__ = ["AlfredMissingAuthException", "AlfredMissingArgument"]
|
alfred/exceptions/__init__.py
CHANGED
|
@@ -1,7 +1,470 @@
|
|
|
1
|
-
|
|
1
|
+
"""
|
|
2
|
+
Exceptions raised by the Alfred SDK.
|
|
3
|
+
|
|
4
|
+
Everything the SDK raises on purpose derives from :class:`AlfredError`. The
|
|
5
|
+
errors that describe a failed HTTP call also inherit from the matching
|
|
6
|
+
``requests`` exception, so code written against ``requests`` keeps working.
|
|
7
|
+
|
|
8
|
+
This module must not import anything else from the ``alfred`` package: both
|
|
9
|
+
``alfred.base`` and ``alfred.http`` import it.
|
|
10
|
+
"""
|
|
11
|
+
# Native imports
|
|
12
|
+
import html
|
|
13
|
+
import json
|
|
14
|
+
import re
|
|
15
|
+
from datetime import datetime, timezone
|
|
16
|
+
from email.utils import parsedate_to_datetime
|
|
17
|
+
from http import HTTPStatus
|
|
18
|
+
from typing import Any, Dict, List, Optional, Text, Type
|
|
19
|
+
from urllib.parse import urlsplit, urlunsplit
|
|
20
|
+
|
|
21
|
+
# 3rd party imports
|
|
22
|
+
import requests
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"AlfredError",
|
|
26
|
+
"AlfredMissingAuthException",
|
|
27
|
+
"AlfredMissingArgument",
|
|
28
|
+
"ConnectionError",
|
|
29
|
+
"AlfredRequestError",
|
|
30
|
+
"AlfredConnectionError",
|
|
31
|
+
"AlfredTimeoutError",
|
|
32
|
+
"AlfredConnectTimeoutError",
|
|
33
|
+
"AlfredResponseParseError",
|
|
34
|
+
"AlfredApiError",
|
|
35
|
+
"AlfredBadRequestError",
|
|
36
|
+
"AlfredAuthenticationError",
|
|
37
|
+
"AlfredPermissionError",
|
|
38
|
+
"AlfredNotFoundError",
|
|
39
|
+
"AlfredConflictError",
|
|
40
|
+
"AlfredPayloadTooLargeError",
|
|
41
|
+
"AlfredRateLimitError",
|
|
42
|
+
"AlfredServerError",
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
# Longest message kept from a server answer. Keeps an HTML error page out of
|
|
46
|
+
# exception messages and logs.
|
|
47
|
+
MAX_MESSAGE_LENGTH = 300
|
|
48
|
+
|
|
49
|
+
_JSON_START = ('{', '[', '"')
|
|
50
|
+
_HTML_BLOCKS = re.compile(r"<(script|style)\b.*?</\1\s*>", re.IGNORECASE | re.DOTALL)
|
|
51
|
+
_HTML_TAGS = re.compile(r"<[^>]*>")
|
|
52
|
+
_SECONDS = re.compile(r"^\d+(\.\d+)?$")
|
|
53
|
+
_MESSAGE_KEYS = ("message", "Message", "error_description", "error", "detail")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _rebuild_error(cls, args, state, dropped):
|
|
57
|
+
error = cls.__new__(cls, *args)
|
|
58
|
+
error.args = args
|
|
59
|
+
error.__dict__.update(state)
|
|
60
|
+
for name in dropped:
|
|
61
|
+
setattr(error, name, None)
|
|
62
|
+
return error
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class AlfredError(Exception):
|
|
2
66
|
"""
|
|
3
|
-
|
|
67
|
+
Base class of every exception the Alfred SDK raises on purpose.
|
|
4
68
|
"""
|
|
69
|
+
|
|
70
|
+
def __reduce__(self):
|
|
71
|
+
# Lets errors cross process boundaries (multiprocessing, concurrent.futures).
|
|
72
|
+
# The ``requests`` response and request are not picklable, so they are dropped.
|
|
73
|
+
state = dict(vars(self))
|
|
74
|
+
dropped = [name for name in ("response", "request") if name in state]
|
|
75
|
+
for name in dropped:
|
|
76
|
+
del state[name]
|
|
77
|
+
return (_rebuild_error, (type(self), self.args, state, dropped))
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class AlfredMissingAuthException(AlfredError):
|
|
81
|
+
"""
|
|
82
|
+
Raised when proper authentication/authorization have not been provided.
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class AlfredMissingArgument(AlfredError):
|
|
87
|
+
"""
|
|
88
|
+
Raised when a payload is missing a required argument based on the whole context
|
|
89
|
+
of the operation.
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class ConnectionError(AlfredError): # pylint: disable=redefined-builtin
|
|
94
|
+
"""
|
|
95
|
+
Raised when the realtime connection cannot be established.
|
|
96
|
+
"""
|
|
97
|
+
|
|
5
98
|
def __init__(self, message="A connection error occurred"):
|
|
6
99
|
self.message = message
|
|
7
100
|
super().__init__(self.message)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _safe_url(url: Optional[Text]) -> Optional[Text]:
|
|
104
|
+
"""
|
|
105
|
+
Return the URL without credentials, query string or fragment, so it can be
|
|
106
|
+
shown in messages and logs.
|
|
107
|
+
"""
|
|
108
|
+
if not url:
|
|
109
|
+
return None
|
|
110
|
+
try:
|
|
111
|
+
parts = urlsplit(url)
|
|
112
|
+
netloc = parts.netloc.rpartition("@")[2]
|
|
113
|
+
return urlunsplit((parts.scheme, netloc, parts.path, "", ""))
|
|
114
|
+
except ValueError:
|
|
115
|
+
return None
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _cap(text: Text, limit: int = MAX_MESSAGE_LENGTH) -> Text:
|
|
119
|
+
text = " ".join(text.split())
|
|
120
|
+
if len(text) > limit:
|
|
121
|
+
return text[: limit - 3].rstrip() + "..."
|
|
122
|
+
return text
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _clean_text(text: Text) -> Text:
|
|
126
|
+
"""
|
|
127
|
+
Reduce server text to a short single line. Markup is removed first, so an
|
|
128
|
+
HTML error page from a gateway yields its visible words, not its source.
|
|
129
|
+
"""
|
|
130
|
+
if text.lstrip().startswith("<"):
|
|
131
|
+
text = _HTML_BLOCKS.sub(" ", text)
|
|
132
|
+
text = html.unescape(_HTML_TAGS.sub(" ", text))
|
|
133
|
+
return _cap(text)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _message_from_body(body: Any) -> Optional[Text]:
|
|
137
|
+
"""
|
|
138
|
+
Pull the most human-readable message out of a parsed error body.
|
|
139
|
+
"""
|
|
140
|
+
if isinstance(body, str):
|
|
141
|
+
return _clean_text(body) or None
|
|
142
|
+
if isinstance(body, dict):
|
|
143
|
+
for key in _MESSAGE_KEYS:
|
|
144
|
+
value = body.get(key)
|
|
145
|
+
if isinstance(value, (str, dict)):
|
|
146
|
+
found = _message_from_body(value)
|
|
147
|
+
if found:
|
|
148
|
+
return found
|
|
149
|
+
reasons = _error_list(body)
|
|
150
|
+
if reasons:
|
|
151
|
+
return _cap("; ".join(reasons))
|
|
152
|
+
return None
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _error_list(body: Any) -> List[Text]:
|
|
156
|
+
"""
|
|
157
|
+
The reasons some endpoints send as a list of strings under ``errors``
|
|
158
|
+
(for example a refused classification request). Empty when there is none.
|
|
159
|
+
"""
|
|
160
|
+
if isinstance(body, dict):
|
|
161
|
+
value = body.get("errors")
|
|
162
|
+
if isinstance(value, list):
|
|
163
|
+
return [item.strip() for item in value if isinstance(item, str) and item.strip()]
|
|
164
|
+
return []
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _string_field(body: Any, *names: Text) -> Optional[Text]:
|
|
168
|
+
if isinstance(body, dict):
|
|
169
|
+
for name in names:
|
|
170
|
+
value = body.get(name)
|
|
171
|
+
if isinstance(value, str) and value.strip():
|
|
172
|
+
return value.strip()
|
|
173
|
+
return None
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _int_field(body: Any, name: Text) -> Optional[int]:
|
|
177
|
+
if not isinstance(body, dict):
|
|
178
|
+
return None
|
|
179
|
+
value = body.get(name)
|
|
180
|
+
if isinstance(value, bool):
|
|
181
|
+
return None
|
|
182
|
+
if isinstance(value, int):
|
|
183
|
+
return value
|
|
184
|
+
if isinstance(value, str) and value.strip().isdigit():
|
|
185
|
+
return int(value.strip())
|
|
186
|
+
return None
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _parse_body(response: requests.Response) -> Any:
|
|
190
|
+
"""
|
|
191
|
+
Return the parsed JSON body, the text, or None when the body is empty.
|
|
192
|
+
Never raises: a body that claims to be JSON but is not is returned as text.
|
|
193
|
+
"""
|
|
194
|
+
try:
|
|
195
|
+
text = response.text
|
|
196
|
+
except Exception: # pylint: disable=broad-except
|
|
197
|
+
return None
|
|
198
|
+
if not text or not text.strip():
|
|
199
|
+
return None
|
|
200
|
+
content_type = (response.headers.get("Content-Type") or "").lower()
|
|
201
|
+
if "json" in content_type or text.lstrip().startswith(_JSON_START):
|
|
202
|
+
try:
|
|
203
|
+
return json.loads(text)
|
|
204
|
+
except ValueError:
|
|
205
|
+
pass
|
|
206
|
+
return text
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def parse_retry_after(value: Optional[Text]) -> Optional[float]:
|
|
210
|
+
"""
|
|
211
|
+
Convert a ``Retry-After`` header (seconds or an HTTP date) to seconds.
|
|
212
|
+
Returns None when the header is absent or not understood.
|
|
213
|
+
"""
|
|
214
|
+
if not value:
|
|
215
|
+
return None
|
|
216
|
+
value = value.strip()
|
|
217
|
+
if _SECONDS.match(value):
|
|
218
|
+
return float(value)
|
|
219
|
+
try:
|
|
220
|
+
when = parsedate_to_datetime(value)
|
|
221
|
+
except (TypeError, ValueError, IndexError):
|
|
222
|
+
return None
|
|
223
|
+
if when.tzinfo is None:
|
|
224
|
+
when = when.replace(tzinfo=timezone.utc)
|
|
225
|
+
return max(0.0, (when - datetime.now(timezone.utc)).total_seconds())
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _phrase(status_code: Optional[int], response: Optional[requests.Response]) -> Text:
|
|
229
|
+
reason = getattr(response, "reason", None)
|
|
230
|
+
if isinstance(reason, str) and reason.strip():
|
|
231
|
+
return reason.strip()
|
|
232
|
+
try:
|
|
233
|
+
return HTTPStatus(status_code).phrase
|
|
234
|
+
except ValueError:
|
|
235
|
+
return "Error"
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _describe(method: Optional[Text], url: Optional[Text]) -> Text:
|
|
239
|
+
return " ".join(part for part in (method, url) if part)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
class AlfredRequestError(AlfredError, requests.exceptions.RequestException):
|
|
243
|
+
"""
|
|
244
|
+
The request never produced an answer from the API (network failure).
|
|
245
|
+
|
|
246
|
+
Attributes:
|
|
247
|
+
- message: What went wrong, without the query string of the URL.
|
|
248
|
+
- method, url: The request that failed; url has no query string.
|
|
249
|
+
- request: The prepared ``requests`` request.
|
|
250
|
+
"""
|
|
251
|
+
|
|
252
|
+
def __init__(
|
|
253
|
+
self,
|
|
254
|
+
message: Optional[Text] = None,
|
|
255
|
+
*,
|
|
256
|
+
method: Optional[Text] = None,
|
|
257
|
+
url: Optional[Text] = None,
|
|
258
|
+
request: Any = None,
|
|
259
|
+
):
|
|
260
|
+
self.message = message or "The request failed"
|
|
261
|
+
self.method = method
|
|
262
|
+
self.url = _safe_url(url)
|
|
263
|
+
text = self.message
|
|
264
|
+
target = _describe(method, self.url)
|
|
265
|
+
if target:
|
|
266
|
+
text = f"{target}: {text}"
|
|
267
|
+
super().__init__(text, request=request)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
class AlfredConnectionError(AlfredRequestError, requests.exceptions.ConnectionError):
|
|
271
|
+
"""
|
|
272
|
+
DNS failure, refused or reset connection, TLS failure.
|
|
273
|
+
"""
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
class AlfredTimeoutError(AlfredRequestError, requests.exceptions.Timeout):
|
|
277
|
+
"""
|
|
278
|
+
The API did not answer within the timeout.
|
|
279
|
+
"""
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
class AlfredConnectTimeoutError(
|
|
283
|
+
AlfredTimeoutError, AlfredConnectionError, requests.exceptions.ConnectTimeout
|
|
284
|
+
):
|
|
285
|
+
"""
|
|
286
|
+
The connection could not be opened within the timeout. It is both a
|
|
287
|
+
timeout and a connection error, like ``requests.exceptions.ConnectTimeout``.
|
|
288
|
+
"""
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
class AlfredResponseParseError(AlfredError, ValueError):
|
|
292
|
+
"""
|
|
293
|
+
A successful response whose body could not be parsed.
|
|
294
|
+
|
|
295
|
+
Attributes:
|
|
296
|
+
- response: The ``requests`` response.
|
|
297
|
+
- status_code: HTTP status of that response.
|
|
298
|
+
"""
|
|
299
|
+
|
|
300
|
+
def __init__(self, message: Text, *, response: Any = None):
|
|
301
|
+
self.response = response
|
|
302
|
+
self.status_code = getattr(response, "status_code", None)
|
|
303
|
+
super().__init__(message)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
class AlfredApiError(AlfredError, requests.exceptions.HTTPError):
|
|
307
|
+
"""
|
|
308
|
+
The API answered with a 4xx or 5xx status.
|
|
309
|
+
|
|
310
|
+
Use :meth:`from_response` to build the right subclass for a response.
|
|
311
|
+
|
|
312
|
+
Attributes:
|
|
313
|
+
- status_code: HTTP status code.
|
|
314
|
+
- message: Best human-readable message found in the answer.
|
|
315
|
+
- reason: The server's machine-readable ``reason``, when it sent one.
|
|
316
|
+
- correlation_id: The server's error reference for support, when present.
|
|
317
|
+
It is not the correlation id of a job.
|
|
318
|
+
- errors: The individual reasons, when the answer lists them under
|
|
319
|
+
``errors``; otherwise an empty list.
|
|
320
|
+
- body: Parsed JSON body, the text of a non-JSON body, or None if empty.
|
|
321
|
+
- response, request: The ``requests`` objects.
|
|
322
|
+
- method, url: The request; url has no query string or credentials.
|
|
323
|
+
"""
|
|
324
|
+
|
|
325
|
+
def __init__(
|
|
326
|
+
self,
|
|
327
|
+
message: Optional[Text] = None,
|
|
328
|
+
*,
|
|
329
|
+
status_code: Optional[int] = None,
|
|
330
|
+
reason: Optional[Text] = None,
|
|
331
|
+
correlation_id: Optional[Text] = None,
|
|
332
|
+
errors: Optional[List[Text]] = None,
|
|
333
|
+
body: Any = None,
|
|
334
|
+
response: Any = None,
|
|
335
|
+
request: Any = None,
|
|
336
|
+
method: Optional[Text] = None,
|
|
337
|
+
url: Optional[Text] = None,
|
|
338
|
+
):
|
|
339
|
+
if request is None and response is not None:
|
|
340
|
+
request = getattr(response, "request", None)
|
|
341
|
+
self.status_code = status_code
|
|
342
|
+
self.reason = reason
|
|
343
|
+
self.correlation_id = correlation_id
|
|
344
|
+
self.errors = list(errors or [])
|
|
345
|
+
self.body = body
|
|
346
|
+
self.method = method
|
|
347
|
+
self.url = _safe_url(url)
|
|
348
|
+
phrase = _phrase(status_code, response)
|
|
349
|
+
self.message = message or phrase
|
|
350
|
+
text = " ".join(
|
|
351
|
+
part
|
|
352
|
+
for part in (str(status_code) if status_code is not None else "", phrase)
|
|
353
|
+
if part
|
|
354
|
+
)
|
|
355
|
+
target = _describe(method, self.url)
|
|
356
|
+
if target:
|
|
357
|
+
text = f"{text} for {target}" if text else target
|
|
358
|
+
if self.message != phrase:
|
|
359
|
+
text = f"{text}: {self.message}" if text else self.message
|
|
360
|
+
super().__init__(text or self.message, response=response, request=request)
|
|
361
|
+
|
|
362
|
+
@classmethod
|
|
363
|
+
def from_response(
|
|
364
|
+
cls, response: requests.Response, message: Optional[Text] = None
|
|
365
|
+
) -> "AlfredApiError":
|
|
366
|
+
"""
|
|
367
|
+
Build the exception for an error response.
|
|
368
|
+
|
|
369
|
+
Called on :class:`AlfredApiError` itself the class is chosen from the
|
|
370
|
+
status code; called on a subclass that class is used.
|
|
371
|
+
"""
|
|
372
|
+
status = response.status_code
|
|
373
|
+
error_class = cls if cls is not AlfredApiError else _class_for_status(status)
|
|
374
|
+
body = _parse_body(response)
|
|
375
|
+
request = getattr(response, "request", None)
|
|
376
|
+
kwargs: Dict[str, Any] = {
|
|
377
|
+
"status_code": status,
|
|
378
|
+
"message": message or _message_from_body(body) or _phrase(status, response),
|
|
379
|
+
"reason": _string_field(body, "reason"),
|
|
380
|
+
"correlation_id": _string_field(
|
|
381
|
+
body, "correlation_id", "correlationId", "CorrelationId"
|
|
382
|
+
),
|
|
383
|
+
"errors": _error_list(body),
|
|
384
|
+
"body": body,
|
|
385
|
+
"response": response,
|
|
386
|
+
"request": request,
|
|
387
|
+
"method": getattr(request, "method", None),
|
|
388
|
+
"url": getattr(request, "url", None) or response.url,
|
|
389
|
+
}
|
|
390
|
+
if issubclass(error_class, (AlfredRateLimitError, AlfredServerError)):
|
|
391
|
+
kwargs["retry_after"] = parse_retry_after(response.headers.get("Retry-After"))
|
|
392
|
+
if issubclass(error_class, AlfredPayloadTooLargeError):
|
|
393
|
+
kwargs["max_bytes"] = _int_field(body, "max_bytes")
|
|
394
|
+
return error_class(**kwargs)
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
class AlfredBadRequestError(AlfredApiError):
|
|
398
|
+
"""400: the request was rejected as invalid."""
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
class AlfredAuthenticationError(AlfredApiError):
|
|
402
|
+
"""401, or a refused OAuth token request."""
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
class AlfredPermissionError(AlfredApiError):
|
|
406
|
+
"""403: authenticated, but not allowed (role, suspended account, user agent)."""
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
class AlfredNotFoundError(AlfredApiError):
|
|
410
|
+
"""404: the resource does not exist (or is not visible to the caller)."""
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
class AlfredConflictError(AlfredApiError):
|
|
414
|
+
"""409: the resource is in a state that refuses the operation."""
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
class AlfredPayloadTooLargeError(AlfredApiError):
|
|
418
|
+
"""
|
|
419
|
+
413: the file or body is over the size limit.
|
|
420
|
+
|
|
421
|
+
Attribute ``max_bytes``: the limit reported by the server, or None.
|
|
422
|
+
"""
|
|
423
|
+
|
|
424
|
+
def __init__(self, *args, max_bytes: Optional[int] = None, **kwargs):
|
|
425
|
+
self.max_bytes = max_bytes
|
|
426
|
+
super().__init__(*args, **kwargs)
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
class AlfredRateLimitError(AlfredApiError):
|
|
430
|
+
"""
|
|
431
|
+
429: too many calls.
|
|
432
|
+
|
|
433
|
+
Attribute ``retry_after``: seconds to wait from the ``Retry-After``
|
|
434
|
+
header, or None when the server did not send a usable one.
|
|
435
|
+
"""
|
|
436
|
+
|
|
437
|
+
def __init__(self, *args, retry_after: Optional[float] = None, **kwargs):
|
|
438
|
+
self.retry_after = retry_after
|
|
439
|
+
super().__init__(*args, **kwargs)
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
class AlfredServerError(AlfredApiError):
|
|
443
|
+
"""
|
|
444
|
+
5xx: the server or a gateway in front of it failed.
|
|
445
|
+
|
|
446
|
+
Attribute ``retry_after``: seconds from the ``Retry-After`` header, or None.
|
|
447
|
+
"""
|
|
448
|
+
|
|
449
|
+
def __init__(self, *args, retry_after: Optional[float] = None, **kwargs):
|
|
450
|
+
self.retry_after = retry_after
|
|
451
|
+
super().__init__(*args, **kwargs)
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
_STATUS_CLASSES: Dict[int, Type[AlfredApiError]] = {
|
|
455
|
+
400: AlfredBadRequestError,
|
|
456
|
+
401: AlfredAuthenticationError,
|
|
457
|
+
403: AlfredPermissionError,
|
|
458
|
+
404: AlfredNotFoundError,
|
|
459
|
+
409: AlfredConflictError,
|
|
460
|
+
413: AlfredPayloadTooLargeError,
|
|
461
|
+
429: AlfredRateLimitError,
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def _class_for_status(status_code: int) -> Type[AlfredApiError]:
|
|
466
|
+
if status_code in _STATUS_CLASSES:
|
|
467
|
+
return _STATUS_CLASSES[status_code]
|
|
468
|
+
if 500 <= status_code <= 599:
|
|
469
|
+
return AlfredServerError
|
|
470
|
+
return AlfredApiError
|