-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
207 lines (163 loc) · 7.63 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
"""
Copyright (c) 2024 AstreaTSS
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import asyncio
import contextlib
import logging
import os
import sys
from typing import TYPE_CHECKING
import aiohttp
import atproto
import msgspec
from dotenv import load_dotenv
from content_parser import ContentParser
from models import account_decoder, event_decoder, mastodon_status_decoder
if TYPE_CHECKING:
from atproto_client.models.blob_ref import BlobRef
load_dotenv()
decoder = msgspec.json.Decoder()
log = logging.getLogger("mastodon-bluesky")
log.setLevel(logging.INFO)
log.addHandler(logging.StreamHandler(sys.stdout))
async def main() -> None:
async with aiohttp.ClientSession() as session:
log.info("Verifying Mastodon credentials...")
async with session.get(
f"https://{os.environ['MASTODON_INSTANCE']}/api/v1/accounts/verify_credentials",
headers={"Authorization": f"Bearer {os.environ['MASTODON_ACCESS_TOKEN']}"},
) as response:
response.raise_for_status()
try:
account = account_decoder.decode(await response.read())
except msgspec.DecodeError as e:
log.error("Error decoding account data", exc_info=e)
return
log.info(
"Verified Mastodon as %s! Setting up Bluesky connection...",
account.username,
)
bluesky = atproto.AsyncClient()
profile = await bluesky.login(
os.environ["BLUESKY_USERNAME"], os.environ["BLUESKY_PASSWORD"]
)
log.info(
"Logged into Bluesky as %s! Setting up Mastodon post streaming...",
profile.handle,
)
async with aiohttp.ClientSession() as session:
async with session.ws_connect(
f"wss://{os.environ['MASTODON_INSTANCE']}/api/v1/streaming",
headers={"Authorization": f"Bearer {os.environ['MASTODON_ACCESS_TOKEN']}"},
) as ws:
await ws.send_json(
{
"type": "subscribe",
"stream": "list",
"list": os.environ["MASTODON_LIST_ID"],
"access_token": os.environ["MASTODON_ACCESS_TOKEN"],
}
)
log.info("Connected to Mastodon! Listening for updates...")
async for msg in ws:
try:
data = event_decoder.decode(msg.data)
if data.event != "update":
continue
payload = mastodon_status_decoder.decode(data.payload)
log.info("Received post: %s", payload.uri)
if payload.account.id != account.id:
log.info("Ignoring post from another account: %s", payload.uri)
continue
if payload.in_reply_to_id is not None:
log.info("Ignoring reply post: %s", payload.pretty_url)
continue
if payload.reblog is not None:
log.info("Ignoring reblog: %s", payload.pretty_url)
continue
data_parser = ContentParser()
data_parser.feed(payload.content)
data_parser.close()
parsed_content = "".join(data_parser.data).strip()
if len(parsed_content) > 300:
log.info(
"Ignoring post with too much text: %s", payload.pretty_url
)
continue
if parsed_content.startswith("[Mastodon]"):
log.info(
"Ignoring post meant for Mastodon only: %s",
payload.pretty_url,
)
continue
if payload.visibility != "public":
log.info("Ignoring non-public post: %s", payload.pretty_url)
continue
image_blobs: list[tuple["BlobRef", str | None]] = []
for attachment in payload.media_attachments:
if attachment.type == "image":
async with session.get(attachment.url) as resp:
if resp.status != 200:
continue
img_data = await resp.read()
resp = await bluesky.upload_blob(img_data)
image_blobs.append((resp.blob, attachment.description))
images = [
atproto.models.AppBskyEmbedImages.Image(
alt=image_alt or "", image=blob
)
for blob, image_alt in image_blobs
]
embed = None
if images:
embed = atproto.models.AppBskyEmbedImages.Main(images=images)
elif payload.card is not None:
if payload.card.image is not None:
async with session.get(payload.card.image) as resp:
if resp.status != 200:
continue
img_data = await resp.read()
resp = await bluesky.upload_blob(img_data)
blob = resp.blob
else:
blob = None
embed = atproto.models.AppBskyEmbedExternal.Main(
external=atproto.models.AppBskyEmbedExternal.External(
title=payload.card.title,
description=payload.card.description or "",
uri=payload.card.url,
thumb=blob,
)
)
bluesky_post = await bluesky.send_post(
text=parsed_content,
embed=embed,
facets=data_parser.build_facets(),
)
weird_id_thing = bluesky_post.uri.split("/")[-1]
log.info(
"Posted %s to Bluesky: %s",
payload.pretty_url,
f"https://bsky.app/profile/{profile.handle}/post/{weird_id_thing}",
)
except Exception as e:
log.error("Error processing message", exc_info=e)
async def wrapped_main() -> None:
with contextlib.suppress(asyncio.CancelledError, KeyboardInterrupt):
await main()
asyncio.run(wrapped_main())