Something went wrong. Try again.
a fork of EvalEx by ezylang with a handful of breaking changes
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251import jsonimport reimport uuidfrom dataclasses import dataclass, fieldfrom typing import Any, cast, override
import httpximport websockets
from cross.attachments import ( LabelsAttachment, 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 misskey.info import MisskeyServicefrom util.markdown import MarkdownParserfrom util.util import listen_websocket, normalize_service_url
ALLOWED_VISIBILITY = ["public", "home"]
@dataclassclass 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))