|
7 | 7 | from __future__ import annotations
|
8 | 8 | from collections.abc import Callable
|
9 | 9 | 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 |
11 | 11 | import functools, html.parser, itertools, json, math, re, threading, time, uuid
|
12 | 12 | import miniirc, requests, traceback # type: ignore
|
13 | 13 |
|
14 | 14 |
|
15 |
| -ver = (0, 0, 4) |
| 15 | +ver = (0, 0, 5) |
16 | 16 | __version__ = '.'.join(map(str, ver))
|
17 | 17 |
|
18 | 18 |
|
@@ -398,19 +398,34 @@ def _update_baseurl(self) -> None:
|
398 | 398 | # Non-SSL localhost connections are probably to
|
399 | 399 | # https://github.com/matrix-org/pantalaimon which doesn't support
|
400 | 400 | # the "v3" URLs yet.
|
401 |
| - protocol = 'http' |
| 401 | + matrix_url = f'http://{hostname}' |
402 | 402 | api_version = 'r0'
|
403 | 403 | else:
|
404 |
| - protocol = 'https' |
405 | 404 | api_version = 'v3'
|
406 | 405 |
|
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') |
410 | 426 |
|
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}' |
414 | 429 |
|
415 | 430 | def __get(self, endpoint: str, timeout: int = 5, /,
|
416 | 431 | **params: Optional[str | int]) -> Any:
|
|
0 commit comments