Add YAPF style + ignore, and format tracked Python files
This commit is contained in:
@@ -11,8 +11,9 @@ import requests
|
||||
|
||||
from ProviderCore.base import Provider
|
||||
|
||||
|
||||
_MATRIX_INIT_CHECK_CACHE: Dict[str, Tuple[bool, Optional[str]]] = {}
|
||||
_MATRIX_INIT_CHECK_CACHE: Dict[str,
|
||||
Tuple[bool,
|
||||
Optional[str]]] = {}
|
||||
|
||||
|
||||
def _sniff_mime_from_header(path: Path) -> Optional[str]:
|
||||
@@ -79,9 +80,10 @@ def _sniff_mime_from_header(path: Path) -> Optional[str]:
|
||||
return None
|
||||
|
||||
|
||||
def _classify_matrix_upload(
|
||||
path: Path, *, explicit_mime_type: Optional[str] = None
|
||||
) -> Tuple[str, str]:
|
||||
def _classify_matrix_upload(path: Path,
|
||||
*,
|
||||
explicit_mime_type: Optional[str] = None) -> Tuple[str,
|
||||
str]:
|
||||
"""Return (mime_type, msgtype) for Matrix uploads."""
|
||||
mime_type = str(explicit_mime_type or "").strip() or None
|
||||
|
||||
@@ -94,9 +96,11 @@ def _classify_matrix_upload(
|
||||
|
||||
# Refinements based on extension for ambiguous containers.
|
||||
ext = path.suffix.lower()
|
||||
if ext in {".m4a", ".aac"}:
|
||||
if ext in {".m4a",
|
||||
".aac"}:
|
||||
mime_type = mime_type or "audio/mp4"
|
||||
if ext in {".mkv", ".webm"}:
|
||||
if ext in {".mkv",
|
||||
".webm"}:
|
||||
mime_type = mime_type or "video/x-matroska"
|
||||
if ext in {".ogv"}:
|
||||
mime_type = mime_type or "video/ogg"
|
||||
@@ -142,7 +146,13 @@ def _classify_matrix_upload(
|
||||
".3gp",
|
||||
".ogv",
|
||||
}
|
||||
image_exts = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".tiff"}
|
||||
image_exts = {".jpg",
|
||||
".jpeg",
|
||||
".png",
|
||||
".gif",
|
||||
".webp",
|
||||
".bmp",
|
||||
".tiff"}
|
||||
if ext in audio_exts:
|
||||
msgtype = "m.audio"
|
||||
elif ext in video_exts:
|
||||
@@ -162,9 +172,10 @@ def _normalize_homeserver(value: str) -> str:
|
||||
return text.rstrip("/")
|
||||
|
||||
|
||||
def _matrix_health_check(
|
||||
*, homeserver: str, access_token: Optional[str]
|
||||
) -> Tuple[bool, Optional[str]]:
|
||||
def _matrix_health_check(*,
|
||||
homeserver: str,
|
||||
access_token: Optional[str]) -> Tuple[bool,
|
||||
Optional[str]]:
|
||||
"""Lightweight Matrix reachability/auth validation.
|
||||
|
||||
- Always checks `/versions` (no auth).
|
||||
@@ -180,9 +191,13 @@ def _matrix_health_check(
|
||||
return False, f"Homeserver returned {resp.status_code}"
|
||||
|
||||
if access_token:
|
||||
headers = {"Authorization": f"Bearer {access_token}"}
|
||||
headers = {
|
||||
"Authorization": f"Bearer {access_token}"
|
||||
}
|
||||
resp = requests.get(
|
||||
f"{base}/_matrix/client/v3/account/whoami", headers=headers, timeout=5
|
||||
f"{base}/_matrix/client/v3/account/whoami",
|
||||
headers=headers,
|
||||
timeout=5
|
||||
)
|
||||
if resp.status_code != 200:
|
||||
return False, f"Authentication failed: {resp.status_code}"
|
||||
@@ -201,9 +216,10 @@ class Matrix(Provider):
|
||||
self._init_reason: Optional[str] = None
|
||||
|
||||
matrix_conf = (
|
||||
self.config.get("provider", {}).get("matrix", {})
|
||||
if isinstance(self.config, dict)
|
||||
else {}
|
||||
self.config.get("provider",
|
||||
{}).get("matrix",
|
||||
{}) if isinstance(self.config,
|
||||
dict) else {}
|
||||
)
|
||||
homeserver = matrix_conf.get("homeserver")
|
||||
access_token = matrix_conf.get("access_token")
|
||||
@@ -237,14 +253,18 @@ class Matrix(Provider):
|
||||
return False
|
||||
if self._init_ok is False:
|
||||
return False
|
||||
matrix_conf = self.config.get("provider", {}).get("matrix", {})
|
||||
matrix_conf = self.config.get("provider",
|
||||
{}).get("matrix",
|
||||
{})
|
||||
return bool(
|
||||
matrix_conf.get("homeserver")
|
||||
and (matrix_conf.get("access_token") or matrix_conf.get("password"))
|
||||
)
|
||||
|
||||
def _get_homeserver_and_token(self) -> Tuple[str, str]:
|
||||
matrix_conf = self.config.get("provider", {}).get("matrix", {})
|
||||
matrix_conf = self.config.get("provider",
|
||||
{}).get("matrix",
|
||||
{})
|
||||
homeserver = matrix_conf.get("homeserver")
|
||||
access_token = matrix_conf.get("access_token")
|
||||
if not homeserver:
|
||||
@@ -262,8 +282,14 @@ class Matrix(Provider):
|
||||
Uses `GET /_matrix/client/v3/joined_rooms`.
|
||||
"""
|
||||
base, token = self._get_homeserver_and_token()
|
||||
headers = {"Authorization": f"Bearer {token}"}
|
||||
resp = requests.get(f"{base}/_matrix/client/v3/joined_rooms", headers=headers, timeout=10)
|
||||
headers = {
|
||||
"Authorization": f"Bearer {token}"
|
||||
}
|
||||
resp = requests.get(
|
||||
f"{base}/_matrix/client/v3/joined_rooms",
|
||||
headers=headers,
|
||||
timeout=10
|
||||
)
|
||||
if resp.status_code != 200:
|
||||
raise Exception(f"Matrix joined_rooms failed: {resp.text}")
|
||||
data = resp.json() or {}
|
||||
@@ -275,18 +301,24 @@ class Matrix(Provider):
|
||||
out.append(rid.strip())
|
||||
return out
|
||||
|
||||
def list_rooms(self, *, room_ids: Optional[List[str]] = None) -> List[Dict[str, Any]]:
|
||||
def list_rooms(self,
|
||||
*,
|
||||
room_ids: Optional[List[str]] = None) -> List[Dict[str,
|
||||
Any]]:
|
||||
"""Return joined rooms, optionally limited to a subset.
|
||||
|
||||
Performance note: room names require additional per-room HTTP requests.
|
||||
If `room_ids` is provided, only those rooms will have name lookups.
|
||||
"""
|
||||
base, token = self._get_homeserver_and_token()
|
||||
headers = {"Authorization": f"Bearer {token}"}
|
||||
headers = {
|
||||
"Authorization": f"Bearer {token}"
|
||||
}
|
||||
|
||||
joined = self.list_joined_room_ids()
|
||||
if room_ids:
|
||||
allowed = {str(v).strip().casefold() for v in room_ids if str(v).strip()}
|
||||
allowed = {str(v).strip().casefold()
|
||||
for v in room_ids if str(v).strip()}
|
||||
if allowed:
|
||||
# Accept either full IDs (!id:hs) or short IDs (!id).
|
||||
def _is_allowed(rid: str) -> bool:
|
||||
@@ -319,7 +351,10 @@ class Matrix(Provider):
|
||||
name = maybe
|
||||
except Exception:
|
||||
pass
|
||||
out.append({"room_id": room_id, "name": name})
|
||||
out.append({
|
||||
"room_id": room_id,
|
||||
"name": name
|
||||
})
|
||||
return out
|
||||
|
||||
def upload_to_room(self, file_path: str, room_id: str, **kwargs: Any) -> str:
|
||||
@@ -349,10 +384,17 @@ class Matrix(Provider):
|
||||
upload_url = f"{base}/_matrix/media/v3/upload"
|
||||
with open(path, "rb") as handle:
|
||||
wrapped = ProgressFileReader(
|
||||
handle, total_bytes=int(path.stat().st_size), label="upload"
|
||||
handle,
|
||||
total_bytes=int(path.stat().st_size),
|
||||
label="upload"
|
||||
)
|
||||
resp = requests.post(
|
||||
upload_url, headers=headers, data=wrapped, params={"filename": filename}
|
||||
upload_url,
|
||||
headers=headers,
|
||||
data=wrapped,
|
||||
params={
|
||||
"filename": filename
|
||||
}
|
||||
)
|
||||
if resp.status_code != 200:
|
||||
raise Exception(f"Matrix upload failed: {resp.text}")
|
||||
@@ -366,7 +408,7 @@ class Matrix(Provider):
|
||||
try:
|
||||
curi = str(content_uri or "").strip()
|
||||
if curi.startswith("mxc://"):
|
||||
rest = curi[len("mxc://") :]
|
||||
rest = curi[len("mxc://"):]
|
||||
if "/" in rest:
|
||||
server_name, media_id = rest.split("/", 1)
|
||||
server_name = str(server_name).strip()
|
||||
@@ -376,14 +418,24 @@ class Matrix(Provider):
|
||||
except Exception:
|
||||
download_url_for_store = ""
|
||||
|
||||
info = {"mimetype": mime_type, "size": path.stat().st_size}
|
||||
payload = {"msgtype": msgtype, "body": filename, "url": content_uri, "info": info}
|
||||
info = {
|
||||
"mimetype": mime_type,
|
||||
"size": path.stat().st_size
|
||||
}
|
||||
payload = {
|
||||
"msgtype": msgtype,
|
||||
"body": filename,
|
||||
"url": content_uri,
|
||||
"info": info
|
||||
}
|
||||
|
||||
# Correct Matrix client API send endpoint requires a transaction ID.
|
||||
txn_id = f"mm_{int(time.time())}_{uuid.uuid4().hex[:8]}"
|
||||
encoded_room = quote(str(room_id), safe="")
|
||||
send_url = f"{base}/_matrix/client/v3/rooms/{encoded_room}/send/m.room.message/{txn_id}"
|
||||
send_headers = {"Authorization": f"Bearer {token}"}
|
||||
send_headers = {
|
||||
"Authorization": f"Bearer {token}"
|
||||
}
|
||||
send_resp = requests.put(send_url, headers=send_headers, json=payload)
|
||||
if send_resp.status_code != 200:
|
||||
raise Exception(f"Matrix send message failed: {send_resp.text}")
|
||||
@@ -391,8 +443,7 @@ class Matrix(Provider):
|
||||
event_id = (send_resp.json() or {}).get("event_id")
|
||||
link = (
|
||||
f"https://matrix.to/#/{room_id}/{event_id}"
|
||||
if event_id
|
||||
else f"https://matrix.to/#/{room_id}"
|
||||
if event_id else f"https://matrix.to/#/{room_id}"
|
||||
)
|
||||
|
||||
# Optional: if a PipeObject is provided and it already has store+hash,
|
||||
@@ -403,7 +454,10 @@ class Matrix(Provider):
|
||||
from Store import Store
|
||||
|
||||
# Prefer the direct media download URL for storage backends.
|
||||
Store(self.config, suppress_debug=True).try_add_url_for_pipe_object(
|
||||
Store(
|
||||
self.config,
|
||||
suppress_debug=True
|
||||
).try_add_url_for_pipe_object(
|
||||
pipe_obj,
|
||||
download_url_for_store or link,
|
||||
)
|
||||
@@ -424,8 +478,13 @@ class Matrix(Provider):
|
||||
encoded_room = quote(str(room_id), safe="")
|
||||
txn_id = f"mm_{int(time.time())}_{uuid.uuid4().hex[:8]}"
|
||||
send_url = f"{base}/_matrix/client/v3/rooms/{encoded_room}/send/m.room.message/{txn_id}"
|
||||
send_headers = {"Authorization": f"Bearer {token}"}
|
||||
payload = {"msgtype": "m.text", "body": message}
|
||||
send_headers = {
|
||||
"Authorization": f"Bearer {token}"
|
||||
}
|
||||
payload = {
|
||||
"msgtype": "m.text",
|
||||
"body": message
|
||||
}
|
||||
send_resp = requests.put(send_url, headers=send_headers, json=payload)
|
||||
if send_resp.status_code != 200:
|
||||
raise Exception(f"Matrix send text failed: {send_resp.text}")
|
||||
@@ -433,19 +492,25 @@ class Matrix(Provider):
|
||||
event_id = (send_resp.json() or {}).get("event_id")
|
||||
return (
|
||||
f"https://matrix.to/#/{room_id}/{event_id}"
|
||||
if event_id
|
||||
else f"https://matrix.to/#/{room_id}"
|
||||
if event_id else f"https://matrix.to/#/{room_id}"
|
||||
)
|
||||
|
||||
def upload(self, file_path: str, **kwargs: Any) -> str:
|
||||
matrix_conf = self.config.get("provider", {}).get("matrix", {})
|
||||
matrix_conf = self.config.get("provider",
|
||||
{}).get("matrix",
|
||||
{})
|
||||
room_id = matrix_conf.get("room_id")
|
||||
if not room_id:
|
||||
raise Exception("Matrix room_id missing")
|
||||
return self.upload_to_room(file_path, str(room_id))
|
||||
|
||||
def selector(
|
||||
self, selected_items: List[Any], *, ctx: Any, stage_is_last: bool = True, **_kwargs: Any
|
||||
self,
|
||||
selected_items: List[Any],
|
||||
*,
|
||||
ctx: Any,
|
||||
stage_is_last: bool = True,
|
||||
**_kwargs: Any
|
||||
) -> bool:
|
||||
"""Handle Matrix room selection via `@N`.
|
||||
|
||||
@@ -501,7 +566,11 @@ class Matrix(Provider):
|
||||
print(f"Matrix upload file missing: {file_path}")
|
||||
continue
|
||||
|
||||
link = self.upload_to_room(str(media_path), str(room_id), pipe_obj=pipe_obj)
|
||||
link = self.upload_to_room(
|
||||
str(media_path),
|
||||
str(room_id),
|
||||
pipe_obj=pipe_obj
|
||||
)
|
||||
if link:
|
||||
print(link)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user