Skip to content

Commit 0b4d14b

Browse files
committed
Check .well-known/matrix/client
1 parent 1d34f87 commit 0b4d14b

File tree

2 files changed

+26
-11
lines changed

2 files changed

+26
-11
lines changed

miniirc_matrix.py

+25-10
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,12 @@
77
from __future__ import annotations
88
from collections.abc import Callable
99
from typing import Any, Optional, TypeVar, overload
10-
from urllib.parse import quote as _url_quote
10+
from urllib.parse import quote as _url_quote, urlparse as _urlparse
1111
import functools, html.parser, itertools, json, math, re, threading, time, uuid
1212
import miniirc, requests, traceback # type: ignore
1313

1414

15-
ver = (0, 0, 4)
15+
ver = (0, 0, 5)
1616
__version__ = '.'.join(map(str, ver))
1717

1818

@@ -398,19 +398,34 @@ def _update_baseurl(self) -> None:
398398
# Non-SSL localhost connections are probably to
399399
# https://github.com/matrix-org/pantalaimon which doesn't support
400400
# the "v3" URLs yet.
401-
protocol = 'http'
401+
matrix_url = f'http://{hostname}'
402402
api_version = 'r0'
403403
else:
404-
protocol = 'https'
405404
api_version = 'v3'
406405

407-
# Use a shorter hostname if possible
408-
if self.port == 443:
409-
hostname = self.ip
406+
# Check for a .well-known/matrix/client
407+
res = requests.get(f'https://{hostname}/.well-known/matrix/client',
408+
timeout=10)
409+
if res.status_code == 200:
410+
e = _Event(res.json())
411+
baseurl = e.m_homeserver.base_url[str].rstrip('/')
412+
413+
# Ensure the baseurl is valid
414+
parsed_url = _urlparse(baseurl)
415+
if (parsed_url.scheme != 'https' or parsed_url.query or
416+
parsed_url.fragment):
417+
raise ValueError(f'Invalid URL {baseurl!r}')
418+
elif res.status_code == 404:
419+
# Use a shorter hostname if possible
420+
if self.port == 443:
421+
hostname = self.ip
422+
baseurl = f'https://{hostname}'
423+
else:
424+
res.raise_for_status()
425+
raise ValueError(f'Status code {res.status_code} returned')
410426

411-
matrix_url = f'{protocol}://{hostname}/_matrix'
412-
self._baseurl = f'{matrix_url}/client/{api_version}'
413-
self._media_baseurl = f'{matrix_url}/media/{api_version}'
427+
self._baseurl = f'{baseurl}/_matrix/client/{api_version}'
428+
self._media_baseurl = f'{baseurl}/_matrix/media/{api_version}'
414429

415430
def __get(self, endpoint: str, timeout: int = 5, /,
416431
**params: Optional[str | int]) -> Any:

setup.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
setup(
77
name='miniirc_matrix',
8-
version='0.0.4',
8+
version='0.0.5',
99
py_modules=['miniirc_matrix'],
1010
author='luk3yx',
1111
description='A Matrix wrapper for miniirc.',

0 commit comments

Comments
 (0)