Skip to content

Commit

Permalink
Fixed mypy errors
Browse files Browse the repository at this point in the history
  • Loading branch information
qstokkink committed Oct 4, 2024
1 parent a991174 commit 6082776
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 23 deletions.
13 changes: 8 additions & 5 deletions src/tribler/core/libtorrent/restapi/downloads_endpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -406,11 +406,14 @@ async def add_download(self, request: Request) -> RESTResponse:
"""
tdef = uri = None
if request.content_type == 'applications/x-bittorrent':
params = dict(request.query.items())
if 'anon_hops' in params:
params['anon_hops'] = int(params['anon_hops'])
if 'safe_seeding' in params:
params['safe_seeding'] = params['safe_seeding'] != 'false'
params: dict[str, str | int | list[int]] = {}
for k, v in request.query.items():
if k == "anon_hops":
params[k] = int(v)
elif k == "safe_seeding":
params[k] = v != "false"
else:
params[k] = v
body = await request.read()
metainfo = cast(dict[bytes, Any], lt.bdecode(body))
packed_selected_files = cast(Optional[list[int]], metainfo.pop(b"selected_files", None))
Expand Down
12 changes: 6 additions & 6 deletions src/tribler/core/restapi/file_endpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,13 @@ async def browse(self, request: web.Request) -> RESTResponse:
"paths": paths})

# Move up until we find a directory
path = Path(path).resolve()
while not path.is_dir():
path = path.parent
parent_path = Path(path).resolve()
while not parent_path.is_dir():
parent_path = parent_path.parent

# Get all files/subdirs
results = []
for file in path.iterdir():
for file in parent_path.iterdir():
if not file.is_dir() and not show_files:
continue
with contextlib.suppress(PermissionError):
Expand All @@ -68,11 +68,11 @@ async def browse(self, request: web.Request) -> RESTResponse:
# Get parent path (if available)
results.insert(0, {
"name": "..",
"path": str(path.parent.resolve()) if path != path.parent else "/",
"path": str(parent_path.parent.resolve()) if parent_path != parent_path.parent else "/",
"dir": True,
})

return RESTResponse({"current": str(path.resolve()),
return RESTResponse({"current": str(parent_path.resolve()),
"paths": results})

async def list(self, request: web.Request) -> RESTResponse:
Expand Down
4 changes: 2 additions & 2 deletions src/tribler/core/restapi/rest_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ async def start_http_site(self, runner: web.AppRunner) -> None:
str(e))
raise

current_port = api_port or self.site._server.sockets[0].getsockname()[1] # noqa: SLF001
current_port = api_port or cast(Server, self.site._server).sockets[0].getsockname()[1] # noqa: SLF001
self.config.set("api/http_port_running", current_port)
self.config.write()

Expand All @@ -280,7 +280,7 @@ async def start_https_site(self, runner: web.AppRunner) -> None:
await self.site_https.start()
self._logger.info("Started HTTPS REST API: %s", self.site_https.name)

current_port = port or self.site_https._server.sockets[0].getsockname()[1] # noqa: SLF001
current_port = port or cast(Server, self.site_https._server).sockets[0].getsockname()[1] # noqa: SLF001
self.config.set("api/https_port_running", current_port)
self.config.write()

Expand Down
23 changes: 15 additions & 8 deletions src/tribler/core/restapi/webui_endpoint.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import logging
import mimetypes

Expand All @@ -20,25 +22,30 @@ def __init__(self) -> None:
"""
super().__init__()
self._logger = logging.getLogger(self.__class__.__name__)
self.app.add_routes([web.get('/{path:.*}', self.return_files)])
self.app.add_routes([web.get("/{path:.*}", self.return_files)])

self.webui_root = tribler.get_webui_root()
self.has_dist = (self.webui_root / 'dist').exists()
self.has_dist = (self.webui_root / "dist").exists()
self.session = ClientSession() if not self.has_dist else None

async def return_files(self, request: web.Request) -> RESTResponse:
async def return_files(self, request: web.Request) -> RESTResponse | web.FileResponse:
"""
Return the file at the requested path.
"""
path = request.match_info['path'] or 'index.html'
path = request.match_info["path"] or "index.html"

if self.session:
async with self.session.get(f'http://localhost:5173/{path}') as response:
return web.Response(body=await response.read(), content_type=response.content_type)
async with self.session.get(f"http://localhost:5173/{path}") as client_response:
return RESTResponse(body=await client_response.read(), content_type=client_response.content_type)
else:
resource = self.webui_root / 'dist' / path
resource = self.webui_root / "dist" / path
response = web.FileResponse(resource)
response.content_type = 'application/javascript' if path.endswith('.tsx') else mimetypes.guess_type(path)[0]
if path.endswith(".tsx"):
response.content_type = "application/javascript"
elif (guessed_type := mimetypes.guess_type(path)[0]) is not None:
response.content_type = guessed_type
else:
response.content_type = "application/octet-stream"
return response

async def shutdown_task_manager(self) -> None:
Expand Down
7 changes: 5 additions & 2 deletions src/tribler/core/socks5/aiohttp_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,23 @@

import socket
from asyncio import BaseTransport, wait_for
from typing import Callable
from typing import TYPE_CHECKING, Callable

from aiohttp import TCPConnector
from aiohttp.abc import AbstractResolver

from tribler.core.socks5.client import Socks5Client, Socks5ClientUDPConnection

if TYPE_CHECKING:
from aiohttp.abc import ResolveResult


class FakeResolver(AbstractResolver):
"""
Pretend to resolve an address. Just echo it back.
"""

async def resolve(self, host: str, port: int = 0, family: int = socket.AF_INET) -> list[dict[str, str | int]]:
async def resolve(self, host: str, port: int = 0, family: int = socket.AF_INET) -> list[ResolveResult]:
"""
Resolve a host to itself.
"""
Expand Down

0 comments on commit 6082776

Please sign in to comment.