Auto-detect homeserver scheme://

This commit is contained in:
miruka 2020-08-19 02:14:46 -04:00
parent 2fa8b2c5f9
commit 16970d5e56
3 changed files with 43 additions and 13 deletions

View File

@ -2,7 +2,6 @@
import asyncio
import logging as log
import math
import os
import re
import sys
@ -11,6 +10,7 @@ import traceback
from datetime import datetime
from pathlib import Path
from typing import Any, DefaultDict, Dict, List, Optional, Tuple
from urllib.parse import urlparse
import aiohttp
from appdirs import AppDirs
@ -148,16 +148,44 @@ class Backend:
Possible login methods include `m.login.password` or `m.login.sso`.
"""
client = MatrixClient(self, homeserver=homeserver)
if not re.match(r"https?://", homeserver):
homeserver = f"http://{homeserver}"
client = MatrixClient(self, homeserver=homeserver)
http_re = re.compile("^http://")
is_local = urlparse(client.homeserver).netloc.split(":")[0] in (
"localhost", "127.0.0.1", "::1",
)
try:
client.homeserver = (await client.discovery_info()).homeserver_url
except (MatrixNotFound, MatrixForbidden):
except MatrixError:
# This is either already the real URL, or an invalid URL.
pass
try:
return (client.homeserver, (await client.login_info()).flows)
try:
login_response = await client.login_info()
except (asyncio.TimeoutError, MatrixError):
# Maybe we still have a http URL and server only supports https
client.homeserver = http_re.sub("https://", client.homeserver)
login_response = await client.login_info()
# If we still have a http URL and server redirected to https
if login_response.transport_response.real_url.scheme == "https":
client.homeserver = http_re.sub("https://", client.homeserver)
# If we still have a http URL and server accept both http and https
if http_re.match(client.homeserver) and not is_local:
original = client.homeserver
client.homeserver = http_re.sub("https://", client.homeserver)
try:
await asyncio.wait_for(client.login_info(), timeout=6)
except (asyncio.TimeoutError, MatrixError):
client.homeserver = original
return (client.homeserver, login_response.flows)
finally:
await client.close()

View File

@ -160,11 +160,6 @@ class MatrixClient(nio.AsyncClient):
device_id: Optional[str] = None,
) -> None:
if not urlparse(homeserver).scheme:
raise ValueError(
f"homeserver is missing scheme (e.g. https://): {homeserver}",
)
store = Path(backend.appdirs.user_data_dir) / "encryption"
store.mkdir(parents=True, exist_ok=True)
@ -253,6 +248,9 @@ class MatrixClient(nio.AsyncClient):
response = await super()._send(*args, **kwargs)
if isinstance(response, nio.ErrorResponse):
for a in args:
if isinstance(a, str) and "cyberia" in a:
import remote_pdb; remote_pdb.RemotePdb("127.0.0.1", 4444).set_trace()
raise MatrixError.from_nio(response)
return response

View File

@ -64,6 +64,8 @@ HBox {
accepted()
}, (type, args, error, traceback, uuid) => {
console.error(traceback)
connectTimeout.stop()
connectFuture = null
@ -73,7 +75,7 @@ HBox {
text = qsTr("Invalid homeserver address") :
type.startsWith("Matrix") ?
text = qsTr("Error contacting server: %1").arg(type) :
text = qsTr("Connection failed: %1(%2)").arg(type).arg(args) :
py.showError(type, traceback, uuid)
@ -130,11 +132,11 @@ HBox {
readonly property string cleanText:
text.toLowerCase().trim().replace(/\/+$/, "")
error: text && ! /https?:\/\/.+/.test(cleanText)
inputMethodHints: Qt.ImhUrlCharactersOnly
defaultText: window.getState(
box, "acceptedUserUrl", "",
)
placeholderText: "https://example.org"
placeholderText: "example.org"
Layout.fillWidth: true
Layout.fillHeight: true
@ -202,7 +204,9 @@ HBox {
width: serverList.width
loadingIconStep: box.loadingIconStep
onClicked: {
serverField.item.field.text = model.id
serverField.item.field.text =
model.id.replace(/^https:\/\//, "")
serverField.item.apply.clicked()
}
}