Skip to content

Commit 261d6e1

Browse files
committed
style: Format code with black
Line length: 120
1 parent cd4dee4 commit 261d6e1

File tree

1 file changed

+70
-50
lines changed

1 file changed

+70
-50
lines changed

src/mitmproxy_remote_interceptions.py

Lines changed: 70 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,9 @@ def load(loader: addonmanager.Loader) -> None:
2929

3030
async def running(self) -> None:
3131
self._server = await websockets.serve(
32-
self._ws_handler, "localhost", ctx.options.ws_port,
32+
self._ws_handler,
33+
"localhost",
34+
ctx.options.ws_port,
3335
compression=None,
3436
max_size=1024 * 1024 * 1024, # 1 GiB
3537
)
@@ -49,55 +51,57 @@ async def response(self, flow: http.HTTPFlow) -> None:
4951
await self._handle_http_message(flow, is_request=False)
5052

5153
async def _ws_handler(self, websocket: websockets.WebSocketServerProtocol) -> None:
52-
ctx.log.info(f"WebSocket API client connected (CID: \"{str(websocket.id)}\")")
54+
ctx.log.info(f'WebSocket API client connected (CID: "{str(websocket.id)}")')
5355
self._websockets.append(websocket)
5456

5557
while True:
5658
try:
5759
message = await websocket.recv()
5860
except (websockets.ConnectionClosedOK, websockets.ConnectionClosedError):
5961
self._websockets.remove(websocket)
60-
ctx.log.info(f"WebSocket API client disconnected (CID: \"{str(websocket.id)}\")")
62+
ctx.log.info(f'WebSocket API client disconnected (CID: "{str(websocket.id)}")')
6163
break
6264

6365
try:
6466
api_response: dict[str, object] = json.loads(message)
6567
except json.JSONDecodeError:
66-
ctx.log.warn(
67-
f"Invalid JSON received from WebSocket API client (CID: \"{str(websocket.id)}\"). Ignoring.")
68+
ctx.log.warn(f'Invalid JSON received from WebSocket API client (CID: "{str(websocket.id)}"). Ignoring.')
6869
continue
6970

7071
transaction_id: str | None = api_response.get("id")
7172
if transaction_id is None:
7273
ctx.log.warn(
7374
f"Received response from WebSocket API client without a transaction ID"
74-
f" (CID: \"{str(websocket.id)}\")"
75-
f". Ignoring.")
75+
f' (CID: "{str(websocket.id)}")'
76+
f". Ignoring."
77+
)
7678
continue
7779

7880
if transaction_id in self._pendingTransactions:
79-
ctx.log.debug(f"Received response from WebSocket API client"
80-
f" (CID: \"{str(websocket.id)}\", TID: {transaction_id})")
81+
ctx.log.debug(
82+
f"Received response from WebSocket API client"
83+
f' (CID: "{str(websocket.id)}", TID: {transaction_id})'
84+
)
8185
self._pendingTransactions[transaction_id].set_result(api_response)
8286
else:
83-
ctx.log.warn(f"Received response from WebSocket API with an unknown transaction ID"
84-
f" (CID: \"{str(websocket.id)}\", TID: \"{transaction_id}\")"
85-
f". Ignoring.")
87+
ctx.log.warn(
88+
f"Received response from WebSocket API with an unknown transaction ID"
89+
f' (CID: "{str(websocket.id)}", TID: "{transaction_id}")'
90+
f". Ignoring."
91+
)
8692

8793
async def _perform_transaction(
88-
self,
89-
websocket: websockets.WebSocketServerProtocol,
90-
api_request: dict[str, object]
94+
self,
95+
websocket: websockets.WebSocketServerProtocol,
96+
api_request: dict[str, object],
9197
) -> dict[str, object]:
9298
# Create a transaction ID, and prepare to receive a response.
9399
transaction_id: str = str(uuid.uuid4())
94-
pending_interception = \
95-
self._pendingTransactions[transaction_id] = asyncio.get_running_loop().create_future()
100+
pending_interception = self._pendingTransactions[transaction_id] = asyncio.get_running_loop().create_future()
96101

97102
# Add the transaction ID to the API request, wait for a response, and then remove the ID from the response.
98103
api_request["id"] = transaction_id
99-
ctx.log.debug(
100-
f"Sending request to WebSocket API client (CID: \"{str(websocket.id)}\", TID: \"{transaction_id}\")")
104+
ctx.log.debug(f'Sending request to WebSocket API client (CID: "{str(websocket.id)}", TID: "{transaction_id}")')
101105
await websocket.send(json.dumps(api_request))
102106
api_response: dict[str, object] = await pending_interception
103107
del api_response["id"]
@@ -118,13 +122,17 @@ async def _handle_http_message(self, flow: http.HTTPFlow, is_request: bool):
118122

119123
# Determine which full messages to send to the client.
120124
requested_message_settings: MessageSetSettings = MessageSetSettings.from_json(
121-
await self._perform_transaction(websocket, {
122-
"stage": "pre_request" if is_request else "pre_response",
123-
"flow_id": flow.id,
124-
"request_summary": _request_to_summary_json(flow.request),
125-
"response_summary":
126-
_response_to_summary_json(flow.response) if flow.response is not None else None,
127-
})
125+
await self._perform_transaction(
126+
websocket,
127+
{
128+
"stage": "pre_request" if is_request else "pre_response",
129+
"flow_id": flow.id,
130+
"request_summary": _request_to_summary_json(flow.request),
131+
"response_summary": _response_to_summary_json(flow.response)
132+
if flow.response is not None
133+
else None,
134+
},
135+
)
128136
)
129137

