2019-04-12 03:22:43 +10:00
|
|
|
# Copyright 2019 miruka
|
|
|
|
# This file is part of harmonyqml, licensed under GPLv3.
|
|
|
|
|
|
|
|
import functools
|
2019-04-13 22:59:10 +10:00
|
|
|
import logging
|
|
|
|
import sys
|
|
|
|
import traceback
|
2019-04-12 03:22:43 +10:00
|
|
|
from concurrent.futures import Future, ThreadPoolExecutor
|
2019-04-13 22:59:10 +10:00
|
|
|
from threading import Event, currentThread
|
2019-04-15 02:56:30 +10:00
|
|
|
from typing import Callable, DefaultDict
|
2019-04-12 03:22:43 +10:00
|
|
|
|
2019-04-13 03:18:46 +10:00
|
|
|
from PyQt5.QtCore import QObject, pyqtProperty, pyqtSignal, pyqtSlot
|
2019-04-12 03:22:43 +10:00
|
|
|
|
|
|
|
import nio
|
|
|
|
import nio.responses as nr
|
|
|
|
|
2019-04-18 11:08:32 +10:00
|
|
|
from .network_manager import NetworkManager
|
|
|
|
|
2019-04-12 03:22:43 +10:00
|
|
|
# One pool per hostname/remote server;
|
|
|
|
# multiple Client for different accounts on the same server can exist.
|
|
|
|
_POOLS: DefaultDict[str, ThreadPoolExecutor] = \
|
|
|
|
DefaultDict(lambda: ThreadPoolExecutor(max_workers=6))
|
|
|
|
|
|
|
|
|
|
|
|
def futurize(func: Callable) -> Callable:
|
|
|
|
@functools.wraps(func)
|
|
|
|
def wrapper(*args, **kwargs) -> Future:
|
2019-04-13 22:59:10 +10:00
|
|
|
def run_and_catch_errs():
|
|
|
|
# Without this, exceptions are silently ignored
|
|
|
|
try:
|
|
|
|
func(*args, **kwargs)
|
|
|
|
except Exception:
|
|
|
|
traceback.print_exc()
|
|
|
|
logging.error("Exiting %s due to exception.", currentThread())
|
|
|
|
sys.exit(1)
|
|
|
|
|
|
|
|
return args[0].pool.submit(run_and_catch_errs) # args[0] = self
|
2019-04-12 03:22:43 +10:00
|
|
|
return wrapper
|
|
|
|
|
|
|
|
|
|
|
|
class Client(QObject):
|
2019-04-18 11:08:32 +10:00
|
|
|
roomInvited = pyqtSignal(str)
|
|
|
|
roomJoined = pyqtSignal(str)
|
|
|
|
roomLeft = pyqtSignal(str)
|
|
|
|
roomSyncPrevBatchTokenReceived = pyqtSignal(str, str)
|
|
|
|
roomPastPrevBatchTokenReceived = pyqtSignal(str, str)
|
|
|
|
roomEventReceived = pyqtSignal(str, str, dict)
|
|
|
|
roomTypingUsersUpdated = pyqtSignal(str, list)
|
2019-04-19 03:46:39 +10:00
|
|
|
messageAboutToBeSent = pyqtSignal(str, dict)
|
2019-04-13 03:18:46 +10:00
|
|
|
|
|
|
|
|
2019-04-18 13:28:25 +10:00
|
|
|
def __init__(self,
|
|
|
|
manager,
|
|
|
|
hostname: str,
|
|
|
|
username: str,
|
|
|
|
device_id: str = "") -> None:
|
|
|
|
super().__init__(manager)
|
|
|
|
self.manager = manager
|
2019-04-12 03:22:43 +10:00
|
|
|
|
|
|
|
host, *port = hostname.split(":")
|
|
|
|
self.host: str = host
|
|
|
|
self.port: int = int(port[0]) if port else 443
|
|
|
|
|
2019-04-18 11:08:32 +10:00
|
|
|
self.pool: ThreadPoolExecutor = _POOLS[self.host]
|
|
|
|
|
2019-04-12 03:22:43 +10:00
|
|
|
self.nio: nio.client.HttpClient = \
|
|
|
|
nio.client.HttpClient(self.host, username, device_id)
|
|
|
|
|
2019-04-18 11:08:32 +10:00
|
|
|
# Since nio clients can't handle more than one talk operation
|
|
|
|
# at a time, this one is used exclusively to poll the sync API
|
|
|
|
self.nio_sync: nio.client.HttpClient = \
|
|
|
|
nio.client.HttpClient(self.host, username, device_id)
|
2019-04-12 03:22:43 +10:00
|
|
|
|
2019-04-18 11:08:32 +10:00
|
|
|
self.net = NetworkManager(self.host, self.port, self.nio)
|
|
|
|
self.net_sync = NetworkManager(self.host, self.port, self.nio_sync)
|
2019-04-12 03:22:43 +10:00
|
|
|
|
2019-04-18 12:34:22 +10:00
|
|
|
self._loading: bool = False
|
|
|
|
|
2019-04-12 03:22:43 +10:00
|
|
|
self._stop_sync: Event = Event()
|
|
|
|
|
|
|
|
|
|
|
|
def __repr__(self) -> str:
|
|
|
|
return "%s(host=%r, port=%r, user_id=%r)" % \
|
2019-04-13 03:18:46 +10:00
|
|
|
(type(self).__name__, self.host, self.port, self.userID)
|
|
|
|
|
|
|
|
|
|
|
|
@pyqtProperty(str, constant=True)
|
|
|
|
def userID(self) -> str:
|
|
|
|
return self.nio.user_id
|
2019-04-12 03:22:43 +10:00
|
|
|
|
|
|
|
|
|
|
|
@pyqtSlot(str)
|
|
|
|
@pyqtSlot(str, str)
|
|
|
|
@futurize
|
|
|
|
def login(self, password: str, device_name: str = "") -> None:
|
|
|
|
self.net.write(self.nio.connect())
|
2019-04-18 11:08:32 +10:00
|
|
|
response = self.net.talk(self.nio.login, password, device_name)
|
|
|
|
|
|
|
|
self.net_sync.write(self.nio_sync.connect())
|
|
|
|
self.nio_sync.receive_response(response)
|
2019-04-12 03:22:43 +10:00
|
|
|
self.startSyncing()
|
|
|
|
|
|
|
|
|
|
|
|
@pyqtSlot(str, str, str)
|
|
|
|
@futurize
|
|
|
|
def resumeSession(self, user_id: str, token: str, device_id: str
|
|
|
|
) -> None:
|
|
|
|
self.net.write(self.nio.connect())
|
|
|
|
response = nr.LoginResponse(user_id, device_id, token)
|
|
|
|
self.nio.receive_response(response)
|
2019-04-18 11:08:32 +10:00
|
|
|
|
|
|
|
self.net_sync.write(self.nio_sync.connect())
|
|
|
|
self.nio_sync.receive_response(response)
|
2019-04-12 03:22:43 +10:00
|
|
|
self.startSyncing()
|
|
|
|
|
|
|
|
|
|
|
|
@pyqtSlot()
|
|
|
|
@futurize
|
|
|
|
def logout(self) -> None:
|
|
|
|
self._stop_sync.set()
|
|
|
|
self.net.write(self.nio.disconnect())
|
2019-04-18 11:08:32 +10:00
|
|
|
self.net_sync.write(self.nio_sync.disconnect())
|
2019-04-12 03:22:43 +10:00
|
|
|
|
|
|
|
|
2019-04-12 18:33:09 +10:00
|
|
|
@pyqtSlot()
|
2019-04-12 03:22:43 +10:00
|
|
|
@futurize
|
|
|
|
def startSyncing(self) -> None:
|
|
|
|
while True:
|
2019-04-18 11:08:32 +10:00
|
|
|
self._on_sync(self.net_sync.talk(
|
|
|
|
self.nio_sync.sync, timeout=10_000
|
|
|
|
))
|
2019-04-12 03:22:43 +10:00
|
|
|
|
|
|
|
if self._stop_sync.is_set():
|
|
|
|
self._stop_sync.clear()
|
|
|
|
break
|
2019-04-12 18:33:09 +10:00
|
|
|
|
|
|
|
|
2019-04-13 03:18:46 +10:00
|
|
|
def _on_sync(self, response: nr.SyncResponse) -> None:
|
2019-04-18 11:08:32 +10:00
|
|
|
self.nio.receive_response(response)
|
|
|
|
|
2019-04-13 03:18:46 +10:00
|
|
|
for room_id in response.rooms.invite:
|
|
|
|
self.roomInvited.emit(room_id)
|
|
|
|
|
2019-04-15 02:56:30 +10:00
|
|
|
for room_id, room_info in response.rooms.join.items():
|
2019-04-13 03:18:46 +10:00
|
|
|
self.roomJoined.emit(room_id)
|
|
|
|
|
2019-04-18 11:08:32 +10:00
|
|
|
self.roomSyncPrevBatchTokenReceived.emit(
|
|
|
|
room_id, room_info.timeline.prev_batch
|
|
|
|
)
|
|
|
|
|
2019-04-15 02:56:30 +10:00
|
|
|
for ev in room_info.timeline.events:
|
|
|
|
self.roomEventReceived.emit(
|
|
|
|
room_id, type(ev).__name__, ev.__dict__
|
|
|
|
)
|
|
|
|
|
2019-04-15 06:12:07 +10:00
|
|
|
for ev in room_info.ephemeral:
|
|
|
|
if isinstance(ev, nr.TypingNoticeEvent):
|
|
|
|
self.roomTypingUsersUpdated.emit(room_id, ev.users)
|
|
|
|
else:
|
|
|
|
print("ephemeral event: ", ev)
|
|
|
|
|
2019-04-13 22:59:10 +10:00
|
|
|
for room_id in response.rooms.leave:
|
2019-04-13 03:18:46 +10:00
|
|
|
self.roomLeft.emit(room_id)
|
2019-04-18 11:08:32 +10:00
|
|
|
|
|
|
|
|
|
|
|
@futurize
|
2019-04-18 12:34:22 +10:00
|
|
|
def loadPastEvents(self, room_id: str, start_token: str, limit: int = 100
|
|
|
|
) -> None:
|
2019-04-18 11:08:32 +10:00
|
|
|
# From QML, use Backend.loastPastEvents instead
|
2019-04-18 12:34:22 +10:00
|
|
|
|
|
|
|
if self._loading:
|
|
|
|
return
|
|
|
|
self._loading = True
|
|
|
|
|
2019-04-18 11:08:32 +10:00
|
|
|
self._on_past_events(
|
|
|
|
room_id,
|
|
|
|
self.net.talk(
|
2019-04-18 12:34:22 +10:00
|
|
|
self.nio.room_messages, room_id, start=start_token, limit=limit
|
2019-04-18 11:08:32 +10:00
|
|
|
)
|
|
|
|
)
|
2019-04-18 12:34:22 +10:00
|
|
|
self._loading = False
|
2019-04-18 11:08:32 +10:00
|
|
|
|
|
|
|
|
|
|
|
def _on_past_events(self, room_id: str, response: nr.RoomMessagesResponse
|
|
|
|
) -> None:
|
|
|
|
self.roomPastPrevBatchTokenReceived.emit(room_id, response.end)
|
|
|
|
|
|
|
|
for ev in response.chunk:
|
|
|
|
self.roomEventReceived.emit(
|
|
|
|
room_id, type(ev).__name__, ev.__dict__
|
|
|
|
)
|
2019-04-18 13:01:26 +10:00
|
|
|
|
|
|
|
|
|
|
|
@pyqtSlot(str, str)
|
|
|
|
@futurize
|
2019-04-18 13:28:25 +10:00
|
|
|
def sendMarkdown(self, room_id: str, text: str) -> None:
|
|
|
|
html = self.manager.backend.htmlFilter.fromMarkdown(text)
|
2019-04-18 13:01:26 +10:00
|
|
|
content = {
|
|
|
|
"body": text,
|
2019-04-18 13:28:25 +10:00
|
|
|
"formatted_body": html,
|
2019-04-18 13:01:26 +10:00
|
|
|
"format": "org.matrix.custom.html",
|
|
|
|
"msgtype": "m.text",
|
|
|
|
}
|
2019-04-19 03:46:39 +10:00
|
|
|
self.messageAboutToBeSent.emit(room_id, content)
|
|
|
|
|
|
|
|
self.net.talk(
|
|
|
|
self.nio.room_send,
|
|
|
|
room_id = room_id,
|
|
|
|
message_type = "m.room.message",
|
|
|
|
content = content,
|
|
|
|
)
|