-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
executable file
·1899 lines (1536 loc) · 69.6 KB
/
app.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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import glob
import io
import mimetypes
import os
import re
from typing import List, Tuple
from flask import Flask, make_response, redirect, render_template, send_file, send_from_directory, session, request
from flask_session import Session
import sqlite3
import uuid
import random
import qrcode
import urllib.parse
import base64
import requests
from misskey import Misskey
from misskey.enum import Permissions as MisskeyPermissions
import markdown
import subprocess
import hashlib
import base64
import traceback
import demoji
import json
from typing import Optional
import time
from functools import wraps
import datetime
import magic
import sys
from modules.classes import ConfigT
from modules.emojistore import EmojiStore
from werkzeug.middleware.profiler import ProfilerMiddleware
import yaml
try:
from yaml import CLoader as PyYAMLLoader, CDumper as PyYAMLDumper
except ImportError:
from yaml import Loader as PyYAMLLoader, Dumper as PyYAMLDumper
#from modules.mfmrenderer import BasicMFMRenderer
APP_VER = '2024.04.14'
try:
gbres = subprocess.check_output(["git", "branch", "--show-current"])
gres = subprocess.check_output(["git", "show", "--format=%h", "--no-patch"])
APP_GITINFO = {
'branch': gbres.decode().strip(),
'commit': gres.decode().strip()
}
except:
APP_GITINFO = None
config: ConfigT = yaml.load(stream=open('config.yml'), Loader=PyYAMLLoader)
sys.setrecursionlimit(16389)
db = sqlite3.connect('database.db', check_same_thread=False)
db.row_factory = sqlite3.Row
emoji_db = sqlite3.connect('emoji_cache.db', check_same_thread=False)
emoji_db.row_factory = sqlite3.Row
cur = db.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS auth_session (id TEXT, mi_session_id TEXT, misskey_token TEXT, host TEXT, acct TEXT, callback_auth_code TEXT, ready INTEGER, auth_url TEXT, auth_qr_base64 TEXT)')
cur.execute('CREATE TABLE IF NOT EXISTS users (id TEXT, acct TEXT, misskey_token TEXT, host TEXT)')
cur.execute('CREATE TABLE IF NOT EXISTS shortlink (sid TEXT, url TEXT)')
cur.execute('CREATE TABLE IF NOT EXISTS settings(acct TEXT, alwaysConvertJPEG INTEGER DEFAULT 0, enableScriptLess INTEGER DEFAULT 0, timeline TEXT, enableImageThumbnail INTEGER DEFAULT 1, enableDatasaveIcon INTEGER DEFAULT 0)')
cur.close()
db.commit()
cur = emoji_db.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS emoji_cache(host TEXT PRIMARY KEY, data TEXT, last_updated INTEGER)')
cur.close()
emoji_db.commit()
app = Flask(__name__, static_url_path='/static', template_folder=os.path.abspath('templates'))
app.secret_key = config['flask']['session_secret']
app.config['SECRET_KEY'] = config['flask']['session_secret']
app.config['SESSION_TYPE'] = 'filesystem'
if config['flask']['enable_profiler']:
app.config['PROFILE'] = True
app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30], profile_dir='./profiler/', filename_format='{method}-{path}.dump')
Session(app)
request.client_settings: dict
HTTP_USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Citraskey/' + APP_VER
http_session = requests.Session()
http_session.headers['User-Agent'] = HTTP_USER_AGENT
emojiStore = EmojiStore(emoji_db, session=http_session)
SYS_DIRS = ['emoji_cache', 'mediaproxy_cache']
MEDIAPROXY_IMAGECOMP_LEVEL_NORMAL = '20'
MEDIAPROXY_IMAGECOMP_LEVEL_HQ = '2'
MEDIAPROXY_IMAGECOMP_LEVEL_NORMAL_GM = '35'
MEDIAPROXY_IMAGECOMP_LEVEL_LQ_GM = '15'
MEDIAPROXY_IMAGECOMP_LEVEL_HQ_GM = '90'
URL_REGEX = re.compile(r'(?!.*(?:"|>))(https?://[\w!?/+\-_~;.,*&@#$%()\'=:]+)')
MISSKEY_EMOJI_REGEX = re.compile(r':([a-zA-Z0-9_]+)(?:@?)(|[a-zA-Z0-9\.-]+):')
MENTION_REGEX = re.compile(r'@([0-9a-zA-Z\-\._@]+)')
NOTIFICATION_TYPES = {
'follow': 'にフォローされました',
'mention': 'にメンションされました',
'reply': 'が返信しました',
'renote': 'にRenoteされました',
'quote': 'に引用されました',
'reaction': 'にリアクションされました',
'pollVote': 'が投票しました',
'receiveFollowRequest': 'からフォローリクエストが届きました',
'followRequestAccepted': 'がフォローリクエストを承認しました',
'groupInvited': 'からグループ招待されました',
'pollEnded': 'の投票が終了しました'
}
PRESET_REACTIONS = ['👍', '❤️', '😆', '🤔', '🎉', '💢', '😥', '😇', '🥴', '🍮', '🤯']
for d in SYS_DIRS:
if not os.path.exists(d):
os.makedirs(d)
else:
for f in glob.glob(f'{d}/*')+glob.glob(f'{d}/*.*'):
os.remove(f)
def intcomma(i: int):
return f'{i:,}'
def randomstr(size: int):
return ''.join(random.choice('0123456789abcdefghijkmnpqrstuvwxyz') for _ in range(size))
def make_short_link(url: str):
sid = randomstr(10)
cur = db.cursor()
cur.execute('SELECT * FROM shortlink WHERE sid = ?', (sid,))
if cur.fetchone():
return make_short_link(url)
cur.execute('INSERT INTO shortlink (sid, url) VALUES (?, ?)', (sid, url))
db.commit()
cur.close()
return sid
def make_mediaproxy_url(target: str, hq: bool = False, jpeg: bool = False, png: bool = False, detail: bool = False, lq: bool = False):
b64code = base64.urlsafe_b64encode(target.encode()).decode()
qs = []
if detail:
qs.append('detail=true')
return f'/mediaproxy{"_hq" if hq else ""}{"_jpeg" if jpeg else ""}{"_lq" if lq else ""}{"_png" if png else ""}/{b64code}' + ('?' + ('&'.join(qs)))
def make_emoji2image_url(target: str):
b64code = base64.urlsafe_b64encode(target.encode()).decode()
return f'/emoji2image/{b64code}'
def parse_misskey_emoji(host, tx):
emojis = []
for emoji in MISSKEY_EMOJI_REGEX.findall(tx):
#print(emoji)
h = emoji[1] or host
if h == '.':
h = session['host']
e = emojiStore.get(h, emoji[0])
if e:
emojis.append(e)
return emojis
def render_icon(user: dict, icon_class: str = 'icon-in-note'):
data_saver = request.client_settings['enableDatasaveIcon']
if (not data_saver) and user.get('avatarDecorations'):
html_s = f'<div style="position:relative"><img src="{make_mediaproxy_url(user["avatarUrl"])}" class="{icon_class}">'
html_m = []
for dec in user['avatarDecorations']:
html_m.append(f'<img src="{make_mediaproxy_url(dec["url"], png=True)}" class="{icon_class} icon-decorated">')
html_e = '</div>'
return html_s + (''.join(html_m)) + html_e
else:
if not data_saver:
return f'<img src="{make_mediaproxy_url(user["avatarUrl"])}" class="{icon_class}">'
else:
return f'<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAAGklEQVRIx+3BMQEAAADCoPVP7W8GoAAAAOANDi4AAbvaTIQAAAAASUVORK5CYII=" class="{icon_class}">'
def sort_roles(roles: List[dict]):
return sorted(roles, key=lambda v: v['displayOrder'], reverse=True)
def emoji_convert(tx: str, host):
emojis = parse_misskey_emoji(host, tx)
for emoji in emojis:
tx = tx.replace(f':{emoji["name"]}:', f'<img src="{make_mediaproxy_url(emoji["url"])}" class="emoji-in-text">')
if not tx:
return tx
parsedUemojis = demoji.findall(tx)
for k in parsedUemojis.keys():
tx = tx.replace(k, f'<img src="{make_emoji2image_url(k)}" class="emoji-in-text">')
return tx
def mfm_parse(text: str, host: str = None):
#t = time.time()
#txt = BasicMFMRenderer(
# emojiStore=emojiStore,
# emojiUrlFilter=make_mediaproxy_url,
# unicodeEmojiFilter=lambda x: f'<img class="emoji-in-text" src="{make_emoji2image_url(x)}">',
# author_host=host,
# hashtag_url='/search?type=tags&q=',
# profile_url='/@'
#).render(text)
#print(f'MFM Parse: {(time.time()-t)*1000:.2f}ms')
txt = cleantext(text)
txt = renderURL(txt)
txt = markdown_render(txt)
txt = mention2link(txt)
txt = convert_tag(txt)
txt = emoji_convert(txt, host)
return txt
def unicode_emoji_hex(e):
return hex(ord(e[0]))[2:]
def reactions_count_html(note_id: str, reactions: dict, my_reaction: Optional[str], host: str):
if not reactions:
return ''
rhtm = []
for k in reactions.keys():
uniqId = randomstr(8)
uniqId2 = randomstr(8)
is_local_emoji = k.endswith('@.:')
is_unicode_emoji = False
emj = k
if k.startswith(':'):
ep = parse_misskey_emoji(host, k)
if ep:
e = ep[0]
if not request.client_settings['enableScriptLess']:
emj = f'<img src="{make_mediaproxy_url(e["url"])}" id="note-reaction-element-{uniqId2}" class="emoji-in-text" data-note-id="{note_id}" data-reaction-content="{e["name"]}" data-reaction-type="custom" data-reaction-element-root="{uniqId}" />'
else:
emj = f'<a href="/api/notes/reaction?noteId={note_id}&reaction={e["name"]}&type=custom&direct=true"><img src="{make_mediaproxy_url(e["url"])}" class="emoji-in-text" /></a>'
else:
emd = demoji.findall(k)
if emd:
is_unicode_emoji = True
emj = f'<img src="{make_emoji2image_url(k)}" id="note-reaction-element-{uniqId2}" class="emoji-in-text" data-note-id="{note_id}" data-reaction-content="{unicode_emoji_hex(k)}" data-reaction-type="unicode" data-reaction-element-root="{uniqId}" />'
if request.client_settings['enableScriptLess']:
emj = f'<a href="/api/notes/reaction?noteId={note_id}&reaction={unicode_emoji_hex(k)}&type=unicode&direct=true"><img src="{make_emoji2image_url(k)}" class="emoji-in-text" /></a>'
rhtm.append(f'<span id="note-reaction-element-root-{uniqId}" class="note-reaction-button-{note_id} {"note-reaction-selected" if k == my_reaction else ""} {"reactive-emoji note-reaction-available" if is_local_emoji or is_unicode_emoji else ""}" data-reaction-element-id="{uniqId2}">{emj}: {reactions[k]}</span>')
html = ' '.join(rhtm)
return html
def render_reaction_picker_element(note_id: str, reactions: List[dict]):
reactionEls = []
for r in reactions:
reactionEls.append(f'<span><img src="{make_mediaproxy_url(r["url"], jpeg=True)}" class="emoji-in-text note-reaction-available note-reaction-picker-child-{note_id}" data-note-id="{note_id}" data-reaction-content=":{r["name"]}:" data-reaction-type="custom"></span>')
return ''.join(reactionEls)
def render_markdown_simple(markdown_text: str):
# 強調のパース
markdown_text = re.sub(r'\*\*(.*?)\*\*', r'<strong>\1</strong>', markdown_text)
markdown_text = re.sub(r'__(.*?)__', r'<strong>\1</strong>', markdown_text)
# 斜体のパース
markdown_text = re.sub(r'\*(.*?)\*', r'<em>\1</em>', markdown_text)
markdown_text = re.sub(r'_(.*?)_', r'<em>\1</em>', markdown_text)
# リンクのパース
markdown_text = re.sub(r'\[([^\]]+?)\]\(([^)]+?)\)', r'<a href="\2">\1</a>', markdown_text)
markdown_text = markdown_text.replace('\n', '<br/>')
if markdown_text.startswith('<p>'):
markdown_text = markdown_text[3:]
if markdown_text.endswith('</p>'):
markdown_text = markdown_text[:-4]
return markdown_text
def markdown_render(text: str):
#t = markdown.markdown(text)
#if t.startswith('<p>'):
# t = t[3:]
#if t.endswith('</p>'):
# t = t[:-4]
t = render_markdown_simple(text)
return t
def cleantext(text: str):
if not text:
return ''
# remove script tag
text = re.sub(r'<script.*?>.*?</script>', '', text, flags=re.DOTALL)
return text
def convert_tag(text: str):
# inline text
return re.sub(r'(^|\s)#(\w+)', r'\1<a href="/search?type=tags&q=\2">#\2</a>', text)
def mention2link(text: str):
def replace(match):
username = match.group(1)
# 既存のURLの一部でない場合にのみ置換
if not re.search(r'https?://[^\s]*@' + re.escape(username), text):
return f'<a href="/@{username}">@{username}</a>'
else:
return match.group(0)
result = MENTION_REGEX.sub(replace, text)
return result
#return re.sub(r'@([0-9a-zA-Z\-\._@]+)', r'<a href="/@\1">@\1</a>', text)
def render_note_element(note: dict, option_data: dict, nest_count: int = 1):
if nest_count < 0:
return ''
return render_template(
'app/components/note.html',
note=note,
option_data=option_data,
markdown_render=markdown_render,
emoji_convert=emoji_convert,
reactions_count_html=reactions_count_html,
enumerate=enumerate,
render_note_element=render_note_element,
make_mediaproxy_url=make_mediaproxy_url,
renderURL=renderURL,
format_datetime=format_datetime,
make_emoji2image_url=make_emoji2image_url,
unicode_emoji_hex=unicode_emoji_hex,
cleantext=cleantext,
convert_tag=convert_tag,
mention2link=mention2link,
i=session['i'],
meta=session['meta'],
user_host=session['host'],
nest_count=nest_count,
str=str,
render_poll=render_poll,
PRESET_REACTIONS=PRESET_REACTIONS,
mfm_parse=mfm_parse,
print=print,
render_icon=render_icon
)
def render_message_element(message: dict, receiverId: str):
return render_template(
'app/components/message.html',
message=message,
markdown_render=markdown_render,
emoji_convert=emoji_convert,
reactions_count_html=reactions_count_html,
enumerate=enumerate,
make_mediaproxy_url=make_mediaproxy_url,
renderURL=renderURL,
format_datetime=format_datetime,
cleantext=cleantext,
convert_tag=convert_tag,
mention2link=mention2link,
i=session['i'],
meta=session['meta'],
user_host=session['host'],
str=str,
receiverId=receiverId,
mfm_parse=mfm_parse
)
def renderURL(src):
return URL_REGEX.sub(r'<a href="\1">\1</a>', src)
def render_notification(n: dict):
ntype = n['type']
if ntype == 'app':
return 'この通知には対応していません'
ntypestring = NOTIFICATION_TYPES.get(ntype, '不明')
if ntype == 'reaction':
ntypestring = emoji_convert(n['reaction'], n['user']['host'] or session['host'])
if ntype != 'pollEnded':
user_avatar_url = n["user"]["avatarUrl"]
user_name = n["user"]["name"]
user_acct_name = n["user"]["username"]
user_name_emojis = n["user"]["emojis"]
htm = f'<a href="/users/{n["user"]["id"]}"><img src="{make_mediaproxy_url(user_avatar_url)}" width="18"></a> {emoji_convert(cleantext(user_name or user_acct_name), n["user"]["host"] or session["host"])} さん{ntypestring}<br>'
else:
#user_avatar_url = n["note"]["user"]["avatarUrl"]
#user_name = n["note"]["user"]["name"]
#user_acct_name = n["note"]["user"]["username"]
#user_name_emojis = n["note"]["user"]["emojis"]
htm = 'アンケートの結果が出ました<br>'
if n.get('note'):
if ntype != 'renote':
htm += render_note_element(n['note'], {})
else:
htm += render_note_element(n['note']['renote'], {})
return htm
def render_poll(note_id: str, poll: dict):
disabled = False
status = ''
if poll['expiresAt']:
dt = datetime.datetime.strptime(poll['expiresAt'], '%Y-%m-%dT%H:%M:%S.%fZ').astimezone(datetime.timezone.utc)
if dt < datetime.datetime.now(datetime.timezone.utc):
disabled = True
status = '投票終了'
else:
d = dt - datetime.datetime.now(datetime.timezone.utc)
status = f'あと{d.days}日{d.seconds // 3600}時間{d.seconds % 3600 // 60}分'
if not poll['multiple']:
for p in poll['choices']:
if p['isVoted']:
disabled = True
break
poll_lines = []
for i, p in enumerate(poll['choices']):
po = '<tr>'
po += f'<td><input type="{"checkbox" if poll["multiple"] else "radio" }" class="note-poll-choice" data-note-id="{note_id}" data-choice-index="{i}" {"checked disabled" if p["isVoted"] else "" } {"disabled" if disabled else ""}></td>'
po += f'<td>{cleantext(p["text"])}</td>'
po += f'<td>{p["votes"]}</td>'
po += '</tr>'
poll_lines.append(po)
return '<table><tbody>' + (''.join(poll_lines)) + f'</tbody></table><small>{status}</small>'
def render_channel_card(channel: dict):
return render_template('app/components/channel_card.html', channel=channel, emoji_convert=emoji_convert, markdown_render=markdown_render, mention2link=mention2link)
def render_user_profile(user, tab: str = None, untilId: str = None):
notes_payload = {'i': session['misskey_token'], 'userId': user['id'], 'limit': 11, 'includeReplies': False}
if tab:
if tab == 'replies':
notes_payload['includeReplies'] = True
if tab == 'medias':
notes_payload['withFiles'] = True
if untilId:
notes_payload['untilId'] = untilId
if tab != 'pins':
ok, res, r2 = api(f'/api/users/notes', json=notes_payload)
if not ok:
if res.get('error'):
return make_response(f'{res["error"]["message"]}<br>{res["error"]["code"]}', 500)
notes = res
else:
notes = user['pinnedNotes']
return render_template('app/user_detail.html',
user=user,
notes=notes,
render_note_element=render_note_element,
make_mediaproxy_url=make_mediaproxy_url,
emoji_convert=emoji_convert,
mention2link=mention2link,
cleantext=cleantext,
render_icon=render_icon,
sort_roles=sort_roles,
mfm_parse=mfm_parse
)
def render_user_card(user):
return render_template('app/components/user_card.html',
user=user,
make_mediaproxy_url=make_mediaproxy_url,
emoji_convert=emoji_convert,
mention2link=mention2link,
render_icon=render_icon,
mfm_parse=mfm_parse,
markdown_render=markdown_render
)
def error_json(error_id: int, reason: Optional[str] = None, internal: bool = False, status: int = None):
return make_response(json.dumps({
'errorId': error_id,
'reason': reason
}), status or (500 if internal else 400))
def fetch_meta(host: str) -> dict:
r = http_session.post('https://' + host + '/api/meta', headers={'Content-Type': 'application/json'}, data=b'{}')
if r.status_code != 200:
raise Exception('Failed to fetch meta')
return r.json()
def fetch_i(host: str, token: str) -> dict:
r = http_session.post('https://' + host + '/api/i', json={'i': token})
if r.status_code != 200:
raise Exception('Failed to fetch i')
return r.json()
def api(url, host: str = None, method: str = 'POST', decode_json: bool = True, *args, **kwargs) -> Tuple[bool, Optional[dict], requests.Response]:
if host:
hst = host
else:
hst = session['host']
if not hst:
raise Exception('No host')
r = getattr(http_session, method.lower())('https://' + hst + url, *args, **kwargs)
#print(f'{url}: {r.status_code}')
if r.status_code == 200:
obj = {}
if decode_json:
obj = r.json()
return True, obj, r
if r.status_code == 204:
return True, None, r
if r.status_code >= 400:
obj = {}
if decode_json:
obj = r.json()
return False, obj, r
def formcheck2bool(formVal):
return 1 if formVal == 'on' else 0
def login_check(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not session.get('logged_in') or not session.get('id'):
return make_response('You are not logged in<br><a href="/logout">logout</a>', 401)
cur = db.cursor()
cur.execute('SELECT * FROM users WHERE id = ?', (session['id'],))
row = cur.fetchone()
if not row:
cur.close()
return make_response('You are not logged in<br><a href="/logout">logout</a>', 401)
return f(*args, **kwargs)
return decorated_function
def inject_client_settings(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if session.get('acct'):
cur = db.cursor()
cur.execute('SELECT * FROM settings WHERE acct = ?', (session['acct'],))
row = cur.fetchone()
cur.close()
if not row:
return make_response('You must login again<br><a href="/logout">logout</a>', 401)
request.client_settings = dict(row)
else:
request.client_settings = {}
return f(*args, **kwargs)
return decorated_function
def format_datetime(dtstr: str, to_jst: bool = True):
dt = datetime.datetime.strptime(dtstr, '%Y-%m-%dT%H:%M:%S.%fZ')
if to_jst:
dt = dt + datetime.timedelta(hours=9)
return dt.strftime('%Y/%m/%d %H:%M:%S')
@app.route('/')
@inject_client_settings
def root():
if session.get('logged_in'):
return home_timeline()
else:
return render_template('index.html', app_ver=APP_VER)
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico', mimetype='image/vnd.microsoft.icon')
@app.route('/logout')
def logout():
if session.get('id'):
cur = db.cursor()
cur.execute('DELETE FROM users WHERE id = ?', (session['id'],))
cur.close()
db.commit()
session.clear()
return redirect('/')
@app.route('/auth/start', methods=['POST'])
def auth_start():
hostname = request.form.get('hostname')
if not hostname:
return make_response('hostname is required', 400)
session['auth_id'] = str(uuid.uuid4())
mi_sesid = str(uuid.uuid4())
callbk_code = randomstr(8)
callback_url = f'{"https" if request.is_secure else "http"}://{request.host}/auth/callback'
urlargs = urllib.parse.urlencode({
'name': 'Citraskey',
'permission': ','.join([perm.value for perm in [
MisskeyPermissions.READ_ACCOUNT,
MisskeyPermissions.READ_DRIVE,
MisskeyPermissions.READ_NOTIFICATIONS,
MisskeyPermissions.READ_REACTIONS,
MisskeyPermissions.READ_MESSAGING,
MisskeyPermissions.READ_FOLLOWING,
MisskeyPermissions.READ_MUTES,
MisskeyPermissions.READ_BLOCKS,
MisskeyPermissions.READ_CHANNELS,
MisskeyPermissions.WRITE_ACCOUNT,
MisskeyPermissions.WRITE_DRIVE,
MisskeyPermissions.WRITE_NOTES,
MisskeyPermissions.WRITE_REACTIONS,
MisskeyPermissions.WRITE_VOTES,
MisskeyPermissions.WRITE_MESSAGING,
MisskeyPermissions.WRITE_FOLLOWING,
MisskeyPermissions.WRITE_MUTES,
MisskeyPermissions.WRITE_BLOCKS,
MisskeyPermissions.WRITE_CHANNELS
]]),
'callback': callback_url
})
auth_url = f'http://{hostname}/miauth/{mi_sesid}?{urlargs}'
f = io.BytesIO()
qr = qrcode.make(auth_url)
qr.save(f)
f.seek(0)
qr_base64 = 'data:image/png;base64,' + base64.b64encode(f.read()).decode('utf-8')
sid = make_short_link(auth_url)
short_auth_url = f'{"https" if request.is_secure else "http"}://{request.host}/s/{sid}'
cur = db.cursor()
cur.execute('INSERT INTO auth_session(id, mi_session_id, misskey_token, host, callback_auth_code, ready, auth_url, auth_qr_base64) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', (session['auth_id'], mi_sesid, None, hostname, callbk_code, 0, short_auth_url, qr_base64))
cur.close()
db.commit()
return render_template('auth_start.html', auth_url=short_auth_url, hostname=hostname, qr_base64=qr_base64)
@app.route('/auth/check', methods=['POST'])
def auth_check():
if not session.get('auth_id'):
return redirect('/')
cur = db.cursor()
cur.execute('SELECT * FROM auth_session WHERE id = ?', (session['auth_id'],))
row = cur.fetchone()
cur.close()
if not row:
return make_response('auth_id is invalid', 400)
if row['ready'] == 0:
return render_template('auth_start.html', not_ready=True, auth_url=row['auth_url'], hostname=row['host'], qr_base64=row['auth_qr_base64'])
else:
return render_template('auth_callback.html')
@app.route('/auth/callback', methods=['GET'])
def auth_callback():
session_id = request.args.get('session')
if not session_id:
return make_response('session is required', 400)
cur = db.cursor()
cur.execute('SELECT * FROM auth_session WHERE mi_session_id = ?', (session_id,))
row = cur.fetchone()
cur.close()
if not row:
return make_response('session is invalid', 400)
ok, res, r = api(f'/api/miauth/{session_id}/check', host=row['host'])
if not ok:
cur = db.cursor()
cur.execute('DELETE FROM auth_session WHERE mi_session_id = ?', (session_id,))
cur.close()
db.commit()
return make_response(f'Session check failed ({r.status_code})', 400)
if not res['ok']:
cur = db.cursor()
cur.execute('DELETE FROM auth_session WHERE mi_session_id = ?', (session_id,))
cur.close()
db.commit()
return make_response(f'Session check failed', 400)
acct = f'{res["user"]["username"]}@{row["host"]}'
misskey_token = res['token']
cur = db.cursor()
cur.execute('UPDATE auth_session SET ready = 1, misskey_token = ?, acct = ? WHERE mi_session_id = ?', (misskey_token, acct, session_id))
cur.close()
db.commit()
return render_template('auth_ok.html', callback_code=row['callback_auth_code'], acct=acct)
@app.route('/auth/callback_check', methods=['POST'])
def auth_callback_check():
if not session.get('auth_id'):
return redirect('/')
cur = db.cursor()
cur.execute('SELECT * FROM auth_session WHERE id = ?', (session['auth_id'],))
row = cur.fetchone()
cur.close()
if not row:
return make_response('auth_id is invalid', 400)
if row['ready'] == 0:
return make_response('まだ認証ができていません', 400)
callback_code = request.form.get('callback_code')
if not callback_code:
return make_response('callback_code is required', 400)
if callback_code != row['callback_auth_code']:
return make_response('callback_code is invalid', 400)
session['id'] = str(uuid.uuid4())
cur = db.cursor()
cur.execute('DELETE FROM auth_session WHERE id = ?', (session['auth_id'],))
cur.execute('INSERT INTO users(id, acct, misskey_token, host) VALUES (?, ?, ?, ?)', (session['id'], row['acct'], row['misskey_token'], row['host']))
cur.close()
db.commit()
try:
meta = fetch_meta(row['host'])
except Exception as e:
return make_response(str(e), 500)
session['i'] = fetch_i(row['host'], row['misskey_token'])
session['meta'] = meta
session['logged_in'] = True
session['host'] = row['host']
session['acct'] = f'{session["i"]["username"]}@{row["host"]}'
session['misskey_token'] = row['misskey_token']
cur = db.cursor()
cur.execute('SELECT * FROM settings WHERE acct = ?', (row['acct'],))
row = cur.fetchone()
if not row:
cur.execute('INSERT INTO settings(acct, alwaysConvertJPEG, timeline) VALUES (?, ?, ?)', (session['acct'], 0, 'home'))
db.commit()
cur.close()
return redirect('/')
@app.route('/s/<sid>')
def shortlink(sid):
cur = db.cursor()
cur.execute('SELECT * FROM shortlink WHERE sid = ?', (sid,))
row = cur.fetchone()
cur.close()
if not row:
return make_response('shortlink is invalid', 400)
return redirect(row['url'])
def home_timeline():
if not session.get('logged_in'):
return make_response('!?')
if not session.get('id'):
session['logged_in'] = False
return redirect('/')
cur = db.cursor()
cur.execute('SELECT * FROM users WHERE id = ?', (session['id'],))
row = cur.fetchone()
cur.close()
if not row:
session['logged_in'] = False
return redirect('/')
timeline_type = request.args.get('tl')
if timeline_type:
if timeline_type not in ['home', 'local', 'hybrid', 'global', 'media']:
return make_response('invalid timeline type', 400)
cur = db.cursor()
cur.execute('UPDATE settings SET timeline = ? WHERE acct = ?', (timeline_type, session['acct']))
cur.close()
db.commit()
request.client_settings['timeline'] = timeline_type
tl = request.client_settings['timeline']
if tl == 'home':
tl = 'timeline'
else:
tl = tl + '-timeline'
untilId = request.args.get('untilId')
payload = {'i': row['misskey_token'], 'limit': 20}
if untilId:
payload['untilId'] = untilId
if timeline_type == 'media' or tl == 'media-timeline':
tl = 'hybrid-timeline'
payload['withFiles'] = True
payload['withReplies'] = False
ok, notes, r = api(f'/api/notes/{tl}', host=row['host'], json=payload, timeout=10)
if not ok:
return make_response(f'Timeline failed ({r.status_code})', 400)
#for note in notes:
# print(f'{note["user"]["username"]}: {note["text"]}')
# print(note['reactions'], note['emojis'])
return render_template(
'app/home.html',
notes=notes,
render_note_element=render_note_element
)
@app.route('/notifications', methods=['GET'])
@login_check
@inject_client_settings
def notifications():
untilId = request.args.get('untilId')
payload = {'i': session['misskey_token'], 'limit': 10}
if untilId:
payload['untilId'] = untilId
ok, notifications, r = api(f'/api/i/notifications', json=payload)
if not ok:
return make_response(f'failed ({r.status_code})', 500)
return render_template(
'app/notifications.html',
notifications=notifications,
render_notification=render_notification
)
@app.route('/search', methods=['GET'])
@login_check
@inject_client_settings
def search():
q = request.args.get('q')
if not q:
return render_template('app/search.html', results=[], next_url='')
#return make_response('q is required', 400)
search_type = request.args.get('type')
if not search_type:
search_type = 'notes'
untilId = request.args.get('untilId')
if search_type not in ['notes', 'tags', 'users']:
return make_response('invalid search type', 400)
if search_type == 'notes':
payload = {'i': session['misskey_token'], 'limit': 10, 'query': q}
if untilId:
payload['untilId'] = untilId
ok, notes, r = api(f'/api/notes/search', json=payload)
if not ok:
return make_response(f'failed ({r.status_code})', 500)
next_url = None
if notes:
next_url = f'/search?type=notes&q={urllib.parse.quote(q)}&untilId={notes[-1]["id"]}'
return render_template('app/search.html', results=notes, render_note_element=render_note_element, next_url=next_url)
elif search_type == 'tags':
payload = {'i': session['misskey_token'], 'limit': 10, 'tag': q}
if untilId:
payload['untilId'] = untilId
ok, notes, r = api(f'/api/notes/search-by-tag', json=payload)
if not ok:
return make_response(f'failed ({r.status_code})', 500)
next_url = None
if notes:
next_url = f'/search?type=tags&q={urllib.parse.quote(q)}&untilId={notes[-1]["id"]}'
return render_template('app/search.html', results=notes, render_note_element=render_note_element, next_url=next_url)
elif search_type == 'users':
if untilId and not untilId.isdigit():
return make_response('untilId must be integer', 400)
elif not untilId:
untilId = '0'
userOrigin = request.args.get('userOrigin')
payload = {'i': session['misskey_token'], 'query': q, 'limit': 10, 'offset': int(untilId)}
if userOrigin:
if not (userOrigin in ['combined', 'local', 'remote']):
return make_response('userOrigin is invalid', 400)
payload['origin'] = userOrigin
ok, users, r = api('/api/users/search', json=payload)
if not ok:
return make_response(f'failed ({r.status_code})', 500)
next_url = None
if users:
next_url_param = {'type': 'users', 'q': q, 'untilId': int(untilId) + max(10, len(users))}
if userOrigin:
next_url_param['userOrigin'] = userOrigin
next_url = '/search?' + urllib.parse.urlencode(next_url_param)
return render_template('app/search.html', results=users, render_user_card=render_user_card, next_url=next_url)
@app.route('/messaging', methods=['GET'])
@login_check
def messaging():
ok, histories, r = api(f'/api/messaging/history', json={'i': session['misskey_token']})
if not ok:
return make_response(f'failed ({r.status_code})', 500)
histories_f = []
user_ids = set()
for h in histories:
if h['user']['id'] in user_ids:
continue
user_ids.add(h['user']['id'])
histories_f.append(h)
return render_template('app/messaging.html',
histories=histories_f,
emoji_convert=emoji_convert,
format_datetime=format_datetime,
make_mediaproxy_url=make_mediaproxy_url,
cleantext=cleantext
)
@app.route('/messaging/<string:user_id>', methods=['GET'])
@login_check
def messaging_user(user_id):
ok, messages, r = api(f'/api/messaging/messages', json={'i': session['misskey_token'], 'userId': user_id})
if not ok:
return make_response(f'failed ({r.status_code})', 500)
return render_template('app/messaging_user.html',
messages=messages,
emoji_convert=emoji_convert,
format_datetime=format_datetime,
make_mediaproxy_url=make_mediaproxy_url,
render_message_element=render_message_element,
sender_id=user_id
)
@app.route('/follow-requests')
@login_check
@inject_client_settings
def follow_requests():
ok, follow_requests, r = api(f'/api/following/requests/list', json={'i': session['misskey_token']})
if not ok:
return make_response(f'failed ({r.status_code})', 500)
return render_template('app/follow_requests.html',
follow_requests=follow_requests,
emoji_convert=emoji_convert,
make_mediaproxy_url=make_mediaproxy_url,
render_icon=render_icon
)
@app.route('/settings', methods=['GET', 'POST'])
@login_check
@inject_client_settings
def settings():
if request.method == 'GET':
return render_template('app/settings.html', settings=request.client_settings, app_ver=APP_VER, app_gitinfo=APP_GITINFO, updated=False)
if request.method == 'POST':
alwaysConvertJPEG = formcheck2bool(request.form.get('alwaysConvertJPEG'))
enableScriptLess = formcheck2bool(request.form.get('enableScriptLess'))
enableImageThumbnail = 1 if request.form.get('enableImageThumbnail')=='on' else 0
enableDatasaveIcon = 1 if request.form.get('enableDatasaveIcon')=='on' else 0
cur = db.cursor()
cur.execute('UPDATE settings SET alwaysConvertJPEG = ?, enableScriptLess = ?, enableImageThumbnail = ?, enableDatasaveIcon = ? WHERE acct = ?', (alwaysConvertJPEG, enableScriptLess, enableImageThumbnail, enableDatasaveIcon, session['acct']))
cur.execute('SELECT * FROM settings WHERE acct = ?', (session['acct'],))
row = cur.fetchone()