-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
4034 lines (3551 loc) · 171 KB
/
Copy pathmain.py
File metadata and controls
4034 lines (3551 loc) · 171 KB
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 functools import wraps
from flask import Flask, send_file, render_template, render_template_string, request, jsonify, redirect, url_for, flash, send_from_directory, session
from werkzeug.utils import secure_filename
from flask_socketio import SocketIO, emit, join_room, leave_room
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from datetime import datetime
import json
from flask import Response
from collections import defaultdict
import time
from jinja2 import Undefined
import re
import ast
import os
import urllib.request
from datetime import datetime, timezone
import pytz
import io
import zipfile
import random
import hashlib
import base64
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import mimetypes
mimetypes.add_type('text/plain', '.py')
cst_timezone = pytz.timezone('America/Chicago')
class ProfanityFilter:
"""
A customizable profanity filter that replaces inappropriate words with censored versions.
It loads a list of banned words from a specified file.
"""
def __init__(self, wordlist_file='data/profanity_words.txt'):
"""
Initializes the ProfanityFilter.
Args:
wordlist_file (str): Path to the file containing banned words.
"""
self.wordlist_file = wordlist_file
self.profane_words = set()
self._regex = None
self.load_words(wordlist_file)
def load_words(self, wordlist_file):
try:
with open(wordlist_file, 'r') as f:
for line in f:
if line.strip() and not line.startswith('#'):
self.profane_words.add(line.strip().lower())
print(f"Loaded {len(self.profane_words)} profane words from {wordlist_file}")
except FileNotFoundError:
print(f"Warning: Profanity wordlist file '{wordlist_file}' not found. Creating it.")
with open(wordlist_file, 'w') as f:
f.write("# List of profane words to filter\n# One word per line\n")
except Exception as e:
print(f"Error loading profanity words: {e}")
self._compile_regex()
def save_words(self):
"""Saves the current set of profane words back to the wordlist file."""
try:
with open(self.wordlist_file, 'w') as f:
f.write("# List of profane words to filter\n# One word per line\n")
for word in sorted(list(self.profane_words)):
f.write(word + '\n')
print(f"Saved {len(self.profane_words)} profane words to {self.wordlist_file}")
except Exception as e:
print(f"Error saving profanity words: {e}")
def _compile_regex(self):
"""Compiles a single regex pattern for all profane words for high performance."""
if not self.profane_words:
self._regex = None
return
# Sort by length descending to match longer phrases before substrings
sorted_words = sorted(list(self.profane_words), key=len, reverse=True)
pattern = r'\b(' + '|'.join(re.escape(word) for word in sorted_words) + r')\b'
self._regex = re.compile(pattern, re.IGNORECASE)
def add_word(self, word):
"""Adds a word to the profane words list and saves it."""
word = word.strip().lower()
if word and word not in self.profane_words:
self.profane_words.add(word)
self.save_words()
self._compile_regex()
return True
return False
def remove_word(self, word):
"""Removes a word from the profane words list and saves it."""
word = word.strip().lower()
if word and word in self.profane_words:
self.profane_words.remove(word)
self.save_words()
self._compile_regex()
return True
return False
def _get_replacement(self, word):
"""
Generates a replacement string for a profane word.
Currently replaces with '#' of the same length as the word.
Args:
word (str): The profane word.
Returns:
str: The replacement string.
"""
return '#' * len(word)
def censor_text(self, text):
if not text or not self._regex:
return text
# Split text into tokens to avoid censoring parts of URLs
tokens = text.split()
censored_tokens = []
for token in tokens:
if token.startswith(('http://', 'https://', 'www.')):
censored_tokens.append(token)
else:
censored_tokens.append(self._regex.sub(lambda m: self._get_replacement(m.group(0)), token))
return ' '.join(censored_tokens)
def contains_profanity(self, text):
"""
Checks if the given text contains any profanity.
Args:
text (str): The text to check.
Returns:
bool: True if profanity is found, False otherwise.
"""
if not text or not self._regex:
return False
return bool(self._regex.search(text))
profanity_filter = ProfanityFilter(wordlist_file='data/profanity_words.txt')
UPLOAD_FOLDER = 'static/uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'mp4', 'webm', 'ogg', 'mov'}
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
CHAT_IMAGES_FOLDER = 'static/chat_images'
os.makedirs(CHAT_IMAGES_FOLDER, exist_ok=True)
def save_chat_image(image_data):
"""Saves a base64 image string to a file and returns the URL path."""
if not image_data or not isinstance(image_data, str) or not (image_data.startswith('data:image') or image_data.startswith('data:video')):
return None
try:
header, encoded = image_data.split(",", 1)
ext = header.split(";")[0].split("/")[1]
if ext == 'quicktime': ext = 'mov'
if ext == 'jpeg': ext = 'jpg'
if ext not in ALLOWED_EXTENSIONS:
return None
filename = f"chat_{int(time.time())}_{random.randint(1000, 9999)}.{ext}"
filepath = os.path.join(CHAT_IMAGES_FOLDER, filename)
with open(filepath, "wb") as f:
f.write(base64.b64decode(encoded))
return f"/{filepath}"
except:
return None
def save_server_icon(icon_data, server_id):
"""Saves a base64 server icon string to a file."""
if not icon_data or not isinstance(icon_data, str) or not icon_data.startswith('data:image'):
return None
try:
header, encoded = icon_data.split(",", 1)
ext = header.split(";")[0].split("/")[1]
if ext not in ['png', 'jpg', 'jpeg', 'gif']:
return None
filename = f"icon_{server_id}_{int(time.time())}.{ext}"
filepath = os.path.join(UPLOAD_FOLDER, filename)
with open(filepath, "wb") as f:
f.write(base64.b64decode(encoded))
return f"/static/uploads/{filename}"
except:
return None
EMOJI_FOLDER = 'static/emojis'
CUSTOM_EMOJIS_FILE = 'data/custom_emojis.json'
os.makedirs(EMOJI_FOLDER, exist_ok=True)
# Cache for expensive file operations
_custom_emojis_cache = None
_friends_cache = None # (friends_dict, requests_dict)
def get_link_metadata(url):
"""Fetches OpenGraph metadata from a URL with a timeout to prevent hanging."""
try:
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'}
req = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(req, timeout=1.5) as response:
# Only read the first 100KB to save memory/time
content = response.read(102400).decode('utf-8', errors='ignore')
title = re.search(r'<meta property="og:title" content="(.*?)"', content, re.I)
if not title: title = re.search(r'<title>(.*?)</title>', content, re.I)
desc = re.search(r'<meta property="og:description" content="(.*?)"', content, re.I)
if not desc: desc = re.search(r'<meta name="description" content="(.*?)"', content, re.I)
img = re.search(r'<meta property="og:image" content="(.*?)"', content, re.I)
return {
'url': url,
'title': title.group(1) if title else url,
'description': desc.group(1) if desc else "",
'image': img.group(1) if img else ""
}
except:
return None
def load_custom_emojis():
global _custom_emojis_cache
if _custom_emojis_cache is not None:
return _custom_emojis_cache
if os.path.exists(CUSTOM_EMOJIS_FILE):
try:
with open(CUSTOM_EMOJIS_FILE, 'r') as f:
_custom_emojis_cache = json.load(f)
return _custom_emojis_cache
except:
return {}
return {}
def save_custom_emojis(emojis):
global _custom_emojis_cache
_custom_emojis_cache = emojis
with open(CUSTOM_EMOJIS_FILE, 'w') as f:
json.dump(emojis, f, indent=2)
app = Flask(__name__)
CONFIG_FILE = 'data/config.json'
def load_config():
if os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, 'r') as f:
return json.load(f)
return {}
app.secret_key = 'your-secret-key-here' # Change this in production
socketio = SocketIO(app, cors_allowed_origins="*")
login_manager = LoginManager()
# Rate Limiting tracking: { username: [timestamp1, timestamp2, ...] }
user_message_history = {}
def get_aes_key():
"""Derive a 256-bit key for AES-256 encryption."""
return hashlib.sha256(app.secret_key.encode()).digest()
def encrypt_password(plain_text):
if not plain_text: return ""
aesgcm = AESGCM(get_aes_key())
nonce = os.urandom(12)
ciphertext = aesgcm.encrypt(nonce, plain_text.encode(), None)
return base64.b64encode(nonce + ciphertext).decode('utf-8')
def decrypt_password(cipher_text):
if not cipher_text: return ""
try:
data = base64.b64decode(cipher_text)
nonce = data[:12]
ciphertext = data[12:]
aesgcm = AESGCM(get_aes_key())
return aesgcm.decrypt(nonce, ciphertext, None).decode('utf-8')
except:
return cipher_text # Fallback for plain text migration
login_manager.init_app(app)
login_manager.login_view = 'login'
@app.route('/download-code')
def download_code():
# Target directory to zip (e.g., your project root)
target_dir = os.path.dirname(os.path.abspath(__file__))
# Create an in-memory byte stream for the ZIP file
memory_file = io.BytesIO()
with zipfile.ZipFile(memory_file, 'w', zipfile.ZIP_DEFLATED) as zf:
# Walk through the directory and add files to the archive
for root, dirs, files in os.walk(target_dir):
for file in files:
# Get the full path and a relative path for the ZIP internal structure
full_path = os.path.join(root, file)
relative_path = os.path.relpath(full_path, target_dir)
# Avoid zipping the running script itself or venv folders if needed
if "__pycache__" not in full_path and ".venv" not in full_path:
zf.write(full_path, relative_path)
# Reset stream position to the beginning
memory_file.seek(0)
return send_file(
memory_file,
mimetype='application/zip',
as_attachment=True,
download_name='project_code.zip'
)
def save_config(config):
with open(CONFIG_FILE, 'w') as f:
json.dump(config, f, indent=2)
app_config = load_config()
SERVERS_FILE = 'data/servers.json'
def load_servers():
if os.path.exists(SERVERS_FILE):
try:
with open(SERVERS_FILE, 'r') as f:
return json.load(f)
except: return {}
return {}
def save_servers(servers_dict):
with open(SERVERS_FILE, 'w') as f:
json.dump(servers_dict, f, indent=2)
servers_data = load_servers()
def can_access_room(room_id):
if not current_user.is_authenticated: return False
if current_user.role in ['Owner', 'Co-owner', 'Admin'] or current_user.id in ['jesseramsey', 'Killua']:
return True
server_id = room_id.split(':')[0] if ':' in room_id else None
if not server_id: return False
srv = servers_data.get(server_id)
if not srv: return False
return current_user.id == srv['owner'] or current_user.id in srv.get('members', [])
@app.context_processor
def inject_app_config():
# Check if current user has the CKC badge
has_ckc = False
if current_user.is_authenticated:
u_badges = users.get(current_user.id, {}).get('badges', [])
for b in u_badges:
b_text = b.get('text') if isinstance(b, dict) else b
if b_text == 'CKC':
has_ckc = True
break
# Filter servers for the UI
user_servers = {}
is_staff = current_user.is_authenticated and (current_user.role in ['Owner', 'Co-owner', 'Admin'] or current_user.id in ['jesseramsey', 'Killua'])
for srv_id, srv in servers_data.items():
if is_staff or (current_user.is_authenticated and (current_user.id == srv['owner'] or current_user.id in srv.get('members', []))):
user_servers[srv_id] = srv
return dict(app_config=app_config,
custom_emojis=load_custom_emojis(),
profane_words=sorted(list(profanity_filter.profane_words)),
special_user='jesseramsey', has_ckc=has_ckc,
servers=user_servers,
active_users=active_users)
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'),
'favicon.ico', mimetype='image/vnd.microsoft.icon')
def load_users():
users = {}
try:
with open('data/users.txt', 'r') as f:
for line in f:
if line.startswith('#') or not line.strip():
continue
parts = [p.strip() for p in line.strip().split('|')]
username, password_enc, display_name, role = parts[:4]
password = decrypt_password(password_enc)
is_suspended = parts[4] if len(parts) > 4 else "false"
is_muted = parts[5] if len(parts) > 5 else "false"
bio = parts[6] if len(parts) > 6 else ""
profile_pic = parts[7] if len(parts) > 7 else ""
theme = parts[8] if len(parts) > 8 else "default"
custom_theme_str = parts[9] if len(parts) > 9 else "{}"
ringtone_url = parts[10] if len(parts) > 10 else ""
mute_ringtone = parts[11] if len(parts) > 11 else "true"
banner_url = parts[12] if len(parts) > 12 else ""
badges_str = parts[13] if len(parts) > 13 else "[]" # This was index 13
is_stealth = parts[14] if len(parts) > 14 else "false"
security_question = parts[15] if len(parts) > 15 else ""
security_answer_enc = parts[16] if len(parts) > 16 else ""
custom_status = parts[17] if len(parts) > 17 else ""
security_answer = decrypt_password(security_answer_enc)
created_at = parts[18] if len(parts) > 18 else ""
last_online = parts[19] if len(parts) > 19 else ""
face_descriptor = parts[20] if len(parts) > 20 else ""
profile_bg = parts[21] if len(parts) > 21 else ""
is_infected = (parts[22] == "true") if len(parts) > 22 else False
# Safely load JSON data with fallbacks
try:
custom_theme = json.loads(custom_theme_str)
except:
try:
custom_theme = ast.literal_eval(custom_theme_str)
except:
custom_theme = {}
try:
badges = json.loads(badges_str)
except:
try:
badges = ast.literal_eval(badges_str)
except:
badges = []
users[username] = {
'password': password,
'display_name': display_name,
'role': role,
'profile_pic': profile_pic,
'is_suspended': is_suspended == "true",
'is_muted': is_muted == "true",
'bio': bio,
'theme': theme,
'custom_theme': custom_theme,
'ringtone_url': ringtone_url,
'mute_ringtone': mute_ringtone == "true",
'banner_url': banner_url,
'badges': badges,
'is_stealth': is_stealth == "true",
'security_question': security_question,
'security_answer': security_answer,
'custom_status': custom_status,
'created_at': created_at,
'last_online': last_online,
'face_descriptor': face_descriptor,
'profile_bg': profile_bg,
'is_infected': is_infected
}
except FileNotFoundError:
pass
return users
def save_users():
with open('data/users.txt', 'w') as f:
f.write('# Format: username|password|display_name|role|is_suspended|is_muted|bio|profile_pic|theme|custom_theme|ringtone_url|mute_ringtone|banner_url|badges|is_stealth|security_question|security_answer|custom_status|created_at|last_online|face_descriptor|profile_bg|is_infected\n')
for username, data in users.items():
password_enc = encrypt_password(data['password'])
security_answer_enc = encrypt_password(data.get('security_answer', ''))
f.write(f"{username}|{password_enc}|{data['display_name']}|{data['role']}|{str(data.get('is_suspended', False)).lower()}|{str(data.get('is_muted', False)).lower()}|{data.get('bio', '')}|{data.get('profile_pic', '')}|{data.get('theme', 'default')}|{json.dumps(data.get('custom_theme', {}))}|{data.get('ringtone_url', '')}|{str(data.get('mute_ringtone', True)).lower()}|{data.get('banner_url', '')}|{json.dumps(data.get('badges', []))}|{str(data.get('is_stealth', False)).lower()}|{data.get('security_question', '')}|{security_answer_enc}|{data.get('custom_status', '')}|{data.get('created_at', '')}|{data.get('last_online', '')}|{data.get('face_descriptor', '')}|{data.get('profile_bg', '')}|{str(data.get('is_infected', False)).lower()}\n")
def load_groups():
groups = {}
try:
if os.path.exists('data/groups.txt'):
with open('data/groups.txt', 'r') as f:
for line in f:
if line.strip() and not line.startswith('#'):
parts = line.strip().split('|')
if len(parts) >= 3:
group_id, name, members_json = parts[:3]
members = json.loads(members_json)
creator = parts[3] if len(parts) > 3 else (members[0] if members else "")
icon_url = parts[4] if len(parts) > 4 else ""
groups[group_id] = {
'name': name,
'members': members,
'creator': creator,
'icon_url': icon_url
}
except Exception as e:
print(f"Error loading groups: {e}")
return groups
def save_groups(groups):
try:
with open('data/groups.txt', 'w') as f:
f.write('# Format: group_id|name|members_json|creator|icon_url\n')
for gid, data in groups.items():
f.write(f"{gid}|{data['name']}|{json.dumps(data['members'])}|{data.get('creator', '')}|{data.get('icon_url', '')}\n")
except Exception as e:
print(f"Error saving groups: {e}")
def load_group_history(group_id):
filepath = f"data/group_msg_{group_id}.txt"
if not os.path.exists(filepath):
return []
messages = []
with open(filepath, 'r') as f:
for line in f:
if line.strip():
try:
messages.append(json.loads(line.strip()))
except: pass
return messages
def save_group_history(group_id, messages):
filepath = f"data/group_msg_{group_id}.txt"
with open(filepath, 'w') as f:
for msg in messages:
f.write(json.dumps(msg) + "\n")
@app.route('/profile/<username>')
@login_required
def view_profile(username):
if username not in users:
flash('User not found')
return redirect(url_for('home'))
user_data = users[username].copy()
user_data['bio'] = users[username].get('bio', 'No bio provided.')
friends, _ = load_friends()
user_friends = friends.get(current_user.id, [])
is_online = any(username in room_users for room_users in active_users.values())
return render_template('profile.html', username=username, user_data=user_data,
friends=user_friends, active_users=active_users, users=users,
user_theme=users.get(current_user.id, {}).get('theme', 'default'),
user_custom_theme=users.get(current_user.id, {}).get('custom_theme', {}),
is_online=is_online)
@app.route('/update_bio', methods=['POST'])
@login_required
def update_bio():
bio = request.form.get('bio', '').strip()
# Apply profanity filter to bios
filtered_bio = profanity_filter.censor_text(bio)
users[current_user.id]['bio'] = filtered_bio
save_users()
flash('Bio updated successfully!', 'success')
return redirect(url_for('home'))
@app.route('/update_banner', methods=['POST'])
@login_required
def update_banner():
banner_url = request.form.get('banner_url', '').strip()
# Handle Banner Upload
banner_file = request.files.get('banner_file')
if banner_file and banner_file.filename != '' and allowed_file(banner_file.filename):
filename = secure_filename(f"banner_{current_user.id}_{int(time.time())}_{banner_file.filename}")
banner_file.save(os.path.join(app.root_path, UPLOAD_FOLDER, filename))
banner_url = f"/static/uploads/{filename}"
users[current_user.id]['banner_url'] = banner_url
save_users()
flash('Profile banner updated successfully!', 'success')
return redirect(url_for('home'))
users = load_users()
messages = []
ROLES = ['Owner', 'Admin', 'Mod', 'Regular User', 'Co-owner', 'Developer']
def get_dm_filename(user1, user2):
# Sort usernames to ensure consistent filename regardless of sender/recipient
users = sorted([user1, user2])
return f"data/dm_{users[0]}_{users[1]}.txt"
def load_dm_history(user1, user2):
filepath = get_dm_filename(user1, user2)
if not os.path.exists(filepath):
return []
try:
with open(filepath, 'r') as f:
messages = []
for line in f:
if line.strip():
try:
messages.append(json.loads(line.strip()))
except json.JSONDecodeError:
try:
messages.append(ast.literal_eval(line.strip()))
except:
pass
return messages
except Exception as e:
print(f"Error loading DM history from {filepath}: {e}")
return []
#saves DM history between two users to a text file in ./data with filename format dm_user1_user2.txt (sorted alphabetically)
def save_dm_history(user1, user2, messages):
filepath = get_dm_filename(user1, user2)
try:
with open(filepath, 'w') as f:
for msg in messages:
f.write(json.dumps(msg) + "\n")
except Exception as e:
print(f"Error saving DM history to {filepath}: {e}")
#loads chat history for all rooms from text files in ./data with filename format chat_roomname.txt, returns a dictionary with room names as keys and lists of messages as values
def load_chat_history():
rooms = defaultdict(list)
if not os.path.exists('data'):
return rooms
for filename in os.listdir('data'):
if filename.startswith('chat_') and filename.endswith('.txt'):
room_id = filename[5:-4].replace('_channel_', ':')
try:
with open(f'data/{filename}', 'r', encoding='utf-8') as f:
for line in f:
if line.strip():
try:
msg = json.loads(line.strip())
rooms[room_id].append(msg)
except: continue
except: pass
return rooms
#saves chat history for a specific room to a text file in ./data with filename format chat_roomname.txt, messages should be in JSON format, one message per line
def save_chat_history(room):
safe_room = room.replace(':', '_channel_')
with open(f'data/chat_{safe_room}.txt', 'w', encoding='utf-8') as f:
for msg in chat_rooms[room]:
f.write(json.dumps(msg) + "\n")
#loads announcements from a text file in ./data/announcements.txt, returns a list of announcements, each announcement should be in JSON format, one announcement per line
def load_announcements():
try:
with open('data/announcements.txt', 'r') as f:
announcements_list = []
for line in f:
if line.strip():
try:
announcements_list.append(json.loads(line.strip()))
except json.JSONDecodeError:
try:
announcements_list.append(ast.literal_eval(line.strip()))
except:
continue
return announcements_list
except FileNotFoundError:
return []
#saves announcements to a text file in ./data/announcements.txt, each announcement should be in JSON format, one announcement per line
def save_announcements():
with open('data/announcements.txt', 'w') as f:
for announcement in announcements:
f.write(json.dumps(announcement) + "\n")
#loads activity logs from a text file in ./data/activity_logs.txt, returns a list of logs, each log should be in JSON format, one log per line. Logs can include channel joins, messages sent, profanity detected, and reports made. Each log entry should have a type (e.g. 'join', 'message', 'profanity', 'report'), username, timestamp, and details (which can be a dictionary with additional info depending on the type)
def load_activity_logs():
"""Load activity logs (channel joins, messages, profanity)"""
logs = []
try:
if os.path.exists('data/activity_logs.txt'):
with open('data/activity_logs.txt', 'r') as f:
for line in f:
if line.strip():
try:
logs.append(json.loads(line.strip()))
except:
pass
except Exception as e:
print(f"Error loading activity logs: {e}")
return logs
#logs an activity to the activity_logs.txt file, activity_type can be 'join', 'message', 'profanity', or 'report'. Details should be a dictionary with relevant information depending on the type (e.g. for 'message' it could include room and message content, for 'profanity' it could include the original message and filtered message, etc.)
def log_activity(activity_type, username, details):
"""Log an activity: 'join', 'message', 'profanity', 'report'"""
try:
log_entry = {
'type': activity_type,
'username': username,
'timestamp': datetime.now(cst_timezone).strftime('%Y-%m-%d %I:%M %p'),
'details': details
}
with open('data/activity_logs.txt', 'a') as f:
f.write(json.dumps(log_entry) + "\n")
except Exception as e:
print(f"Error logging activity: {e}")
chat_rooms = defaultdict(list, load_chat_history())
announcements = load_announcements()
activity_logs = load_activity_logs()
active_users = defaultdict(set)
connected_users = {} # {username: connection_count}
# Registry for active voice calls to support persistence across page navigation
# Format: { username: partner_username }
active_voice_calls = {}
# Multi-user voice channels (Discord-style server voice rooms)
voice_room_members = defaultdict(set) # room_id ("srv_xxx:channel") -> set(username)
user_voice_room = {} # username -> room_id
user_voice_sid = {} # username -> socket sid that joined voice
sid_voice_user = {} # sid -> username (for cleanup on disconnect)
user_voice_status = {} # username -> {'muted': bool, 'deafened': bool}
def rename_user_data(old_username, new_username):
"""Renames a username across all persistent data and in-memory state."""
# 1. Update active users sets
for room in active_users:
if old_username in active_users[room]:
active_users[room].discard(old_username)
active_users[room].add(new_username)
# Update active voice calls registry
if old_username in active_voice_calls:
active_voice_calls[new_username] = active_voice_calls.pop(old_username)
# Update voice channel registries
if old_username in user_voice_room:
room_id = user_voice_room.pop(old_username)
user_voice_room[new_username] = room_id
if old_username in voice_room_members.get(room_id, set()):
voice_room_members[room_id].discard(old_username)
voice_room_members[room_id].add(new_username)
if old_username in user_voice_sid:
sid = user_voice_sid.pop(old_username)
user_voice_sid[new_username] = sid
sid_voice_user[sid] = new_username
if old_username in user_voice_status:
user_voice_status[new_username] = user_voice_status.pop(old_username)
# 2. Update chat histories
for room in chat_rooms:
updated = False
for msg in chat_rooms[room]:
if msg.get('sender') == old_username:
msg['sender'] = new_username
updated = True
if updated:
save_chat_history(room)
# 3. Update Announcements
updated_ann = False
for ann in announcements:
if ann.get('author') == old_username:
ann['author'] = new_username
updated_ann = True
if updated_ann:
save_announcements()
# 4. Update Direct Messages (content and filename)
if os.path.exists('data'):
for filename in os.listdir('data'):
if filename.startswith('dm_') and filename.endswith('.txt'):
parts = filename[3:-4].split('_')
if old_username in parts:
old_path = os.path.join('data', filename)
msgs = load_dm_history(parts[0], parts[1])
for msg in msgs:
if msg.get('sender') == old_username: msg['sender'] = new_username
if msg.get('recipient') == old_username: msg['recipient'] = new_username
new_parts = sorted([new_username if p == old_username else p for p in parts])
save_dm_history(new_parts[0], new_parts[1], msgs)
new_filename = f"dm_{new_parts[0]}_{new_parts[1]}.txt"
if filename != new_filename:
os.remove(old_path)
# 5. Update Friends
friends, friend_requests = load_friends()
changed_f = False
if old_username in friends:
friends[new_username] = friends.pop(old_username)
changed_f = True
for u in list(friends.keys()):
if old_username in friends[u]:
friends[u] = [new_username if x == old_username else x for x in friends[u]]
changed_f = True
if old_username in friend_requests:
friend_requests[new_username] = friend_requests.pop(old_username)
changed_f = True
for u in list(friend_requests.keys()):
if old_username in friend_requests[u]:
friend_requests[u] = [new_username if x == old_username else x for x in friend_requests[u]]
changed_f = True
if changed_f:
save_friends(friends, friend_requests)
# 6. Update Groups and Group Messages
gs = load_groups()
for gid in gs:
if old_username in gs[gid]['members']:
gs[gid]['members'] = [new_username if m == old_username else m for m in gs[gid]['members']]
save_groups(gs)
if gs[gid].get('creator') == old_username:
gs[gid]['creator'] = new_username
save_groups(gs)
gm_msgs = load_group_history(gid)
updated_gm = False
for msg in gm_msgs:
if msg.get('sender') == old_username:
msg['sender'] = new_username
updated_gm = True
if updated_gm:
save_group_history(gid, gm_msgs)
# 7. Update Activity logs
if os.path.exists('data/activity_logs.txt'):
logs = []
with open('data/activity_logs.txt', 'r') as f:
for line in f:
try:
l = json.loads(line.strip())
if l.get('username') == old_username: l['username'] = new_username
logs.append(l)
except: pass
with open('data/activity_logs.txt', 'w') as f:
for l in logs:
f.write(json.dumps(l) + "\n")
# 8. Update Polls
p_data = load_polls()
for pid in p_data:
if p_data[pid].get('creator') == old_username: p_data[pid]['creator'] = new_username
for opt in p_data[pid].get('votes', {}):
if old_username in p_data[pid]['votes'][opt]:
p_data[pid]['votes'][opt] = [new_username if v == old_username else v for v in p_data[pid]['votes'][opt]]
save_polls(p_data)
# Define a User class that inherits from UserMixin for Flask-Login
class User(UserMixin):
def __init__(self, username):
self.id = username
self.display_name = users[username]['display_name']
self.role = users[username]['role']
# Required by Flask-Login to load user from session
@login_manager.user_loader
def load_user(username):
if username in users:
return User(username)
return None
# Route for user registration
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
display_name = request.form.get('display_name', username)
if username in users:
flash('Username already exists')
return redirect(url_for('register'))
users[username] = {
'password': password,
'display_name': display_name,
'role': 'Regular User',
'created_at': datetime.now(cst_timezone).strftime('%Y-%m-%d %I:%M %p'),
'last_online': ''
}
save_users()
login_user(User(username))
flash('Registration successful')
return redirect(url_for('home'))
return render_template('register.html')
# Route for user login
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
# Handle Security Question Verification Stage
if 'security_answer' in request.form:
pending_username = session.get('pending_login_username')
if not pending_username or pending_username not in users:
flash('Login session expired. Please try again.')
session.pop('pending_login_username', None)
return redirect(url_for('login'))
user_answer = request.form.get('security_answer', '').strip().lower()
stored_answer = users[pending_username].get('security_answer', '').strip().lower()
if user_answer == stored_answer:
login_user(User(pending_username))
session.pop('pending_login_username', None)
return redirect(url_for('home'))
else:
flash('Incorrect security answer')
return render_template('login.html',
show_security_modal=True,
security_question=users[pending_username].get('security_question'))
username = request.form['username']
password = request.form['password']
if username in users and users[username]['password'] == password:
# Check maintenance mode
if app_config.get('maintenance_mode', False) and users[username].get('role') not in ['Owner', 'Co-owner']:
flash('Site is currently under maintenance. Only Owners and Co-owners can login.', 'warning')
return render_template('login.html')
# Check if security question is enabled for this user
if users[username].get('security_question') and users[username].get('security_answer'):
session['pending_login_username'] = username
return render_template('login.html',
show_security_modal=True,
security_question=users[username].get('security_question'))
login_user(User(username))
if username == "jesseramsey":
flash("Welcome, Jesse", "jesse_welcome")
elif username == "Killua":
flash("Welcome, Killua", "jesse_welcome")
return redirect(url_for('home'))
flash('Invalid username or password')
return render_template('login.html')
# Route for user settings (password change, profile update, theme selection)
@app.route('/settings', methods=['POST'])
@login_required
def settings():
if request.method == 'POST':
action = request.form.get('action')
response = {'status': 'error', 'message': 'Unknown error occurred'}
if action == 'password':
current_password = request.form['current_password']
new_password = request.form['new_password']
confirm_password = request.form['confirm_password']
if users[current_user.id]['password'] != current_password:
response['message'] = 'Current password is incorrect'
elif new_password != confirm_password:
response['message'] = 'New passwords do not match'
else:
users[current_user.id]['password'] = new_password
save_users()
response = {'status': 'success', 'message': 'Password updated successfully!'}
elif action == 'profile':
new_username = request.form['new_username']
new_display_name = request.form['new_display_name']
new_status = request.form.get('custom_status', '').strip()
if new_username != current_user.id and new_username in users:
response['message'] = 'Username already exists'
else:
# Handle PFP Upload
pfp_file = request.files.get('pfp_file')
if pfp_file and pfp_file.filename != '' and allowed_file(pfp_file.filename):
filename = secure_filename(f"pfp_{current_user.id}_{int(time.time())}_{pfp_file.filename}")
pfp_file.save(os.path.join(app.root_path, UPLOAD_FOLDER, filename))
profile_pic = f"/static/uploads/{filename}"
else:
profile_pic = request.form.get('profile_pic', '')
# Handle Banner Upload
banner_file = request.files.get('banner_file')
if banner_file and banner_file.filename != '' and allowed_file(banner_file.filename):
filename = secure_filename(f"banner_{current_user.id}_{int(time.time())}_{banner_file.filename}")
banner_file.save(os.path.join(app.root_path, UPLOAD_FOLDER, filename))
banner_url = f"/static/uploads/{filename}"
else:
banner_url = request.form.get('banner_url', '')
# Handle Background Upload
bg_file = request.files.get('bg_file')
if bg_file and bg_file.filename != '' and allowed_file(bg_file.filename):
filename = secure_filename(f"bg_{current_user.id}_{int(time.time())}_{bg_file.filename}")
bg_file.save(os.path.join(app.root_path, UPLOAD_FOLDER, filename))
profile_bg = f"/static/uploads/{filename}"
else:
profile_bg = request.form.get('profile_bg', '')
ringtone_url = request.form.get('ringtone_url', '')
mute_ringtone = request.form.get('mute_ringtone') == 'on'
is_stealth = request.form.get('is_stealth') == 'on'
security_question = request.form.get('security_question', '').strip()
security_answer = request.form.get('security_answer', '').strip()
old_username = current_user.id
old_stealth = users[old_username].get('is_stealth', False)
if new_username != old_username:
# Migrate connection status if username changed
if old_username in connected_users:
connected_users[new_username] = connected_users.pop(old_username)
users[new_username] = users.pop(old_username)
rename_user_data(old_username, new_username)
logout_user()
user_message_history.pop(old_username, None)
login_user(User(new_username))
users[new_username]['custom_status'] = profanity_filter.censor_text(new_status)
users[new_username]['display_name'] = new_display_name
users[new_username]['profile_pic'] = profile_pic
users[new_username]['banner_url'] = banner_url
users[new_username]['profile_bg'] = profile_bg
users[new_username]['ringtone_url'] = ringtone_url
users[new_username]['mute_ringtone'] = mute_ringtone
# Only allow staff to use stealth mode
if current_user.role in ['Owner', 'Co-owner', 'Admin'] or current_user.id == 'Killua':
users[new_username]['is_stealth'] = is_stealth
# If stealth status changed while online, notify others immediately
if old_stealth != is_stealth and new_username in connected_users:
status = 'offline' if is_stealth else 'online'
socketio.emit('user-status-change', {'username': new_username, 'status': status})