Something went wrong. Try again.
a fork of EvalEx by ezylang with a handful of breaking changes
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269import jsonimport refrom dataclasses import dataclass, fieldfrom typing import Any, cast, override
import httpximport websockets
from cross.attachments import ( LabelsAttachment, LanguagesAttachment, MediaAttachment, QuoteAttachment, RemoteUrlAttachment, SensitiveAttachment,)from cross.media import Blob, cleanup_blobs, download_blobfrom cross.post import Post, PostReffrom cross.service import InputServicefrom database.connection import DatabasePoolfrom mastodon.info import MastodonService, StatusParser, validate_and_transformfrom 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))