-
Notifications
You must be signed in to change notification settings - Fork 1
/
meower95.py
executable file
·968 lines (871 loc) · 41.3 KB
/
meower95.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
import urllib.request, json, os, time, random, base64, pyglet
from tkinter import *
from PIL import ImageTk,Image
from tkinter import ttk
from os.path import exists
import subprocess as sp
from sys import executable
def log(*args,sep=" ",safe=False):
if not exists("meower95.log"):
lf = open("meower95.log","w")
lf.write('''!!! WARNING !!!
Please do not share this file to anybody you don't know or trust.
This file can contain valuable information like your Meower
account passwords, tokens and etc. that can be used for malicious
intent by databrokers and trouble makers.
If you still need help online, share the contents of the file
meower95.safelog, as it contains only the important problems you
might face while using the program.
Thank you!
-barney86
;3
''')
lf.close()
lf = open("meower95.log","a")
t = time.gmtime()
logput = f"{t[0]}.{t[1]}.{t[2]} {t[3]}:{t[4]}:{t[5]}: " + sep.join(args)
lf.write(logput + "\n")
lf.close()
if safe:
lf = open("meower95.safelog","a" if exists("meower95.safelog") else "w")
lf.write(logput + "\n")
lf.close()
def refresh_conf():
cf = open("meower95.conf","w")
json.dump(cfg,cf)
cf.close()
welcome_messages = ("Select a server by clicking it's title on the list below:",
"Just click a name below to continue.",
"Point your cursor to a server below and click.",
"Just do it.",
"Dude...",
"Stop trying! There's no easter egg, nor whatever.",
"Okay let me explain:",
"You use your mouse pointer (the thing you click with),",
"And point it directly to the server you need to chat.",
"Click, and then click me again.",
"No, you do the stuff I said first, then you click.",
"Okay, you're just annoying, stop trying to be funny.",
"Next time you click I'll crash the program.")
welcome_count = -1
intro_part = 0
server = user = None
useragent = ""
for i in range(0,8):
useragent += random.choice("qwertyuiopasdfghjklzxcvbnm1234567890")
def refresh_intro():
users.delete(0,END)
servers.delete(0,END)
for i in (welcome,servers,user_title,users):
i.place_forget()
welcome.place_forget()
bback.configure(state=DISABLED if intro_part == 0 else NORMAL)
bnext.configure(text="Chat!" if intro_part else "Next >")
if intro_part > 1:
intro.destroy()
elif intro_part:
if "logins" in cfg["servers"][server]:
for i in list(cfg["servers"][server]["logins"].keys()):
users.insert(END,i)
else:
cfg["servers"][server]["logins"] = {}
refresh_conf()
user_title.place(x=130,y=5)
users.place(x=130,y=30,width=310,height=135)
else:
if "servers" in cfg:
for i in list(cfg["servers"].keys()):
servers.insert(END,i)
else:
cfg["servers"] = {}
refresh_conf()
welcome.place(x=130,y=5)
servers.place(x=130,y=30,width=310,height=135)
def next():
global welcome_count,server,user,intro_part
if intro_part: #replace with case, no documentation offline yk
try:
if users.selection_get() in cfg["servers"][server]["logins"].keys():
user = users.selection_get()
else:
return
except TclError as e:
return
else:
try:
if servers.selection_get() in cfg["servers"].keys():
server = servers.selection_get()
else:
return
except TclError:
welcome_count += 1
try: welcome.configure(text=welcome_messages[welcome_count])
except IndexError: intro.destroy()
return
intro_part += 1
refresh_intro()
def register(username,password):
req = urllib.request.Request(cfg["servers"][server]["http"] + "auth/register", headers={'User-Agent': useragent})
req.add_header('Content-Type', 'application/json; charset=utf-8')
jsondata = json.dumps({"username":username,"password":password}).encode('utf-8')
req.add_header('Content-Length', len(jsondata))
return urllib.request.urlopen(req, jsondata)
def back():
global intro_part
if intro_part > 0: intro_part -= 1
refresh_intro()
def add():
global cfg
def save_cfg():
global cfg
if intro_part: cfg["servers"][server]["logins"][entry1.get()] = entry2.get()
else:
cfg["servers"][entry1.get()] = {}
cfg["servers"][entry1.get()]["http"] = entry2.get()
if cfg["servers"][entry1.get()]["http"][len(cfg["servers"][entry1.get()]["http"])] != "/":
cfg["servers"][entry1.get()]["http"] += "/"
cfg["servers"][entry1.get()]["websocket"] = entry3.get()
cfg["servers"][entry1.get()]["logins"] = {}
refresh_conf()
winadd.destroy()
refresh_intro()
winadd = Tk()
winadd.title("Meower - Add " + ("user account" if intro_part else "server"))
winadd.geometry("280x85" if intro_part else "280x105")
Label(winadd,text="Username:" if intro_part else "Name:", font=("Helvetica", 8)).place(x=110,y=10,anchor="e")
entry1 = Entry(winadd,font=("Helvetica", 8))
entry1.place(x=110,y=10,width=165,anchor="w")
Label(winadd,text="Password:" if intro_part else "HTTP(S) server:", font=("Helvetica", 8)).place(x=110,y=35,anchor="e")
entry2 = Entry(winadd,font=("Helvetica", 8))
if intro_part:
entry2.configure(show="•")
reg = Button(winadd,text="Register account",font=("Helvetica", 8),state=DISABLED,command=lambda: register(entry1.get(),entry2.get()) )
reg.place(x=140,y=85,anchor="s")
else:
Label(winadd,text="WS(S) server:", font=("Helvetica", 8)).place(x=110,y=60,anchor="e")
entry3 = Entry(winadd,font=("Helvetica", 8))
entry3.place(x=110,y=60,width=165,anchor="w")
entry2.place(x=110,y=35,width=165,anchor="w")
cancel = Button(winadd,text="Cancel",font=("Helvetica", 8),command=winadd.destroy)
cancel.place(x=5,y=85 if intro_part else 105,anchor="sw")
save = Button(winadd,text="OK",font=("Helvetica", 8),command=save_cfg)
save.place(x=275,y=85 if intro_part else 105,anchor="se")
try:
while intro.wm_state() == "normal":
winadd.update()
except TclError:
return
refresh_intro()
def remove():
if intro_part: del cfg["servers"][server]["logins"][users.selection_get()]
else: del cfg["servers"][servers.selection_get()]
cf = open("meower95.conf","w")
json.dump(cfg,cf)
cf.close()
log("Removed",servers.selection_get(),"from the", "user" if intro_part else "server", "list.")
refresh_intro()
empty_conf = True
if not exists("meower95.conf"):
empty_conf = False
cf = open("meower95.conf","w")
cf.close()
cf = open("meower95.conf","r")
try:
cfg = json.load(cf)
except json.decoder.JSONDecodeError as error:
if empty_conf:
jsonwin = Tk()
jsonwin.title("Meower95 - Error")
jsonwin.geometry("400x110")
jsonwin.resizable(0,0)
warnicon = PhotoImage(file=os.path.realpath('assets/warning.png'))
Label(jsonwin, image=warnicon).place(x=5,y=10)
Label(text='''Your configuration file (meower95.conf) might be corrupted.
Your old JSON file is saved to meower95.conf.bak,
and your current configuration will be reset.
sorry :(''', justify="left", font=("Helvetica", 10)).place(x=50,y=10)
Button(jsonwin,text="Continue",command=jsonwin.destroy,font=("Helvetica", 10)).place(x=395,y=105,anchor="se")
jsonwin.mainloop()
cfb = open("meower95.conf.bak","w")
cfb.write(cf.read())
cfb.close()
cfg = {}
refresh_conf()
else: cfg = {}
cf.close()
intro = Tk()
intro.geometry("450x210")
intro.title("Meower95 - Quick login")
intro.resizable(0,0)
logo = PhotoImage(file=os.path.realpath('assets/meower16.png'))
intro.wm_iconphoto(False, logo)
welcome = Label(intro, text="Welcome to Meower95! Select your server:", font=("Helvetica", 10))
servers = Listbox(intro, font=("Helvetica", 8))
user_title = Label(intro, text="Select your user account:", font=("Helvetica", 10))
users = Listbox(intro, font=("Helvetica", 8))
bback = Button(intro, text="< Back",command=back,font=("Helvetica", 8),state=DISABLED)
bnext = Button(intro,command=next,font=("Helvetica", 8))
badd = Button(intro, text="Add...",command=add,font=("Helvetica", 8))
bdel = Button(intro, text="Remove",command=remove,font=("Helvetica", 8))
sep = ttk.Separator(intro,orient='horizontal')
introsplash = PhotoImage(file=os.path.realpath('assets/intro.png'))
bback.place(x=130,y=205,anchor="sw")
bnext.place(x=440,y=205,anchor="se")
badd.place(x=280,y=205,anchor="se")
bdel.place(x=280,y=205,anchor="sw")
sep.place(x=135,y=172,width=300,anchor="w")
introcanvas = Canvas(width=120,
height=196,
relief="flat")
introcanvas.create_image(0, 0, image=introsplash, anchor="nw")
introcanvas.place(x=3,y=5)
refresh_intro()
try:
intro.mainloop()
except TclError:
pass
if not server or not user: exit()
def_settings = {"emoji":True,"markdown":True,"avatars":True,"msgdel":True,"base64":False,"smartdel":False}
if not "settings" in cfg:
cfg["settings"] = {}
for i in def_settings:
if i not in cfg["settings"]:
cfg["settings"][i] = def_settings[i]
cfg["lastsession"] = {}
cfg["lastsession"]["server"] = server
cfg["lastsession"]["user"] = user
refresh_conf()
window = Tk()
window.resizable(0,0)
window.title("Meower95")
logo = PhotoImage(file=os.path.realpath('assets/meower16.png'))
window.wm_iconphoto(False, logo)
print("Backend open.")
proc = sp.Popen([executable,'backend.py'])
def sendhttp(link, content):
log("Sending", str(content), "to", cfg["servers"][server]["http"] + link)
req = urllib.request.Request(cfg["servers"][server]["http"] + link, headers={'User-Agent': useragent})
req.add_header('Content-Type', 'application/json; charset=utf-8')
req.add_header('Username', user)
req.add_header('Token', ws_data["userdata"]["payload"]["token"])
jsondata = json.dumps(content).encode('utf-8')
req.add_header('Content-Length', len(jsondata))
return urllib.request.urlopen(req, jsondata)
def sendanon(content):
req = urllib.request.Request("https://sendme.josueart40.workers.dev", headers={'User-Agent': useragent})
req.add_header('Content-Type', 'application/json; charset=utf-8')
jsondata = json.dumps({"user":"meowy98","content":content}).encode('utf-8')
return urllib.request.urlopen(req, jsondata)
def react(id,emoji):
log("Reacting with", emoji, "to", id, safe = True)
req = urllib.request.Request(cfg["servers"][server]["http"] + "/posts/" + id + "/reactions/" + urllib.parse.quote(emoji), headers={'User-Agent': useragent}, method='POST')
req.add_header('Username', user)
req.add_header('Token', ws_data["userdata"]["payload"]["token"])
return urllib.request.urlopen(req)
def report(id,reason,comment):
log("Reacting with", emoji, "to", id, safe = True)
req = urllib.request.Request(cfg["servers"][server]["http"] + "/posts/" + id + "/reactions/" + urllib.parse.quote(emoji), headers={'User-Agent': useragent}, method='POST')
req.add_header('Username', user)
req.add_header('Token', ws_data["userdata"]["payload"]["token"])
return urllib.request.urlopen(req)
def readhttp(link):
log("Reading", cfg["servers"][server]["http"] + link, safe = True)
req = urllib.request.Request(cfg["servers"][server]["http"] + link, headers={'User-Agent': useragent})
req.add_header('Username', user)
try:
req.add_header('Token', ws_data["userdata"]["payload"]["token"])
except KeyError:
pass
url = urllib.request.urlopen(req)
data = json.load(url)
return data
def edit_msg(id="",content=""):
req = urllib.request.Request(cfg["servers"][server]["http"] + "posts?id=" + id, headers={'User-Agent': useragent}, method='PATCH')
req.add_header('Content-Type', 'application/json; charset=utf-8')
req.add_header('Username', user)
req.add_header('Token', ws_data["userdata"]["payload"]["token"])
jsondata = json.dumps({"content": content,"username":user,"pswd":cfg["servers"][server]["logins"][user]}).encode('utf-8')
req.add_header('Content-Length', len(jsondata))
return urllib.request.urlopen(req, jsondata)
def del_msg(id=""):
if cfg["settings"]["smartdel"]:
edit_msg(id,"Deleted.")
req = urllib.request.Request(cfg["servers"][server]["http"] + "posts?id=" + id, headers={'User-Agent': useragent}, method='DELETE')
req.add_header('Username', user)
req.add_header('Token', ws_data["userdata"]["payload"]["token"])
return urllib.request.urlopen(req)
def send_msg(event):
global last_message,replies
if entry.get() != "":
text = entry.get()
if cfg["settings"]["base64"]:
text = "ec[Meower95]:"+str(base64.b64encode(bytes(text,"utf8")),"utf8")
entry.delete(0,END)
text_json = json.load(sendhttp(channel,{"reply_to":replies,"content": text,"username":user,"pswd":cfg["servers"][server]["logins"][user]}))
last_message = text_json
replies = []
refresh_view()
def get_users(user):
url = urllib.request.urlopen(cfg["servers"][server]["http"] + "users/" + user)
data = json.load(url)
return data
emojis = {}
ef = open("assets/emojis/emojis.conf")
emojiconf = json.load(ef)
ef.close()
for e in emojiconf.keys():
emojis[e] = PhotoImage(file=os.path.realpath(f'assets/emojis/{emojiconf[e]}'))
def settings():
global ivars
def setvar(variable,widget):
cfg["settings"][variable] = widget.instate(['selected'])
refresh_conf()
settings = Tk()
settings.title("Meower95 - Settings")
settings.geometry("480x320")
settings.resizable(0,0)
sstyle = ttk.Style(settings)
sstyle.configure("TNotebook",font=("Helvetica",10))
notebook = ttk.Notebook(settings)
notebook.place(x=5,y=5,width=470,height=312)
misc = Frame(notebook)
sounds = Frame(notebook)
hacks = Frame(notebook)
notebook.add(misc,text="Misc.")
notebook.add(sounds,text="Sound")
notebook.add(hacks,text="Hacks")
# Misc
emoji = ttk.Checkbutton(misc,text="Convert text emojis into pictures")
emoji.configure(command=lambda: setvar("emoji",emoji))
emoji.place(x=30,y=20)
markdown = ttk.Checkbutton(misc,text="Markdown support",state=DISABLED)
markdown.configure(command=lambda: setvar("markdown",markdown))
markdown.place(x=30,y=50)
avatars = ttk.Checkbutton(misc,text="Load avatars")
avatars.configure(command=lambda: setvar("avatars",avatars))
avatars.place(x=30,y=80)
msgdel = ttk.Checkbutton(hacks,text="Don't hide messages on deletion")
msgdel.configure(command=lambda: setvar("msgdel",msgdel))
msgdel.place(x=30,y=20)
smartdel = ttk.Checkbutton(hacks,text="Autoedit my messages before deletion to be unreadable")
smartdel.configure(command=lambda: setvar("msgdel",msgdel))
smartdel.place(x=30,y=50)
base64 = ttk.Checkbutton(hacks,text="Base64 encryption")
base64.configure(command=lambda: setvar("base64",base64))
base64.place(x=30,y=80)
for i in cfg["settings"].keys():
try:
eval(i).state(['!alternate'])
if cfg["settings"][i]: eval(i).state(['selected'])
except AttributeError:
pass
while True:
settings.update()
try:
if not settings.winfo_exists(): break
except TclError:
break
def edit_gui(post):
if type(post) == dict:
def finish_editing():
text = edittext.get(0.0,END).removesuffix("\n")
if cfg["settings"]["base64"]:
text = "ec[Meower95]:"+str(base64.b64encode(bytes(text,"utf8")),"utf8")
edit_msg(post["_id"],text)
winedit.destroy()
winedit = Tk()
winedit.geometry("480x240")
winedit.resizable(0,0)
edittext = Text(winedit)
edittext.place(x=5,y=5,width=470,height=190)
Button(winedit,text="Cancel",command=winedit.destroy).place(x=5,y=235,anchor="sw")
Button(winedit,text="Edit!",command=finish_editing).place(x=475,y=235,anchor="se")
chan = channel_by_id(post["_id"])
text = home[chan][index_by_id(post["_id"],chan)]["p"]
try:
if text[0:3] == "ec[":
text = str(base64.b64decode(text.split("]:")[len(text.split("]:"))-1]),"utf8")
if text[0:3] == "rr:":
text = str(base64.b64decode(text[3:len(text)-1]),"utf8")
except IndexError:
pass
except UnicodeError:
pass
except base64.binascii.Error:
pass
edittext.insert(0.0,text)
while True:
winedit.update()
try:
if not winedit.winfo_exists(): break
except TclError:
break
def process_text(text):
result = []
words = []
for word in emojis.keys():
last = 0
for i in range(0,text.count(word)):
words.append([text.index(word,last), word])
last = text.index(word,last) + 1
try:
result.append(text[0:words[0][0]])
except IndexError:
return [text]
for i in range(0,len(words)):
result.append(words[i][1])
try:
result.append(text[words[i][0]+len(words[i][1]):words[i][0]])
except IndexError:
pass
result.append(text[words[i][0]+len(words[i][1]):len(text)])
return result
home = {}
last_message = None
imagecache = {}
def mix_hex(a,b):
a = a.removeprefix("#")
b = b.removeprefix("#")
result = "#"
for i in range(0,6,2):
try:
result += hex(round((int(a[i:i+1],16) + int(b[i:i+1],16)) / 2)).removeprefix("0x")
except ValueError:
print("Error mixing colors",a,"and",b)
return "#0090f0"
return result
def load_image(id,name):
filename = os.path.realpath("assets/cache/" + id + "/" + name)
if not exists(filename):
if not exists("assets/cache/"):
os.mkdir("assets/cache/")
os.mkdir("assets/cache/" + id)
url = urllib.request.Request("https://uploads.meower.org/attachments/"+id+"/"+name, headers={'User-Agent': 'Meower95',"Username":user})
try:
img = urllib.request.urlopen(url)
except urllib.error.HTTPError:
return os.path.realpath("assets/warning.png")
else:
image = open(filename,"wb")
image.write(img.read())
image.close()
return filename
def add_reply(id):
if len(replies) < 10 and entry["state"] == NORMAL:
replies.append(id)
refresh_view()
def insert_home():
text = ""
messages.tag_remove(0.0,END)
messages.configure(state=NORMAL)
messages.delete(0.0,END)
if channel not in home or home[channel] == []:
if channel == "livechat":
home[channel] = []
messages.insert(END,"Livechat is waiting for you! ;3",("nonet"))
messages.tag_configure("nonet",foreground="gray")
return
try:
home[channel] = readhttp(channel)
except urllib.error.URLError as e:
messages.insert(END,"Cannot connect to the server:\n",("nonet"))
messages.insert(END,str(e)+"\n",("nonet"))
messages.insert(END," ⚫ Check if you have a working network connection and Meower95 has access to it.\n",("nonet"))
messages.insert(END,f" ⚫ Check if the server you're trying to connect to ({server}) is up.\n",("nonet"))
messages.insert(END,f" ⚫ Have you possibly made a typo while entering the links for {server}?\n",("nonet"))
messages.insert(END,f" ⚫ You might have been IP blocked from {server}. You can still recieve postss realtime, but features are limited.",("nonet"))
messages.tag_configure("nonet",foreground="gray")
return
home[channel].reverse()
for i in range(0,len(home[channel])):
try:
if home[channel][i]["p"][0:3] == "ec[":
home[channel][i]["p"] = str(base64.b64decode(home[channel][i]["p"].split("]:")[len(home[channel][i]["p"].split("]:"))-1]),"utf8")
if home[channel][i]["p"][0:3] == "rr:":
home[channel][i]["p"] = str(base64.b64decode(home[channel][i]["p"][3:len(home[channel][i]["p"])]),"utf8")
except IndexError:
pass
except UnicodeError:
pass
except base64.binascii.Error:
pass
home[channel][i]["u"] = home[channel][i]["u"].replace("\n","")
messages.mark_set(str(i),END)
if home[channel][i]["u"] in ["Discord"]: #known bridges, maybe add phone support later (if it even works today)
color = "#800080"
username = home[channel][i]["p"].split(": ")[0]
text = ": ".join(home[channel][i]["p"].split(": ")[1:len(home[channel][i]["p"].split(":"))]).encode('utf-16', 'surrogatepass').decode('utf-16')
else:
color = "#000080" if home[channel][i]["author"]["avatar_color"] == "000000" else mix_hex(home[channel][i]["author"]["avatar_color"],"000080")
username = home[channel][i]["u"]
text = home[channel][i]["p"].encode('utf-16', 'surrogatepass').decode('utf-16')
messages.insert(END,username,"u_"+home[channel][i]["u"])
if home[channel][i]["isDeleted"]:
messages.insert(END," (deleted)",("p_"+home[channel][i]["_id"],"smallfont"))
elif "edited_at" in home[channel][i]:
messages.insert(END," (edited)",("p_"+home[channel][i]["_id"],"smallfont"))
messages.insert(END,": ",("p_"+home[channel][i]["_id"]))
messages.tag_configure("u_"+home[channel][i]["u"],foreground=color,font=("Helvetica",12))
messages.tag_bind("u_"+home[channel][i]["u"],"<Button-1>", lambda event, u=user:
view_user(u))
text = process_text(text.removesuffix("@"))
for t in text:
if t in emojis.keys():
messages.image_create(END, image = emojis[t])
else:
for w in t.split(" "):
if w != "":
if w[0] == "@":
messages.insert(END,w,("u_"+w.removeprefix("@")))
messages.tag_configure("u_"+w.removeprefix("@"),
foreground="#000080",font=("Helvetica",12))
messages.tag_bind("u_"+w.removeprefix("@"),"<Button-1>",
lambda event, u=w.removeprefix("@"): view_user(u))
else:
messages.insert(END,w,("p_"+home[channel][i]["_id"]))
messages.insert(END," ",("p_"+home[channel][i]["_id"]))
if username == user:
messages.tag_bind("p_"+home[channel][i]["_id"],"<Button-1>",
lambda event, t=home[channel][i]: edit_gui(t))
messages.tag_bind("p_"+home[channel][i]["_id"],"<Button-3>",
lambda event, t=home[channel][i]["_id"]: del_msg(t))
else:
messages.tag_bind("p_"+home[channel][i]["_id"],"<Button-1>",
lambda event, d=home[channel][i]["_id"]: add_reply(d))
if home[channel][i]["isDeleted"]:
messages.tag_configure("p_"+home[channel][i]["_id"],foreground="gray")
for a in home[channel][i]["attachments"]:
if a["mime"][0:5] == "image" and a["size"] < 2500000:
filename = os.path.realpath("assets/cache/" + a["id"] + "/" + a["filename"])
try:
try:
if not a["id"] in imagecache.keys():
imagecache[a["id"]] = Image.open(filename if exists(filename) else load_image(a["id"],a["filename"]))
if imagecache[a["id"]].width > imagecache[a["id"]].height and imagecache[a["id"]].width > 240:
imagecache[a["id"]] = imagecache[a["id"]].resize((240,int(240*imagecache[a["id"]].height/imagecache[a["id"]].width)),Image.LANCZOS)
elif imagecache[a["id"]].height > 240:
imagecache[a["id"]] = imagecache[a["id"]].resize((int(240*imagecache[a["id"]].width/imagecache[a["id"]].height),240),Image.LANCZOS)
imagecache[a["id"]] = ImageTk.PhotoImage(imagecache[a["id"]])
messages.insert(END,"\n")
messages.image_create(END, name=a["id"], image=imagecache[a["id"]])
messages.insert(END,"\n")
except AttributeError:
print("Embed AttributeError")
except KeyError:
pass
except TclError:
pass
messages.insert(END,"\n")
messages.yview(END)
messages.tag_configure("smallfont",font=("Helvetica",10))
messages.configure(state=DISABLED)
pfps = {}
for p in os.listdir("assets/pfps/"):
pfps[os.path.splitext(p)[0]] = PhotoImage(file=os.path.realpath(f'assets/pfps/{p}'))
usrsound = {}
last_sound_user = 0
def refresh_users():
global pfpcache
for i in userlist.get_children():
userlist.delete(i)
try:
ulist_api = readhttp("ulist")["autoget"]
except urllib.error.HTTPError:
for u in ws_data["ulist"].split(";"):
if u in pfps:
userlist.insert("",END,text=" "+u,image=pfps[u])
else:
userlist.insert("",END,text=" "+u)
return
print(ulist_api)
for u in ulist_api:
if cfg["settings"]["avatars"]:
if u["_id"] in pfps:
userlist.insert("",END,text=" "+u["_id"],image=pfps[u["_id"]])
else:
if str(u['pfp_data']) in pfps:
userlist.insert("",END,text=" "+u["_id"],image=pfps[str(u['pfp_data'])])
else:
userlist.insert("",END,text=" "+u["_id"])
else:
userlist.insert("",END,text=" "+u["_id"])
window.update()
replies = []
def refresh_view():
global cfg
for i in (channels,messages,userlist,reply_canvas):
i.place_forget()
if not "view" in cfg:
cfg["view"] = 7
refresh_conf()
show = bin(cfg["view"]).removeprefix("0b")
show = "0" * (3 - len(show)) + show
show = [show]
for i in show[0]:
show.append(bool(int(i)))
del show[0]
height = 320
if show[1]: height += 40 + len(replies) * 20
window.geometry(str(472 + (show[0] + show[2]) * 128) + "x" + str(height))
messages.place(x=128 if show[0] else 0,y=0,height=320,width=460)
scrollbar.place(x=588 if show[0] else 460,y=0,height=height,width=12)
reply_canvas.delete("all")
reply_canvas.place(x=133 if show[0] else 5,y=360)
for y in range(0,len(replies)):
ch = channel_by_id(replies[y])
msg = home[ch][index_by_id(replies[y],ch)]
y=y*20
reply_canvas.create_rectangle(0, y, 450, y+16, fill=mix_hex(window["background"],"#0090F0" if msg["author"]["avatar_color"] == "000000" else "#" + msg["author"]["avatar_color"]),width=0)
reply_canvas.create_rectangle(0, y, 3, y+16, fill="#0090F0" if msg["author"]["avatar_color"] == "000000" else "#" + msg["author"]["avatar_color"],width=0)
reply_canvas.create_text(5,y+3,text="@" + msg["u"] + ": " + msg["p"],anchor="nw",font=("Helvetica",10))
window.update()
if show[0]: channels.place(x=0,y=0,width=128,height=height)
if show[1]: entry.place(x=148 if show[0] else 20,y=340,width=420,anchor="w")
if show[2]: userlist.place(x=600 if show[0] else 472,y=0,width=128,height=height)
def toggle_view(index):
show = bin(cfg["view"]).removeprefix("0b")
show = "0" * (3 - len(show)) + show
show = [show]
for i in show[0]:
show.append(bool(int(i)))
del show[0]
show[index] = not show[index]
for i in range(0,len(show)):
show[i] = str(int(show[i]))
cfg["view"] = int("".join(show),2)
refresh_conf()
refresh_view()
channel = "home"
channellist={}
def change_channel(event):
global channel
if channels.selection_get() in ("Home","Livechat"):
channel = channels.selection_get().lower()
else:
channel_id = channellist[channels.selection_get()]
channel = "posts/" + channel_id
insert_home()
def index_by_id(id,chan):
for m in range(0,len(home[chan])):
if home[chan][m]["_id"] == id:
return m
raise ValueError("id not found")
def channel_by_id(id):
for c in home.keys():
for m in home[c]:
if m["_id"] == id:
return c
raise ValueError("id not found")
def timestring(timestamp):
return str(timestamp[2]) + (('st','nd')[timestamp[2]-1] if timestamp[2] < 2 else 'th') + " of " + ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')[timestamp[1]-1] + " " + str(timestamp[0]) + " " + str(timestamp[3]) + ":" + str(timestamp[4])
def view_user(name):
try:
if type(name) == str:
accountinfo = readhttp("users/"+name)
elif type(name.widget) == ttk.Treeview:
accountinfo = readhttp("users/"+userlist.item(userlist.focus())["text"].removeprefix(" "))
print(accountinfo)
try:
lastseen = time.gmtime(accountinfo["last_seen"])
except Exception as e:
print(e)
lastseen = 0
userwin = Toplevel()
userwin.title("Meower95 - "+accountinfo["_id"])
userwin.geometry("240x180")
userwin.resizable(0,0)
if exists(f'assets/pfps/{accountinfo["pfp_data"]}.png') or exists(f'assets/pfps/{accountinfo["_id"]}.png'):
avatar = PhotoImage(file=os.path.realpath(f'assets/pfps/{accountinfo["_id"]}.png' if exists(f'assets/pfps/{accountinfo["_id"]}.png') else f'assets/pfps/{accountinfo["pfp_data"]}.png'))
Label(userwin,image=avatar).place(x=8,y=8)
userlabel = Label(userwin,text=accountinfo["_id"],font=("Helvetica",14))
userlabel.place(x=28,y=16,anchor="w")
quote = Label(userwin,text=accountinfo["quote"] if accountinfo["quote"] else "No quote",wraplength=100,justify=LEFT,font=("Helvetica",8))
quote.place(x=8,y=32,width=100,height=120)
ttk.Separator(userwin,orient="vertical").place(x=120,y=32,height=120,anchor="n")
chatswith = Listbox(userwin,font=("Helvetica",10))
chatswith.place(x=128,y=32,width=105,height=120)
onlinep = PhotoImage(file = os.path.realpath("assets/online.png" if accountinfo["_id"] in ws_data["ulist"].split(";") else "assets/offline.png"))
onlinei = Label(userwin,image=onlinep).place(x=8,y=166,anchor="w")
online = Label(userwin,text="Online" if accountinfo["_id"] in ws_data["ulist"].split(";") else "Last seen on " + timestring(lastseen),font=("Helvetica",8))
online.place(x=20,y=166,anchor="w")
p_addtochat = PhotoImage(file = os.path.realpath("assets/addtochat.png"))
p_dm = PhotoImage(file = os.path.realpath("assets/dm.png"))
Button(userwin,image=p_addtochat).place(x=213,y=166,width=20,height=20,anchor="e")
Button(userwin,image=p_dm).place(x=233,y=166,width=20,height=20,anchor="e")
for chat in readhttp("chats")["autoget"]:
if not chat["type"] and accountinfo["_id"] in chat["members"]:
chatswith.insert(END,chat["nickname"])
while True:
userwin.update()
try:
if not userwin.winfo_exists(): break
except TclError:
break
except urllib.error.HTTPError:
pass
log("setting up widgets...",safe=True)
style = ttk.Style()
style.configure('.', font=('Helvetica', 8))
menubar = Menu(window,relief=FLAT, font=('Helvetica', 8))
mainmenu = Menu(menubar, tearoff=0, font=('Helvetica', 8))
mainmenu.add_command(label="Settings", command=settings, font=('Helvetica', 8))
mainmenu.add_separator()
mainmenu.add_command(label="Exit", command=window.destroy, font=('Helvetica', 8))
menubar.add_cascade(label="Meower95", menu=mainmenu)
viewmenu = Menu(menubar, tearoff=0, font=('Helvetica', 8))
viewmenu.add_command(label="Chat sidebar", command=lambda: toggle_view(0), font=('Helvetica', 8))
viewmenu.add_command(label="Chat entry", command=lambda: toggle_view(1), font=('Helvetica', 8))
viewmenu.add_command(label="User sidebar", command=lambda: toggle_view(2), font=('Helvetica', 8))
menubar.add_cascade(label="View", menu=viewmenu)
messages = Text(state=DISABLED, font=('Courier', 12),wrap=WORD)
scrollbar = ttk.Scrollbar(command=messages.yview)
messages.config(yscrollcommand = scrollbar.set)
reply_canvas = Canvas(height=200,width=450)
channels = Listbox(font=('Helvetica', 8))
channels.insert(END,"Home")
channels.insert(END,"Livechat")
channels.bind("<<ListboxSelect>>",change_channel)
userlist = ttk.Treeview(padding=0,show='tree',selectmode='browse')
userlist.bind("<<TreeviewSelect>>",view_user)
entry = ttk.Entry()
entry.insert(0,"Waiting for authentification... (reload the program if this takes too long)")
entry.configure(state=DISABLED)
entry.bind("<Return>",send_msg)
entry.bind("<Up>",lambda event: edit_gui(last_message))
refresh_view()
window.config(menu=menubar)
ws_data = {}
insert_home()
try:
while True:
try:
if not window.winfo_exists():
break
except:
break
try:
transfer = open("TRANSFER","r")
deleted = 0
try:
result = json.load(transfer)
except json.decoder.JSONDecodeError:
transfer = open("TRANSFER","w")
transfer.close()
result = ''
if result != '':
transfer.close()
transfer = open("TRANSFER","w")
transfer.write("")
transfer.close()
if result ["cmd"] == "statuscode":
print(result["val"])
if type(result["val"]) == str:
if result["val"] == "E:020 | Kicked":
entry.configure(state=NORMAL)
entry.delete(0,END)
entry.insert(END,"You were kicked from this server :(")
entry.configure(state=DISABLED)
elif result["val"] == "E:018 | Account Banned":
entry.confsigure(state=NORMAL)
entry.delete(0,END)
entry.insert(END,"You were banned from this server :(")
entry.configure(state=DISABLED)
elif result["val"] == "E:119 | IP Blocked":
entry.configure(state=NORMAL)
entry.delete(0,END)
entry.insert(END,"You were IP-banned from this server :(")
entry.configure(state=DISABLED)
elif result["cmd"] == "direct":
if "mode" in result["val"]:
if result["val"]["mode"] == "auth":
ws_data["userdata"] = result["val"]
log("Auth data received.",safe=True)
print("Recieved auth")
entry.configure(state=NORMAL)
entry.delete(0,END)
if ws_data["userdata"]["payload"]["account"]["ban"]["state"] == "perm_restriction" and ws_data["userdata"]["payload"]["account"]["ban"]["restrictions"] == 31:
entry.insert(0,f'You\'re banned for {ws_data["userdata"]["payload"]["account"]["ban"]["reason"]} :(')
entry.configure(state=DISABLED)
else:
entry.configure(state=NORMAL)
chats = readhttp("chats")["autoget"]
for i in chats:
del i["members"][i["members"].index(user)]
channels.insert(END, i["members"][0] if i["type"] else i["nickname"])
channellist[i["members"][0] if i["type"] else i["nickname"]] = i["_id"]
insert_home()
elif result["val"]["mode"] in (1,2):
print(result["val"])
if result["val"]["post_origin"] in ("home","livechat"):
if not result["val"]["post_origin"] in home:
home[result["val"]["post_origin"]] = []
home[result["val"]["post_origin"]].append(result["val"])
else:
if not "posts/"+result["val"]["post_origin"] in home:
home["posts/"+result["val"]["post_origin"]] = []
home["posts/"+result["val"]["post_origin"]].append(result["val"])
if not result["val"]["u"] in usrsound:
if last_sound_user == 12: last_sound_user = 1
else: last_sound_user += 1
usrsound[result["val"]["u"]] = last_sound_user
try:
player = pyglet.media.Player()
player.queue(pyglet.media.StaticSource(pyglet.media.load(os.path.realpath("assets/message" + str(usrsound[result["val"]["u"]]) + ".wav"))))
player.play()
except Exception as e:
print(e)
chan = channel_by_id(result["val"]["_id"])
print(home[chan][index_by_id(result["val"]["_id"],chan)])
insert_home()
elif result["val"]["mode"] == "update_post":
try:
chan = channel_by_id(result["val"]["payload"]["_id"])
try:
prev_history = home[chan][index_by_id(result["val"]["payload"]["_id"],chan)]["history"]
except KeyError:
prev_history = []
prev_history.append(home[chan][index_by_id(result["val"]["payload"]["_id"],chan)])
home[chan][index_by_id(result["val"]["payload"]["_id"],chan)] = result["val"]["payload"]
home[chan][index_by_id(result["val"]["payload"]["_id"],chan)]["edited"] = True
home[chan][index_by_id(result["val"]["payload"]["_id"],chan)]["history"] = prev_history
print(home[chan][index_by_id(result["val"]["payload"]["_id"],chan)])
insert_home()
except ValueError:
pass
elif result["val"]["mode"] == "delete":
try:
chan = channel_by_id(result["val"]["id"])
if cfg["settings"]["msgdel"]:
home[chan][index_by_id(result["val"]["id"],chan)]["isDeleted"] = True
if not "history" in home[chan][index_by_id(result["val"]["_id"],chan)]:
home[chan][index_by_id(result["val"]["_id"],chan)]["history"] = []
home[chan][index_by_id(result["val"]["_id"],chan)]["history"].append(home[chan][index_by_id(result["val"]["payload"]["_id"],chan)])
home[chan][index_by_id(result["val"]["id"],chan)]["isDeleted"] = True
else:
del home[chan][index_by_id(result["val"]["id"],chan)]
insert_home()
except ValueError:
pass
print(home[chan][index_by_id(result["val"]["payload"]["_id"],chan)])
elif result["val"]["mode"] == "banned":
entry.delete(0,END)
entry.configure(state=NORMAL)
if result["val"]["payload"]["state"] == "temp_ban" and result["val"]["payload"]["expires"] > time.time() or result["val"]["payload"]["state"] == "perm_ban":
entry.insert(END,f'You\'re banned for {result["val"]["payload"]["reason"]} :(')
entry.configure(state=DISABLED)
print(f'You\'re banned for {result["val"]["payload"]["reason"]} :(')
else:
ws_data[result["cmd"]] = result["val"]
if result["cmd"] == "ulist":
print("; ".join(result["val"].split(";")))
refresh_users()
except FileNotFoundError:
pass
window.update()
except Exception as Error:
sp.Popen.terminate(proc)
status = sp.Popen.poll(proc)
raise Error
sp.Popen.terminate(proc)
status = sp.Popen.poll(proc)
print("see ya! ;3")