forked from 35enidoi/MisT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
misskey_tui.py
1365 lines (1233 loc) · 55 KB
/
misskey_tui.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
from asciimatics.scene import Scene
from asciimatics.screen import Screen
from asciimatics.renderers import ImageFile
from asciimatics.widgets import Frame, Layout, TextBox, Button, PopUpDialog, VerticalDivider, Text, ListBox, PopupMenu
from asciimatics.exceptions import StopApplication, ResizeScreenError, NextScene
from misskey import Misskey, exceptions, MiAuth
from requests.exceptions import ReadTimeout, ConnectionError, ConnectTimeout, InvalidURL, HTTPError
import os
# _を定義
# プログラム的には意味はない
# これがないとlinterが地獄になる(_の定義がないため)
global _
class MkAPIs():
def __init__(self) -> None:
# version
# syoumi tekitouni ageteru noha naisyo
self.version = 0.381
# mistconfig load
if os.path.isfile("mistconfig.conf"):
self.mistconfig_put(True)
if self.mistconfig["version"] < self.version:
self.mistconfig["version"] = self.version
if not self.mistconfig.get("default"):
self.mistconfig["default"] = {"theme":"default","lang":None,"defaulttoken":None}
self.lang = self.mistconfig["default"].get("lang")
self.theme = self.mistconfig["default"]["theme"]
self.mistconfig_put()
else:
self.lang = self.mistconfig["default"].get("lang")
self.theme = self.mistconfig["default"]["theme"]
else:
self.lang = None
self.theme = "default"
self.mistconfig = {"version":self.version,"default":{"theme":self.theme,"lang":self.lang,"defaulttoken":None},"tokens":[]}
self.mistconfig_put()
# MisT settings
self.tmp = []
self.notes = []
self.nowpoint = 0
self.reacdb = None
self.cfgtxts = ""
self.crnotetxts = "Tab to change widget"
self.crnoteconf = {"CW":None,"renoteId":None,"replyId":None}
self.constcrnoteconf = self.crnoteconf.copy()
self.init_translation()
# Misskey py settings
if (default := self.mistconfig["default"]).get("defaulttoken") or default.get("defaulttoken") == 0:
if len(self.mistconfig["tokens"]) != 0 and (len(self.mistconfig["tokens"]) > default["defaulttoken"]):
self.i = self.mistconfig["tokens"][default["defaulttoken"]]["token"]
self.instance = self.mistconfig["tokens"][default["defaulttoken"]]["instance"]
else:
self.i = None
self.instance = "misskey.io"
else:
self.i = None
self.instance = "misskey.io"
self.mk = None
self.tl = "LTL"
self.tl_len = 10
is_ok = self.reload()
if not is_ok:
self.i = None
def mistconfig_put(self,loadmode=False):
import json
if loadmode:
with open("mistconfig.conf", "r") as f:
self.mistconfig = json.loads(f.read())
else:
with open("mistconfig.conf", "w") as f:
f.write(json.dumps(self.mistconfig))
def init_translation(self):
import gettext
# 翻訳ファイルを配置するディレクトリ
path_to_locale_dir = os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'./locale'
)
)
# もしself.langがNoneなら翻訳なしに
if self.lang is None:
lang = ""
else:
lang = self.lang
# 翻訳用クラスの設定
translater = gettext.translation(
'messages', # domain: 辞書ファイルの名前
localedir=path_to_locale_dir, # 辞書ファイル配置ディレクトリ
languages=[lang], # 翻訳に使用する言語
fallback=True # .moファイルが見つからなかった時は未翻訳の文字列を出力
)
# Pythonの組み込みグローバル領域に_という関数を束縛する
translater.install()
def reload(self):
bef_mk = self.mk
try:
self.mk=Misskey(self.instance,self.i)
if self.i is not None:
self.mk.i()
return True
except (exceptions.MisskeyAPIException, exceptions.MisskeyAuthorizeFailedException,
ConnectionError, ReadTimeout, InvalidURL):
self.mk = bef_mk
return False
def miauth_load(self):
permissions = ["read:account","write:account","read:messaging","write:messaging","read:notifications",
"write:notifications","read:reactions","write:reactions","write:notes"]
return MiAuth(self.instance,name="MisT",permission=permissions)
def miauth_check(self,mia):
try:
self.i = mia.check()
return True
except (exceptions.MisskeyMiAuthFailedException, HTTPError):
return False
def get_i(self):
try:
return self.mk.i()
except (exceptions.MisskeyAPIException, ConnectionError):
return None
def get_note(self,untilid=None,sinceid=None):
try:
if self.tl == "HTL":
self.notes = self.mk.notes_timeline(self.tl_len,with_files=False,until_id=untilid,since_id=sinceid)
elif self.tl == "LTL":
self.notes = self.mk.notes_local_timeline(self.tl_len,with_files=False,until_id=untilid,since_id=sinceid)
elif self.tl == "STL":
self.notes = self.mk.notes_hybrid_timeline(self.tl_len,with_files=False,until_id=untilid,since_id=sinceid)
elif self.tl == "GTL":
self.notes = self.mk.notes_global_timeline(self.tl_len,with_files=False,until_id=untilid,since_id=sinceid)
return True
except (exceptions.MisskeyAPIException, ReadTimeout):
self.notes = []
return False
def get_ntfy(self):
try:
return self.mk.i_notifications(100)
except (exceptions.MisskeyAPIException, ReadTimeout):
return None
def get_reactiondb(self):
import requests
try:
ret = requests.get(f'https://{self.instance}/api/emojis')
if ret.status_code == 200:
import json
self.reacdb = {}
for i in json.loads(ret.text)["emojis"]:
self.reacdb[i["name"]] = i["aliases"]
self.reacdb[i["name"]].append(i["name"])
else:
self.reacdb = None
except ConnectTimeout:
self.reacdb = None
def note_update(self):
beforenotes = self.notes.copy()
noteid = self.notes[0]["id"]
is_ok = self.get_note(noteid[0:8]+"zz")
if is_ok:
return True
else:
self.notes = beforenotes
return False
def noteshow(self,noteid):
try:
return self.mk.notes_show(noteid)
except (exceptions.MisskeyAPIException, ReadTimeout):
return None
def get_instance_meta(self):
try:
self.meta = self.mk.meta()
return True
except (exceptions.MisskeyAPIException, ConnectTimeout):
return False
def get_instance_icon(self):
import requests
try:
iconurl = self.meta["iconUrl"]
returns = requests.get(iconurl)
if returns.status_code == 200:
import io
icon = io.BytesIO(returns.content)
return icon
else:
return "Error"
except ConnectTimeout:
return "Error"
def create_note(self, text):
try:
return self.mk.notes_create(text, self.crnoteconf["CW"],
renote_id=self.crnoteconf["renoteId"],
reply_id=self.crnoteconf["replyId"])
except exceptions.MisskeyAPIException:
return None
def create_renote(self, renoteid):
try:
return self.mk.notes_create(renote_id=renoteid)
except exceptions.MisskeyAPIException:
return None
def create_reaction(self, noteid, reaction):
try:
return self.mk.notes_reactions_create(noteid, reaction)
except exceptions.MisskeyAPIException:
return None
class NoteView(Frame):
def __init__(self, screen, msk):
super(NoteView, self).__init__(screen,
screen.height,
screen.width,
title="Notes",
reduce_cpu=True,
can_scroll=False)
# initialize
self.msk_ = msk
self.set_theme(self.msk_.theme)
# notebox create
self.note=TextBox(screen.height-3,as_string=True,line_wrap=True)
# button create
buttonnames = (_("Quit"), _("Move L"), _("Move R"),
_("Noteupdate"), _("Note Get"), _("More"),
_("Config"))
on_click = (self.pop_quit, self.move_l, self.move_r,
self.noteupdate, self.get_note, self.pop_more,
self.config)
self.buttons = [Button(buttonnames[i], on_click[i]) for i in range(len(buttonnames))]
# layout create
layout = Layout([100])
layout2 = Layout([1 for _ in range(len(self.buttons))])
self.add_layout(layout)
self.add_layout(layout2)
# add widget
layout.add_widget(self.note)
for i in range(len(self.buttons)):
layout2.add_widget(self.buttons[i],i)
# define selfs
self._move_l = self.buttons[buttonnames.index(_("Move L"))]
self._move_r = self.buttons[buttonnames.index(_("Move R"))]
self.layout = layout
self.layout2 = layout2
# disable
self.note.disabled = True
moreind = buttonnames.index(_("More"))
noteupind = buttonnames.index(_("Noteupdate"))
if self.msk_.i is None:
self.buttons[moreind].disabled = True
else:
self.buttons[moreind].disabled = False
if len(self.msk_.notes) == 0:
self.buttons[noteupind].disabled = True
else:
self.buttons[noteupind].disabled = False
# fix
self._note_reload()
self.fix()
def get_note(self,arg=-1):
if arg == -1:
if self.msk_.mk is None:
self.popup((_("connect failed.\nPlease Instance recreate.")), [(_("Ok"))])
return
self.popup(_("note get from"),[(_("latest")),(_("until")),(_("since")),(_("return"))],self.get_note)
return
elif arg == 0:
untilid = None
sinceid = None
elif arg == 3:
return
else:
if len(self.msk_.notes) == 0:
self.popup((_("get note please(latest)")),[(_("Ok"))])
return
elif arg == 1:
untilid = self.msk_.notes[self.msk_.nowpoint]["id"]
sinceid = None
elif arg == 2:
untilid = None
sinceid = self.msk_.notes[self.msk_.nowpoint]["id"]
self.msk_.get_note(untilid,sinceid)
self.msk_.nowpoint=0
self._note_reload()
def noteupdate(self):
is_ok = self.msk_.note_update()
if is_ok:
self._note_reload()
self.popup((_("success")), [_("Ok")])
else:
self.popup((_("something occured")), [_("Ok")])
def move_r(self):
self.msk_.nowpoint += 1
self._note_reload()
def move_l(self):
self.msk_.nowpoint -= 1
self._note_reload()
def _note_reload(self):
self.note.value = f"<{self.msk_.nowpoint+1}/{len(self.msk_.notes)}>\n"
if len(self.msk_.notes) == 0:
self._noteput((_("something occured while noteget.")),(_("or welcome to MisT!")))
self.buttons[3].disabled = True
else:
self.buttons[3].disabled = False
self._note_inp(self.msk_.notes[self.msk_.nowpoint])
if self.msk_.notes[self.msk_.nowpoint].get("renote"):
self._note_inp(self.msk_.notes[self.msk_.nowpoint]["renote"])
if self.msk_.nowpoint == 0:
self._move_l.disabled = True
self.switch_focus(self.layout2,2,0)
else:
self._move_l.disabled = False
if (self.msk_.nowpoint == len(self.msk_.notes)-1) or (self.msk_.nowpoint == len(self.msk_.notes)):
self._move_r.disabled = True
self.switch_focus(self.layout2,1,0)
else:
self._move_r.disabled = False
def _note_inp(self,note):
if note["user"]["host"] is None:
username = f'@{note["user"]["username"]}@{self.msk_.instance}'
else:
username = f'@{note["user"]["username"]}@{note["user"]["host"]}'
if note["user"]["name"] is None:
name = note["user"]["username"]
else:
name = note["user"]["name"]
if note["renoteId"] is not None:
self._noteput(f"{name} [{username}] was renoted noteId:{note['id']}")
else:
self._noteput(f"{name} [{username}] was noted noteId:{note['id']}")
self.msk_.tmp.append("")
if note["user"]["isBot"]:
self.msk_.tmp[-1] += "isBot:True "
if note["user"]["isCat"]:
self.msk_.tmp[-1] += "isCat:True"
if (a := self.msk_.tmp.pop()) != "":
self._noteput(a)
if note["user"].get("badgeRoles"):
if len(note["user"]["badgeRoles"]) != 0:
self._noteput("badgeRoles:["+",".join(i["name"] for i in note["user"]["badgeRoles"])+"]")
self._noteput("-"*(self.screen.width-4))
if note["text"] is None:
if len(note["files"]) == 0:
return
if note["cw"] is not None:
self._noteput("CW detect!",note["cw"],"~"*(self.screen.width-4))
if note["user"]["isCat"]:
self._noteput(note["text"].replace("な","にゃ").replace("ナ","ニャ"),"")
else:
self._noteput(note["text"],"")
if len(note["files"]) != 0:
self._noteput(f'{len(note["files"])} files')
self._noteput(f'{note["renoteCount"]} renotes {note["repliesCount"]} replys {sum(note["reactions"].values())} reactions',
" ".join(f'{i.replace("@.","")}[{note["reactions"][i]}]' for i in note["reactions"].keys()), "")
def _noteput(self,*arg):
for i in arg:
self.note.value += str(i)+"\n"
def pop_more(self):
self.popup((_("?")), [(_("Create Note")), (_("Renote")), (_("Reply")), (_("Reaction")), (_("Notification")), (_("return"))],self._ser_more)
def pop_quit(self):
self.popup((_("Quit?")), [(_("yes")), (_("no"))],self._ser_quit)
def _ser_more(self,arg):
if arg == 0:
# Create Note
raise NextScene("CreateNote")
elif arg == 1:
# Renote or Quote
if len(self.msk_.notes) == 0:
self.popup((_("Please Note Get")), [(_("Ok"))])
else:
self.popup((_('Renote or Quote?')).format(), [(_("Renote")), (_("Quote")), (_("Return"))],self._ser_rn)
elif arg == 2:
# Reply
if len(self.msk_.notes) == 0:
self.popup((_("Please Note Get")), [(_("Ok"))])
else:
if (noteval := self.msk_.notes[self.msk_.nowpoint]).get("renote"):
if noteval["text"] is None:
noteid = noteval["renote"]["id"]
else:
noteid = noteval["id"]
else:
noteid = noteval["id"]
self.msk_.crnoteconf["replyId"] = noteid
raise NextScene("CreateNote")
elif arg == 3:
# Reaction
if len(self.msk_.notes) == 0:
self.popup((_("Please Note Get")), [(_("Ok"))])
else:
self.popup((_("from deck or search?")), [(_("deck")), (_("search")), (_("return"))], self._ser_reac)
elif arg == 4:
# Notification
raise NextScene("Notification")
def _ser_reac(self, arg):
if arg == 0:
# deck
tokenindex = [char["token"] for char in self.msk_.mistconfig["tokens"]].index(self.msk_.i)
if self.msk_.mistconfig["tokens"][tokenindex].get("reacdeck"):
self._ser_reac_deck(-1)
else:
self.popup((_("Please create reaction deck")), [(_("Ok"))])
elif arg == 1:
# search
self.msk_.tmp.append("searchmode")
raise NextScene("SelReaction")
def _ser_reac_deck(self,arg):
tokenindex = [char["token"] for char in self.msk_.mistconfig["tokens"]].index(self.msk_.i)
reacdeck = self.msk_.mistconfig["tokens"][tokenindex]["reacdeck"]
if arg == -1:
# initialize
reacmenu = [(reacdeck[i], lambda x=i:self._ser_reac_deck(x)) for i in range(len(reacdeck))]
reacmenu.insert(0, ("Return", lambda: None))
self._scene.add_effect(PopupMenu(self.screen,reacmenu, self.screen.width//3, 0))
else:
# Create reaction
if (noteval := self.msk_.notes[self.msk_.nowpoint]).get("renote"):
if noteval["text"] is None:
noteid = noteval["renote"]["id"]
else:
noteid = noteval["id"]
else:
noteid = noteval["id"]
is_create_seccess = self.msk_.create_reaction(noteid,f":{reacdeck[arg]}:")
if is_create_seccess:
self.popup((_('Create success! :)')), [(_("Ok"))])
else:
self.popup((_("Create fail :(")), [(_("Ok"))])
def _ser_rn(self, arg):
if arg == 0:
# Renote
if (noteval := self.msk_.notes[self.msk_.nowpoint]).get("renote"):
if noteval["text"] is None:
noteval = noteval["renote"]
username = noteval["user"]["name"]
noteid = noteval["id"]
else:
username = noteval["user"]["name"]
noteid = noteval["id"]
else:
username = noteval["user"]["name"]
noteid = noteval["id"]
if len(noteval["text"]) <= 15:
text = noteval["text"]
else:
text = noteval["text"][0:16]+"..."
self.popup((_('Renote this?\nnoteId:{}\nname:{}\ntext:{}')).format(noteid,username,text), [(_("Ok")),(_("No"))],on_close=self._ser_renote)
if arg == 1:
# Quote
if (noteval := self.msk_.notes[self.msk_.nowpoint]).get("renote"):
if noteval["text"] is None:
noteid = noteval["renote"]["id"]
else:
noteid = noteval["id"]
else:
noteid = noteval["id"]
self.msk_.crnoteconf["renoteId"] = noteid
raise NextScene("CreateNote")
def _ser_renote(self, arg):
if arg == 0:
if (noteval := self.msk_.notes[self.msk_.nowpoint]).get("renote"):
if noteval["text"] is None:
noteid = noteval["renote"]["id"]
else:
noteid = noteval["id"]
else:
noteid = noteval["id"]
createnote = self.msk_.create_renote(noteid)
if createnote is not None:
self.popup((_('Create success! :)')), [(_("Ok"))])
else:
self.popup((_("Create fail :(")), [(_("Ok"))])
def popup(self,txt,button,on_close=None):
self._scene.add_effect(PopUpDialog(self.screen,txt,button,on_close))
def _ser_quit(self,arg):
if arg == 0:
self.msk_.mistconfig_put()
raise StopApplication("UserQuit")
@staticmethod
def config():
raise NextScene("Configration")
class ConfigMenu(Frame):
def __init__(self, screen, msk):
super(ConfigMenu, self).__init__(screen,
screen.height,
screen.width,
title="ConfigMenu",
reduce_cpu=True,
can_scroll=False)
# initialize
self.msk_ = msk
self.set_theme(self.msk_.theme)
# txts create
self.txtbx = TextBox(screen.height-1,as_string=True,line_wrap=True)
self.txt = Text()
self.txtbx.value = self.msk_.cfgtxts
# buttons create
buttonnames = ((_("Return")), (_("Change TL")), (_("Change Theme")), (_("Reaction deck")),
(_("TOKEN")), (_("Instance")), (_("Current")), (_("Version")),
(_("Language")), (_("Clear")), (_("Refresh")), (_("OK")))
onclicks = (self.return_, self.poptl, self.poptheme, self.reactiondeck,
self.poptoken, self.instance_, self.current, self.version_,
self.language_, self.clear_, self.refresh_,self.ok_)
self.buttons = [Button(buttonnames[i],onclicks[i]) for i in range(len(buttonnames))]
# Layout create
layout = Layout([screen.width,2,20])
self.add_layout(layout)
self.layout = layout
# add widget
layout.add_widget(self.txtbx,0)
layout.add_widget(VerticalDivider(screen.height),1)
for i in self.buttons:
layout.add_widget(i,2)
layout.add_widget(self.txt,2)
# disables
self.txtbx.disabled = True
self.txt.disabled = True
self.buttons[-1].disabled = True
# fix
self.fix()
def version_(self):
from util import mistfigleter
self._txtbxput(mistfigleter()+"v"+str(self.msk_.version),"",(_("write by @[email protected]")),"")
def current(self):
self._txtbxput((_("Instance:{}")).format(self.msk_.instance))
if self.msk_.i is None:
self._txtbxput((_("TOKEN:None")),"")
else:
user = self.msk_.get_i()
if user is not None:
self._txtbxput((_("TOKEN:Available")),(_(' name:{}')).format(user["name"]),(_(' username:{}')).format(user["username"]),"")
else:
self._txtbxput((_("TOKEN:Available")),(_("fail to get userinfo :(")),"")
def clear_(self):
self.txtbx.value = ""
self.msk_.cfgtxts = ""
def _txtbxput(self,*arg):
for i in arg:
self.txtbx.value += str(i)+"\n"
self.msk_.cfgtxts = self.txtbx.value
def reactiondeck(self, arg = -1):
if arg == -1:
# initialize
if self.msk_.i is None:
self.popup((_("Please set TOKEN")), [(_("OK"))])
else:
self.popup((_("check deck or add deck?")), [(_("check deck")), (_("del deck")), (_("add deck")), (_("return"))], self.reactiondeck)
elif arg == 0:
# check deck
tokenindex = [char["token"] for char in self.msk_.mistconfig["tokens"]].index(self.msk_.i)
if not (nowtoken := self.msk_.mistconfig["tokens"][tokenindex]).get("reacdeck"):
self.popup((_("Please create reaction deck")), [(_("Ok"))])
else:
self._scene.add_effect(PopupMenu(self.screen,[(char, lambda: None) for char in nowtoken["reacdeck"]], self.screen.width//3, 0))
elif arg == 1:
# del deck
tokenindex = [char["token"] for char in self.msk_.mistconfig["tokens"]].index(self.msk_.i)
if not (nowtoken := self.msk_.mistconfig["tokens"][tokenindex]).get("reacdeck"):
self.popup((_("Please create reaction deck")), [(_("Ok"))])
else:
self.reactiondel(-1)
elif arg == 2:
# add deck
self.msk_.tmp.append("deck")
raise NextScene("SelReaction")
def reactiondel(self, arg):
tokenindex = [char["token"] for char in self.msk_.mistconfig["tokens"]].index(self.msk_.i)
reacdeck = self.msk_.mistconfig["tokens"][tokenindex]["reacdeck"]
if arg == -1:
# initialize
reacmenu = [(reacdeck[i], lambda x=i:self.reactiondel(x)) for i in range(len(reacdeck))]
if len(reacmenu) == 0:
self.msk_.mistconfig_put()
else:
reacmenu.insert(0, ("Return", lambda: self.msk_.mistconfig_put()))
self._scene.add_effect(PopupMenu(self.screen,reacmenu, self.screen.width//3, 0))
else:
# del reaction
reacdeck.pop(arg)
self.reactiondel(-1)
def poptl(self):
self.popup((_("Change TL")), [(_("HTL")), (_("LTL")), (_("STL")), (_("GTL"))],self._ser_tl)
def poptheme(self):
self.popup((_("Change Theme")), [(_("default")), (_("monochrome")), (_("green")), (_("bright")), (_("return"))],self._ser_theme)
def poptoken(self):
self.popup((_("How to?\ncurrent instance:{}")).format(self.msk_.instance), [(_("Create")), (_("Select")), (_("return"))],self._ser_token)
def _ser_tl(self,arg):
if arg == 0:
# HTL
if self.msk_.i is not None:
self.msk_.tl = "HTL"
self._txtbxput((_("change TL:HomeTL")))
else:
self._txtbxput((_("HTL is TOKEN required")))
elif arg == 1:
# LTL
self.msk_.tl = "LTL"
self._txtbxput((_("change TL:LocalTL")))
elif arg == 2:
# STL
if self.msk_.i is not None:
self.msk_.tl = "STL"
self._txtbxput((_("change TL:SocialTL")))
else:
self._txtbxput((_("STL is TOKEN required")))
elif arg == 3:
# GTL
self.msk_.tl = "GTL"
self._txtbxput((_("change TL:GlobalTL")))
def _ser_theme(self,arg):
if arg == 0:
self.msk_.theme = "default"
elif arg == 1:
self.msk_.theme = "monochrome"
elif arg == 2:
self.msk_.theme = "green"
elif arg == 3:
self.msk_.theme = "bright"
elif arg == 4:
return
self.msk_.mistconfig["default"]["theme"] = self.msk_.theme
self.msk_.mistconfig_put()
raise ResizeScreenError("self error")
def _ser_token(self,arg):
if arg == 0:
# Create
self.popup((_("MiAuth or write TOKEN?")).format(),["MiAuth", (_("TOKEN")), (_("return"))],self._ser_token_create)
elif arg == 1:
# Select
if len(self.msk_.mistconfig["tokens"]) == 0:
self.popup((_("Create TOKEN please.")).format(), [(_("ok"))])
else:
self._ser_token_search(-1)
def _ser_token_create(self,arg):
if arg == 0:
from util import pypcopy, webshow
# MiAuth
self.msk_.tmp.append(self.msk_.miauth_load())
url = self.msk_.tmp[-1].generate_url()
webshow(url)
space = " \n "
lens = self.screen.width//2
lines = len(url)//lens
url = space.split("\n")[0]+space.join([url[i*lens:(i+1)*lens] for i in range(lines)])
copysuccess = pypcopy(url)
self.popup((_("miauth url\n\n{}\n\n")).format(url)+((_("cliped!")) if copysuccess else ""), [(_("check ok"))],self.miauth_get)
elif arg == 1:
# TOKEN
self._txtbxput((_("write your TOKEN")))
self.msk_.tmp.append("TOKEN")
self._disables()
def _ser_token_search(self,arg):
token = self.msk_.mistconfig["tokens"]
button = [(_("L")), (_("R")), (_("Select")), (_("Delete")), (_("Set def")), (_("unset def"))]
if arg == -1:
# initialize
self.msk_.tmp.append(0)
mes = (_('<1/{}>\n\nSelect\nname:{}\ninstance:{}\ntoken:{}...').format(len(token),token[0]["name"],token[0]["instance"],token[0]["token"][0:8]))
self.popup(mes, button, self._ser_token_search)
elif arg == 0:
# L
num = self.msk_.tmp.pop()
if num == 0:
self.msk_.tmp.append(0)
headmes = (_("Too Left.\n"))
else:
num -= 1
self.msk_.tmp.append(num)
headmes = (_("Select\n"))
mes = (_('<{}/{}>\n\n{}name:{}\ninstance:{}\ntoken:{}...').format(num+1,len(token),headmes,token[num]["name"],token[num]["instance"],token[num]["token"][0:8]))
self.popup(mes, button,self._ser_token_search)
elif arg == 1:
# R
num = self.msk_.tmp.pop()
if num+1 == len(token):
self.msk_.tmp.append(num)
headmes = (_("Too Right.\n"))
else:
num += 1
self.msk_.tmp.append(num)
headmes = (_("Select\n"))
mes = (_('<{}/{}>\n\n{}name:{}\ninstance:{}\ntoken:{}...').format(num+1,len(token),headmes,token[num]["name"],token[num]["instance"],token[num]["token"][0:8]))
self.popup(mes, button,self._ser_token_search)
elif arg == 2:
# Select
num = self.msk_.tmp.pop()
userinfo = token[num]
self._txtbxput((_('select user:{}')).format(userinfo["name"]),(_('current instance:{}')).format(userinfo["instance"]),"")
self.msk_.i = userinfo["token"]
self.msk_.instance = userinfo["instance"]
is_ok = self.msk_.reload()
if is_ok:
self._txtbxput((_("connect ok!")),"")
self.refresh_(True)
else:
self.msk_.i = None
self._txtbxput((_("connect fail :(")),"")
elif arg == 3:
# Delete
num = self.msk_.tmp[-1]
headmes = (_("Delete this?\n"))
mes = (_('<{}/{}>\n\n{}name:{}\ninstance:{}\ntoken:{}...').format(num+1,len(token),headmes,token[num]["name"],token[num]["instance"],token[num]["token"][0:8]))
self.popup(mes, [(_("Yes")),(_("No"))],self._ser_token_delete)
elif arg == 4:
# Set
num = self.msk_.tmp[-1]
headmes = (_("set to default?\n"))
mes = (_('<{}/{}>\n\n{}name:{}\ninstance:{}\ntoken:{}...').format(num+1,len(token),headmes,token[num]["name"],token[num]["instance"],token[num]["token"][0:8]))
self.popup(mes,[(_("Yes")),(_("No"))],self._ser_token_default)
elif arg == 5:
# Unset
num = self.msk_.tmp[-1]
if self.msk_.mistconfig["default"]["defaulttoken"] is None:
headmes = (_("default token is none\n"))
else:
self.msk_.mistconfig["default"]["defaulttoken"] = None
self.msk_.mistconfig_put()
headmes = (_("unset success!\n"))
mes = (_('<{}/{}>\n\n{}name:{}\ninstance:{}\ntoken:{}...').format(num+1,len(token),headmes,token[num]["name"],token[num]["instance"],token[num]["token"][0:8]))
self.popup(mes, button,self._ser_token_search)
def _ser_token_default(self,arg):
num = self.msk_.tmp[-1]
if arg == 0:
self.msk_.mistconfig["default"]["defaulttoken"] = num
self.msk_.mistconfig_put()
self._ser_token_search(2)
else:
self._ser_token_search(-1)
def _ser_token_delete(self,arg):
num = self.msk_.tmp.pop()
if arg == 0:
if (deftkindex := self.msk_.mistconfig["default"]["defaulttoken"]) is not None:
if num < deftkindex:
self.msk_.mistconfig["default"]["defaulttoken"] -= 1
elif num == deftkindex:
self.msk_.mistconfig["default"]["defaulttoken"] = None
self.msk_.mistconfig["tokens"].pop(num)
self.msk_.mistconfig_put()
if len(self.msk_.mistconfig["tokens"]) == 0:
return
self._ser_token_search(-1)
def miauth_get(self,arg):
if arg == 0:
is_ok = self.msk_.miauth_check(self.msk_.tmp[-1])
if is_ok:
text = (_("MiAuth check Success!\n"))
self.msk_.reload()
userinfo = self.msk_.get_i()
if userinfo is not None:
name = userinfo["name"]
text += (_('Hello {}')).format(name)
else:
text += (_("fail to get userinfo :("))
name = (_("fail to get"))
userdict = {"name":name,"instance":self.msk_.instance,"token":self.msk_.i}
self.msk_.mistconfig["tokens"].append(userdict)
self.msk_.mistconfig_put()
self.msk_.notes = []
self.msk_.reacdb = None
self.popup(text, [(_("Ok"))], self.refresh_)
self.msk_.tmp.pop()
else:
text = (_("MiAuth check Fail :(\ntry again?"))
self.popup(text, [(_("again")), (_("return"))], self.miauth_get)
else:
self.msk_.tmp.pop()
def instance_(self, select=-1):
if select == -1:
if self.msk_.i is not None:
self.popup((_("TOKEN detect!\nchange instance will delete TOKEN.\nOk?")), [(_("Ok")),(_("No"))],on_close=self.instance_)
else:
self.msk_.tmp.append("INSTANCE")
self._txtbxput((_("input instance such as 'misskey.io' 'misskey.backspace.fm'")), (_("current instance:{}")).format(self.msk_.instance),"")
self._disables()
elif select == 0:
self.msk_.i = None
self.instance_()
def ok_(self):
ok_value = self.msk_.tmp.pop()
if ok_value == "TOKEN":
self.msk_.i = self.txt.value
is_ok = self.msk_.reload()
if is_ok:
self._txtbxput((_("TOKEN check OK :)")))
i = self.msk_.get_i()
if i is None:
name = (_("get fail"))
self._txtbxput((_("fail to get your info :(")))
else:
name = i["name"]
self._txtbxput((_("Hello {}!")).format(name))
self.msk_.mistconfig["tokens"].append({"name":name, "instance":self.msk_.instance, "token":self.msk_.i})
self.msk_.mistconfig_put()
self.refresh_(True)
else:
self.msk_.i = ""
self._txtbxput((_("TOKEN check fail :(")))
elif ok_value == "INSTANCE":
before_instance = self.msk_.instance
self.msk_.instance = self.txt.value
is_ok = self.msk_.reload()
if is_ok:
self._txtbxput((_("instance connected! :)")))
is_ok = self.msk_.get_instance_meta()
if is_ok:
icon_bytes = self.msk_.get_instance_icon()
if icon_bytes == "Error":
self._txtbxput((_("error occured while get icon :(")))
else:
icon = ImageFile(icon_bytes,self.screen.height//2)
self._txtbxput(icon)
else:
self._txtbxput((_("error occured while get meta :(")))
else:
self.msk_.instance = before_instance
self._txtbxput((_("instance connect fail :(")))
self._txtbxput((_("current instance:{}")).format(self.msk_.instance),"")
self.refresh_(True)
self._disables(True)
def _disables(self,rev=False):
if rev:
self.txt.value = ""
self.txt.disabled = rev
for i in self.buttons:
i.disabled = (not rev)
self.buttons[-1].disabled = rev
if rev:
self.switch_focus(self.layout,2,0)
else:
self.switch_focus(self.layout,2,len(self.buttons))
def refresh_(self, notedel=False):
if notedel:
self.msk_.reacdb = None
self.msk_.notes = []
raise ResizeScreenError("self error", self._scene)
def language_(self,arg=-1):
import glob
import pathlib
langlst = glob.glob("./locale/*/LC_MESSAGES")
if len(langlst) == 0:
self.popup(_("there is no translation files."),[_("Ok")])
else:
selects = [pathlib.PurePath(lang).parts[1] for lang in langlst]
if arg == -1:
selects.append(_("reset"))
selects.append(_("return"))
self.popup(_("select language"), selects, self.language_)
else:
if arg == len(langlst)+1:
return
else:
if arg == len(langlst):
self.msk_.lang = None
else:
self.msk_.lang = selects[arg]
self.msk_.init_translation()
self.msk_.mistconfig["default"]["lang"] = self.msk_.lang
self.msk_.mistconfig_put()
self.refresh_()
def popup(self,txt,button,on_close=None):
self._scene.add_effect(PopUpDialog(self.screen,txt,button,on_close))
@staticmethod
def return_():
raise NextScene("Main")
class CreateNote(Frame):
def __init__(self, screen, msk):
super(CreateNote, self).__init__(screen,
screen.height,
screen.width,
title="CreateNote",
reduce_cpu=True,
can_scroll=False)
# initialize
self.msk_ = msk
self.set_theme(self.msk_.theme)
# txtbox create
self.txtbx = TextBox(screen.height-3, as_string=True, line_wrap=True,on_change=self.reminder)
self.txtbx.value = self.msk_.crnotetxts
# buttons create
buttonnames = ((_("Note Create")), (_("hug punch")), (_("return")), (_("MoreConf")))
on_click = (self.popcreatenote, self.hug_punch, self.return_, self.conf_)
self.buttons = [Button(buttonnames[i],on_click[i]) for i in range(len(buttonnames))]
# Layout create
layout = Layout([100])
layout2 = Layout([1 for _ in range(len(self.buttons))])
self.add_layout(layout)
self.add_layout(layout2)
# add widget
layout.add_widget(self.txtbx)
for i in range(len(self.buttons)):
layout2.add_widget(self.buttons[i],i)
# fix
self.fix()
def reminder(self):
self.msk_.crnotetxts = self.txtbx.value
def hug_punch(self):
from random import randint
hugpunchs = ["(Δ・x・Δ)","v('ω')v","(=^・・^=)","✌️(´・_・`)✌️",
"( ‘ω’ و(و “","ԅ( ˘ω˘ ԅ)モミモミ","🐡( '-' 🐡 )フグパンチ!!!!","(。>﹏<。)"]
self.txtbx.value += hugpunchs[randint(0,len(hugpunchs)-1)]
def popcreatenote(self):
self._scene.add_effect(PopUpDialog(self.screen,(_("Are you sure about that?")), [(_("Sure")), (_("No"))],self._ser_createnote))
def _ser_createnote(self,arg):
if arg == 0:
return_ = self.msk_.create_note(self.txtbx.value)
if return_ is not None:
self._scene.add_effect(PopUpDialog(self.screen,(_("Create note success :)")), [(_("Ok"))],on_close=self.return_))
self.msk_.crnotetxts = (_("Tab to change widget"))
self.txtbx.value = self.msk_.crnotetxts
self.msk_.crnoteconf = self.msk_.constcrnoteconf.copy()
else:
self._scene.add_effect(PopUpDialog(self.screen,(_("Create note fail :(")), [(_("Ok"))]))
def _ser_ret(self,arg):
if arg == 0:
self.msk_.crnoteconf["renoteId"] = None
self.msk_.crnoteconf["replyId"] = None
self.return_()