Debian Codegraph @

proton/session/transports/requests.py

raw
1 """
2 Copyright (c) 2023 Proton AG
3
4 This file is part of Proton.
5
6 Proton is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 Proton is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with ProtonVPN. If not, see <https://www.gnu.org/licenses/>.
18 """
19 import io
20
21 import requests
22
23 from ..formdata import FormData
24 from ..exceptions import *
25 from .base import Transport, RawResponse
26
27 import json
28
29 NOT_MODIFIED = 304
30
31 class RequestsTransport(Transport):
32 """ This is a simple transport based on the requests library, it's not advised to use in production """
33 def __init__(self, session, requests_session: requests.Session = None):
34 super().__init__(session)
35
36 self._s = requests_session or requests.Session()
37
38 @classmethod
39 def _get_priority(cls):
40 try:
41 return 3
42 except ImportError:
43 return None
44
45 def _build_raw(self, ret):
46 response = RawResponse(ret.status_code,
47 tuple(ret.headers.items()), None, None)
48
49 if ret.status_code == NOT_MODIFIED:
50 return response
51
52 response.data = ret.content
53
54 if ret.headers['content-type'] != 'application/octet-stream':
55 response.json = self._parse_json(ret, allow_unmodified=True)
56
57 return response
58
59 def _parse_json(self, ret, allow_unmodified=False):
60 if allow_unmodified and ret.status_code == NOT_MODIFIED:
61 return None
62
63 try:
64 ret_json = ret.json()
65 except json.decoder.JSONDecodeError:
66 raise ProtonAPIError(ret.status_code, dict(ret.headers), {})
67
68 if ret_json['Code'] not in [1000, 1001]:
69 raise ProtonAPIError(ret.status_code, dict(ret.headers), ret_json)
70
71 return ret_json
72
73 async def async_api_request(
74 self, endpoint,
75 jsondata=None, data=None, additional_headers=None,
76 method=None, params=None, return_raw=False
77 ):
78 self._s.headers['x-pm-appversion'] = self._session.appversion
79 self._s.headers['User-Agent'] = self._session.user_agent
80
81 if self._session.authenticated:
82 self._s.headers['x-pm-uid'] = self._session.UID
83 self._s.headers['Authorization'] = 'Bearer ' + self._session.AccessToken
84
85 # If we don't have an explicit method, default to get if there's no data, post otherwise
86 if method is None:
87 if not jsondata and not data:
88 fct = self._s.get
89 else:
90 fct = self._s.post
91 else:
92 fct = {
93 'get': self._s.get,
94 'post': self._s.post,
95 'put': self._s.put,
96 'delete': self._s.delete,
97 'patch': self._s.patch
98 }.get(method.lower())
99
100 if fct is None:
101 raise ValueError("Unknown method: {}".format(method))
102
103 data_dict = self._get_requests_data(data) if data else None
104 files_dict = self._get_requests_files(data) if data else None
105 try:
106 ret = fct(
107 self._environment.http_base_url + endpoint,
108 headers=additional_headers,
109 json=jsondata,
110 data=data_dict,
111 files=files_dict,
112 params=params
113 )
114 except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e:
115 raise ProtonAPINotReachable(e)
116 except (Exception, requests.exceptions.BaseHTTPError) as e:
117 raise ProtonAPIUnexpectedError(e)
118
119 if return_raw:
120 return self._build_raw(ret)
121
122 ret_json = self._parse_json(ret)
123
124 return ret_json
125
126 @staticmethod
127 def _get_requests_data(form_data: FormData) -> dict:
128 """
129 Converts the FormData instance to a dict that can be passed
130 as the data parameter in requests (e.g. `requests.post(url, data=data)`.
131
132 File-like fields are ignored, use `_get_requests_files` for those.
133 """
134 return {
135 field.name: field.value
136 for field in form_data.fields if not isinstance(field.value, io.IOBase)
137 }
138
139 @staticmethod
140 def _get_requests_files(form_data: FormData) -> dict:
141 """
142 Extracts the file-like fields to a dict that can be passed as the `files`
143 parameter in requests (e.g. `requests.post(url, files=files`).
144 """
145 # From https://requests.readthedocs.io/en/latest/api/#requests.request:
146 # files – (optional) Dictionary of 'name': file-like-objects
147 # (or {'name': file-tuple}) for multipart encoding upload. file-tuple
148 # can be a 2-tuple ('filename', fileobj), 3-tuple ('filename', fileobj, 'content_type')
149 # or a 4-tuple ('filename', fileobj, 'content_type', custom_headers),
150 # where 'content-type' is a string defining the content type of the
151 # given file and custom_headers a dict-like object containing additional
152 # headers to add for the file.
153 return {
154 field.name: (field.filename, field.value, field.content_type)
155 for field in form_data.fields if isinstance(field.value, io.IOBase)
156 }