import json import re from dataclasses import dataclass, field from typing import Any, cast, override import httpx import websockets from cross.attachments import ( LabelsAttachment, LanguagesAttachment, 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 mastodon.info import MastodonService, StatusParser, validate_and_transform from util.util import listen_websocket ALLOWED_VISIBILITY: list[str] = ["public", "unlisted"] @dataclass(kw_only=True) class MastodonInputOptions: token: str instance: str allowed_visibility: list[str] = field( default_factory=lambda: ALLOWED_VISIBILITY.copy() ) filters: list[re.Pattern[str]] = field(default_factory=lambda: []) url_query_auth: bool = False @classmethod def from_dict(cls, data: dict[str, Any]) -> "MastodonInputOptions": validate_and_transform(data) 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 MastodonInputOptions(**data) class MastodonInputService(MastodonService, InputService): def __init__( self, db: DatabasePool, http: httpx.Client, options: MastodonInputOptions ) -> None: super().__init__(options.instance, db, http) self.options: MastodonInputOptions = options if options.url_query_auth: self.log.warning( "Using URL query auth! This is less secure than the default!" ) self.log.info("Verifying '%s' credentails...", self.url) response = self.verify_credentials() self.user_id: str = response["id"] self.log.info("Getting '%s' configuration...", self.url) response = self.fetch_instance_info() self.streaming_url: str = response["urls"]["streaming_api"] @override def _get_token(self) -> str: return self.options.token def _on_create_post(self, status: dict[str, Any]): if status["account"]["id"] != self.user_id: return if status["visibility"] not in self.options.allowed_visibility: self.log.info( "Skipping '%s': disallowed visibility (%s)", status["id"], status["visibility"], ) return if self._is_post_crossposted(self.url, self.user_id, status["id"]): self.log.info( "Skipping '%s': already crossposted", status["id"], ) return reblog: dict[str, Any] | None = status.get("reblog") if reblog: if reblog["account"]["id"] != self.user_id: return self._on_reblog(status, reblog) return if status.get("poll"): self.log.info("Skipping '%s': polls not supported", status["id"]) return quote: dict[str, Any] | None = status.get("quote") if quote: quote = quote["quoted_status"] if quote.get("quoted_status") else quote if not quote or quote["account"]["id"] != self.user_id: return rquote = self._get_post(self.url, self.user_id, quote["id"]) if not rquote: self.log.info( "Skipping '%s': quoted post '%s' not found in db", status["id"], quote["id"], ) return in_reply: str | None = status.get("in_reply_to_id") in_reply_to: str | None = status.get("in_reply_to_account_id") if in_reply_to and in_reply_to != self.user_id: return parent = None if in_reply: parent = self._get_post(self.url, self.user_id, in_reply) if not parent: self.log.info( "Skipping '%s': parent '%s' not found in db", status["id"], in_reply ) return parser = StatusParser(status) parser.feed(status["content"]) tokens = parser.get_result() post = Post( id=status["id"], author=self.user_id, service=self.url, parent_id=in_reply, tokens=tokens, text_type="text/html", ) if quote: post.attachments.put( QuoteAttachment(quoted_id=quote["id"], quoted_user=self.user_id) ) if status.get("url"): post.attachments.put(RemoteUrlAttachment(url=status["url"])) if status.get("sensitive"): post.attachments.put(SensitiveAttachment(sensitive=True)) if status.get("language"): post.attachments.put(LanguagesAttachment(langs=[status["language"]])) if status.get("spoiler_text"): post.attachments.put(LabelsAttachment(labels=[status["spoiler_text"]])) blobs: list[Blob] = [] for media in status.get("media_attachments", []): self.log.info("Downloading '%s'...", media["url"]) blob = download_blob( media["url"], media.get("description"), client=self.http ) if not blob.is_ok(): self.log.error( "Skipping '%s': failed to download attachment. %s", status["id"], blob.value(), ) 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": status["id"], "parent": parent["id"], "root": parent["root"] or parent["id"], } ) else: self._insert_post( { "user": self.user_id, "service": self.url, "identifier": status["id"], } ) self.log.info("Crossposting: '%s'", status["id"]) for out in self.outputs: self.submitter(lambda: out.accept_post(post)) self.submitter(lambda: cleanup_blobs(blobs)) def _on_reblog(self, status: dict[str, Any], reblog: dict[str, Any]): reposted = self._get_post(self.url, self.user_id, reblog["id"]) if not reposted: self.log.info( "Skipping repost '%s': reposted post '%s' not found in db", status["id"], reblog["id"], ) return self._insert_post( { "user": self.user_id, "service": self.url, "identifier": status["id"], "reposted": reposted["id"], } ) repost_ref = PostRef(id=status["id"], author=self.user_id, service=self.url) reposted_ref = PostRef(id=reblog["id"], author=self.user_id, service=self.url) self.log.info("Crossposting: '%s'", status["id"]) for out in self.outputs: self.submitter(lambda: out.accept_repost(repost_ref, reposted_ref)) def _on_delete_post(self, status_id: str): post = self._get_post(self.url, self.user_id, status_id) if not post: self.log.warning("Skipping delete '%s': post not found in db", status_id) return post_ref = PostRef(id=status_id, author=self.user_id, service=self.url) if post["reposted"]: self.log.info("Deleting repost: '%s'", status_id) for output in self.outputs: self.submitter(lambda: output.delete_repost(post_ref)) else: self.log.info("Deleting post: '%s'", status_id) for output in self.outputs: self.submitter(lambda: output.delete_post(post_ref)) self.submitter(lambda: self._delete_post_by_id(post["id"])) def _accept_msg(self, msg: websockets.Data) -> None: data: dict[str, Any] = cast(dict[str, Any], json.loads(msg)) event: str = cast(str, data["event"]) payload: str = cast(str, data["payload"]) if event == "update": self._on_create_post(json.loads(payload)) elif event == "delete": self._on_delete_post(payload) @override async def listen(self): url = f"{self.streaming_url}/api/v1/streaming?stream=user" headers = {} if not self.options.url_query_auth: headers["Authorization"] = f"Bearer {self.options.token}" else: url += f"&access_token={self.options.token}" async for msg in listen_websocket(url, self.log, headers=headers): self.submitter(lambda: self._accept_msg(msg))