import json import re import uuid from dataclasses import dataclass, field from typing import Any, cast, override import httpx import websockets from cross.attachments import ( LabelsAttachment, MediaAttachment, QuoteAttachment, RemoteUrlAttachment, SensitiveAttachment, ) from cross.media import Blob, cleanup_blobs, download_blob from cross.post import Post, PostRef from cross.service import InputService from database.connection import DatabasePool from misskey.info import MisskeyService from util.markdown import MarkdownParser from util.util import listen_websocket, normalize_service_url ALLOWED_VISIBILITY = ["public", "home"] @dataclass class MisskeyInputOptions: token: str instance: str allowed_visibility: list[str] = field( default_factory=lambda: ALLOWED_VISIBILITY.copy() ) filters: list[re.Pattern[str]] = field(default_factory=lambda: []) @classmethod def from_dict(cls, data: dict[str, Any]) -> "MisskeyInputOptions": data["instance"] = normalize_service_url(data["instance"]) if "allowed_visibility" in data: for vis in data.get("allowed_visibility", []): if vis not in ALLOWED_VISIBILITY: raise ValueError(f"Invalid visibility option {vis}!") if "filters" in data: data["filters"] = [re.compile(r) for r in data["filters"]] return MisskeyInputOptions(**data) class MisskeyInputService(MisskeyService, InputService): def __init__( self, db: DatabasePool, http: httpx.Client, options: MisskeyInputOptions ) -> None: super().__init__(options.instance, db, http) self.options: MisskeyInputOptions = options self.log.info("Verifying '%s' credentails...", self.url) response = self.verify_credentials() self.user_id: str = response["id"] @override def _get_token(self) -> str: return self.options.token def _on_note(self, note: dict[str, Any]): if note["userId"] != self.user_id: return if note["visibility"] not in self.options.allowed_visibility: self.log.info( "Skipping '%s': disallowed visibility (%s)", note["id"], note["visibility"], ) return if self._is_post_crossposted(self.url, self.user_id, note["id"]): self.log.info( "Skipping '%s': already crossposted", note["id"], ) return if note.get("poll"): self.log.info("Skipping '%s': polls not supported", note["id"]) return renote: dict[str, Any] | None = note.get("renote") if renote: if note.get("text") is None: self._on_renote(note, renote) return if renote["userId"] != self.user_id: return rrenote = self._get_post(self.url, self.user_id, renote["id"]) if not rrenote: self.log.info( "Skipping '%s': quoted post '%s' not found in db", note["id"], renote["id"], ) return reply: dict[str, Any] | None = note.get("reply") if reply and reply.get("userId") != self.user_id: self.log.info("Skipping '%s': Reply to other user..", note["id"]) return parent = None if reply: parent = self._get_post(self.url, self.user_id, reply["id"]) if not parent: self.log.info( "Skipping '%s': parent '%s' not found in db", note["id"], reply["id"], ) return mention_handles: dict = note.get("mentionHandles") or {} tags: list[str] = note.get("tags") or [] handles: list[tuple[str, str]] = [] for _key, value in mention_handles.items(): handles.append((value, value)) parser = MarkdownParser() # TODO MFM parser tokens = parser.parse(note.get("text", ""), tags, handles) post = Post( id=note["id"], author=self.user_id, service=self.url, parent_id=reply["id"] if reply else None, tokens=tokens, text_type="text/x.misskeymarkdown", ) post.attachments.put(RemoteUrlAttachment(url=self.url + "/notes/" + note["id"])) if renote: post.attachments.put( QuoteAttachment(quoted_id=renote["id"], quoted_user=self.user_id) ) if any(a.get("isSensitive", False) for a in note.get("files", [])): post.attachments.put(SensitiveAttachment(sensitive=True)) if note.get("cw"): post.attachments.put(LabelsAttachment(labels=[note["cw"]])) blobs: list[Blob] = [] for media in note.get("files", []): self.log.info("Downloading '%s'...", media["url"]) blob = download_blob( media["url"], media.get("comment", ""), client=self.http ) if not blob.is_ok(): self.log.error( "Skipping '%s': failed to download media. %s", note["id"], blob.error(), ) return blobs.append(blob.value()) if blobs: post.attachments.put(MediaAttachment(blobs=blobs)) if parent: self._insert_post( { "user": self.user_id, "service": self.url, "identifier": note["id"], "parent": parent["id"], "root": parent["root"] or parent["id"], } ) else: self._insert_post( { "user": self.user_id, "service": self.url, "identifier": note["id"], } ) self.log.info("Crossposting: '%s'", note["id"]) for out in self.outputs: self.submitter(lambda: out.accept_post(post)) self.submitter(lambda: cleanup_blobs(blobs)) def _on_renote(self, note: dict[str, Any], renote: dict[str, Any]): reposted = self._get_post(self.url, self.user_id, renote["id"]) if not reposted: self.log.info( "Skipping repost '%s': reposted post '%s' not found in db", note["id"], renote["id"], ) return self._insert_post( { "user": self.user_id, "service": self.url, "identifier": note["id"], "reposted": reposted["id"], } ) repost_ref = PostRef(id=note["id"], author=self.user_id, service=self.url) reposted_ref = PostRef(id=renote["id"], author=self.user_id, service=self.url) self.log.info("Crossposting: '%s'", note["id"]) for out in self.outputs: self.submitter(lambda: out.accept_repost(repost_ref, reposted_ref)) def _accept_msg(self, msg: websockets.Data) -> None: data: dict[str, Any] = cast(dict[str, Any], json.loads(msg)) if data["type"] == "channel": type: str = cast(str, data["body"]["type"]) if type == "note" or type == "reply": note_body = data["body"]["body"] self._on_note(note_body) async def _subscribe_to_home(self, ws: websockets.ClientConnection) -> None: await ws.send( json.dumps( { "type": "connect", "body": {"channel": "homeTimeline", "id": str(uuid.uuid4())}, } ) ) self.log.info("Subscribed to 'homeTimeline' channel...") @override async def listen(self): streaming: str = f"{'wss' if self.url.startswith('https') else 'ws'}://{self.url.split('://', 1)[1]}" url: str = f"{streaming}/streaming?i={self.options.token}" async for msg in listen_websocket( url, self.log, on_connect=self._subscribe_to_home ): self.submitter(lambda: self._accept_msg(msg))