130138
# If no messages are requested, skip to the next client.
@@ -133,30 +141,36 @@ async def _handle_http_message(self, flow: http.HTTPFlow, is_request: bool):
133141

134142
# Send and receive the relevant messages.
135143
message_set: MessageSet = MessageSet.from_json(
136-
await self._perform_transaction(websocket, {
137-
"stage": "request" if is_request else "response",
138-
"flow_id": flow.id,
139-
"request": _request_to_json(flow.request) if requested_message_settings.send_request else None,
140-
"response": _response_to_json(flow.response) if (requested_message_settings.send_response
141-
and flow.response is not None) else None,
142-
})
144+
await self._perform_transaction(
145+
websocket,
146+
{
147+
"stage": "request" if is_request else "response",
148+
"flow_id": flow.id,
149+
"request": _request_to_json(flow.request) if requested_message_settings.send_request else None,
150+
"response": _response_to_json(flow.response)
151+
if (requested_message_settings.send_response and flow.response is not None)
152+
else None,
153+
},
154+
)
143155
)
144156

145157
# Use the received messages.
146158
if message_set.request is not None:
147159
if message_set.request.http_version == "RI/UNSET":
148-
message_set.request.http_version = flow.request.http_version \
149-
if flow.request is not None else "HTTP/1.1"
160+
message_set.request.http_version = (
161+
flow.request.http_version if flow.request is not None else "HTTP/1.1"
162+
)
150163
flow.request = message_set.request
151164
if message_set.response is not None:
152165
if message_set.response.http_version == "RI/UNSET":
153-
message_set.response.http_version = flow.response.http_version \
154-
if flow.response is not None else "HTTP/1.1"
166+
message_set.response.http_version = (
167+
flow.response.http_version if flow.response is not None else "HTTP/1.1"
168+
)
155169
flow.response = message_set.response
156170

157171

158172
addons: list[object] = [
159-
RemoteInterceptions()
173+
RemoteInterceptions(),
160174
]
161175

162176

@@ -199,12 +213,15 @@ def _request_from_json(request_json: dict[str, object]) -> http.Request:
199213
scheme=b"",
200214
authority=b"",
201215
path=b"",
202-
http_version=typing.cast(str, request_json["http_version"]
203-
if request_json["http_version"] is not None else "RI/UNSET").encode("utf-8", "surrogateescape"),
216+
http_version=typing.cast(
217+
str,
218+
request_json["http_version"] if request_json["http_version"] is not None else "RI/UNSET",
219+
).encode("utf-8", "surrogateescape"),
204220
headers=_headers_from_json(typing.cast(dict[str, list[str]], request_json["headers"])),
205221
content=None,
206222
trailers=_headers_from_json(typing.cast(dict[str, list[str]], request_json["trailers"]))
207-
if request_json["trailers"] is not None else None,
223+
if request_json["trailers"] is not None
224+
else None,
208225
timestamp_start=typing.cast(float, request_json["timestamp_start"]),
209226
timestamp_end=typing.cast(float, request_json["timestamp_end"]),
210227
)
@@ -239,14 +256,17 @@ def _response_to_summary_json(response: http.Response) -> dict[str, object]:
239256

240257
def _response_from_json(response_json: dict[str, object]) -> http.Response:
241258
response = http.Response(
242-
http_version=typing.cast(str, response_json["http_version"]
243-
if response_json["http_version"] is not None else "RI/UNSET").encode("utf-8", "surrogateescape"),
259+
http_version=typing.cast(
260+
str,
261+
response_json["http_version"] if response_json["http_version"] is not None else "RI/UNSET",
262+
).encode("utf-8", "surrogateescape"),
244263
status_code=typing.cast(int, response_json["status_code"]),
245264
reason=typing.cast(str, response_json["reason"] or "").encode("ISO-8859-1"),
246265
headers=_headers_from_json(typing.cast(dict[str, list[str]], response_json["headers"])),
247266
content=None,
248267
trailers=_headers_from_json(typing.cast(dict[str, list[str]], response_json["trailers"]))
249-
if response_json["trailers"] is not None else None,
268+
if response_json["trailers"] is not None
269+
else None,
250270
timestamp_start=typing.cast(float, response_json["timestamp_start"]),
251271
timestamp_end=typing.cast(float, response_json["timestamp_end"]),
252272
)
@@ -278,10 +298,10 @@ def __init__(self, request: http.Request | None, response: http.Response | None)
278298
@staticmethod
279299
def from_json(json_dict: dict[str, object]) -> MessageSet:
280300
return MessageSet(
281-
request=_request_from_json(
282-
typing.cast(dict[str, object], json_dict["request"]))
283-
if json_dict.get("request") is not None else None,
284-
response=_response_from_json(
285-
typing.cast(dict[str, object], json_dict["response"]))
286-
if json_dict.get("response") is not None else None,
301+
request=_request_from_json(typing.cast(dict[str, object], json_dict["request"]))
302+
if json_dict.get("request") is not None
303+
else None,
304+
response=_response_from_json(typing.cast(dict[str, object], json_dict["response"]))
305+
if json_dict.get("response") is not None
306+
else None,
287307
)

0 commit comments

Comments
 (0)