-
Notifications
You must be signed in to change notification settings - Fork 1
/
lmmy.py
159 lines (129 loc) · 4.34 KB
/
lmmy.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
import asyncio
import sqlite3
import tornado.web, tornado.locale, tornado.httpclient
from tornado.httputil import url_concat
class DataContext:
__slots__ = 'db',
def __init__(self, db):
self.db = db
def instances(self):
return { instance[0] for instance in self.db.execute('''
SELECT "domain"
FROM "instances"
ORDER BY "domain"''').fetchall() }
def has_instance(self, domain):
return self.db.execute('''
SELECT 1
FROM "instances"
WHERE "domain" = ?
LIMIT 1''', (domain,)).fetchone() is not None
def add_instance(self, domain):
self.db.execute('''
INSERT
INTO "instances" ( "domain" )
VALUES ( ? )''', (domain,))
self.db.commit()
def del_instance(self, domain):
self.db.execute('''
DELETE
FROM "communities"
WHERE "instance_id" IN (SELECT "id"
FROM "instances"
WHERE "domain" = ?)''', (domain,))
self.db.execute('''
DELETE
FROM "communities"
WHERE "domain_id" IN (SELECT "id"
FROM "instances"
WHERE "domain" = ?)''', (domain,))
self.db.execute('''
DELETE
FROM "instances"
WHERE "domain" = ?''', (domain,))
self.db.commit()
def has_community(self, instance, name, domain):
return self.db.execute('''
SELECT 1
FROM "communities" AS "c"
INNER JOIN "instances" AS "i"
ON "c"."instance_id" = "i"."id"
INNER JOIN "instances" AS "d"
ON "c"."domain_id" = "d"."id"
WHERE "i"."domain" = ?
AND "c"."name" = ?
AND "d"."domain" = ?
LIMIT 1''', (instance, name, domain)).fetchone() is not None
def add_community(self, instance, name, domain):
self.db.execute('''
INSERT
INTO "communities" ( "instance_id"
, "domain_id"
, "name" )
VALUES ( (SELECT "id"
FROM "instances"
WHERE "domain" = ?)
, (SELECT "id"
FROM "instances"
WHERE "domain" = ?)
, ? )''', (instance, domain, name))
self.db.commit()
class RequestHandler(tornado.web.RequestHandler):
__slots__ = 'db',
def __init__(self, app, req, db):
super().__init__(app, req)
self.db = db
class WelcomeHandler(RequestHandler):
async def get(self):
to = self.get_query_argument('to')
instances = self.db.instances()
await self.render('welcome.html', to = to, instances = instances)
async def post(self):
to = self.get_query_argument('to')
if not to.startswith('/c'):
return self.redirect(f"/error")
instance = self.get_body_argument('instance')
if not self.db.has_instance(instance):
return self.redirect(f"/error")
self.set_cookie('instance', instance, expires_days = 365)
return self.redirect(to)
class CommunityHandler(RequestHandler):
async def get(self, name, domain):
if not self.db.has_instance(domain):
return self.redirect(f"/error")
if (instance := self.get_cookie('instance')) is None:
return self.redirect(url_concat('/welcome', { 'to': f"/c/{name}@{domain}" }))
if not self.db.has_instance(instance):
return self.redirect(f"/error")
if domain == instance:
return self.redirect(f"https://{instance}/c/{name}")
if not self.db.has_community(instance, name, domain):
http = tornado.httpclient.AsyncHTTPClient()
try:
req = await http.fetch(f"https://{instance}/api/v3/community?name={name}@{domain}",
headers = { 'Accept': 'application/json'})
except:
has = False
else:
has = req.code == 200
if has:
self.db.add_community(instance, name, domain)
else:
return self.redirect(f"https://{instance}/search/q/!{name}%40{domain}" +
"/type/All/sort/TopAll/listing_type/All/community_id/0/creator_id/0/page/1")
return self.redirect(f"https://{instance}/c/{name}@{domain}")
class ErrorHandler(RequestHandler):
async def get(self):
await self.render('error.html')
async def main():
tornado.locale.load_translations('lang')
db = DataContext(sqlite3.connect('lmmy.db'))
app = tornado.web.Application([
(r"/", tornado.web.RedirectHandler, { 'url': 'https://join-lemmy.org/' }),
(r"/welcome", WelcomeHandler, { 'db': db }),
(r"/c/([\w.]+)@([a-zA-Z0-9._:-]+)", CommunityHandler, { 'db': db }),
(r"/error", ErrorHandler, { 'db': db })
], static_path = 'static')
app.listen(8888)
await asyncio.Event().wait()
if __name__ == '__main__':
asyncio.run(main())