-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
2482 lines (2080 loc) · 92.7 KB
/
Copy pathapi.py
File metadata and controls
2482 lines (2080 loc) · 92.7 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
#!/usr/bin/env python3
"""
pyIRCX Management API
Provides comprehensive data access and management for web administration
"""
import sqlite3
import json
import sys
import os
import time
import re
import hashlib
import socket
import subprocess
from pathlib import Path
from datetime import datetime
import logging
try:
import fcntl
except ImportError: # pragma: no cover - non-POSIX fallback
fcntl = None
# Import connection pool and helpers
import db_pool
from api_helpers import (
api_error_handler,
rate_limit,
timed_cache,
validate_access_type,
validate_pattern,
validate_timeout,
validate_nickname,
validate_channel_name,
validate_staff_level
)
from responses import get_log_message, SERVER_MESSAGES
# Setup logging
logger = logging.getLogger(__name__)
# Default paths - check system install location first, then local checkout
# System installation paths (from install.sh)
SYSTEM_CONFIG = "/etc/pyircx/pyircx_config.json"
SYSTEM_INSTALL = "/opt/pyircx"
PROJECT_ROOT = Path(__file__).resolve().parent
PROJECT_CONFIG = PROJECT_ROOT / "pyircx_config.json"
# User installation paths (legacy manual installations)
USER_CONFIG = os.path.expanduser("~/pyIRCX/pyircx_config.json")
USER_INSTALL = os.path.expanduser("~/pyIRCX")
ENV_CONFIG = os.environ.get("PYIRCX_CONFIG")
ENV_DB = os.environ.get("PYIRCX_DB")
ENV_LOG = os.environ.get("PYIRCX_LOG")
ENV_STATUS = os.environ.get("PYIRCX_STATUS")
# Determine which installation is active
if ENV_CONFIG:
DEFAULT_CONFIG = ENV_CONFIG
DEFAULT_DB = ENV_DB or str(PROJECT_ROOT / "pyircx.db")
DEFAULT_LOG = ENV_LOG or str(PROJECT_ROOT / "pyircx.log")
DEFAULT_STATUS = ENV_STATUS or str(PROJECT_ROOT / "pyircx_status.json")
elif os.path.exists(SYSTEM_CONFIG):
# System installation detected
DEFAULT_CONFIG = SYSTEM_CONFIG
DEFAULT_DB = os.path.join(SYSTEM_INSTALL, "pyircx.db")
DEFAULT_LOG = os.path.join(SYSTEM_INSTALL, "pyircx.log")
DEFAULT_STATUS = os.path.join(SYSTEM_INSTALL, "pyircx_status.json")
elif PROJECT_CONFIG.exists():
# Running from a source checkout
DEFAULT_CONFIG = str(PROJECT_CONFIG)
DEFAULT_DB = str(PROJECT_ROOT / "pyircx.db")
DEFAULT_LOG = str(PROJECT_ROOT / "pyircx.log")
DEFAULT_STATUS = str(PROJECT_ROOT / "pyircx_status.json")
else:
# Fall back to legacy user installation
DEFAULT_CONFIG = USER_CONFIG
DEFAULT_DB = os.path.join(USER_INSTALL, "pyircx.db")
DEFAULT_LOG = os.path.join(USER_INSTALL, "pyircx.log")
DEFAULT_STATUS = os.path.join(USER_INSTALL, "pyircx_status.json")
def _get_bcrypt():
"""Import bcrypt only when password operations are needed."""
try:
import bcrypt
except ImportError as e:
raise RuntimeError("bcrypt is required for password operations") from e
return bcrypt
def _hash_password(password):
bcrypt = _get_bcrypt()
return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
def _check_password(password, password_hash):
bcrypt = _get_bcrypt()
return bcrypt.checkpw(password.encode('utf-8'), password_hash.encode('utf-8'))
def ensure_db_pool(pool_size=10):
"""Initialize the shared DB pool on first use."""
if db_pool.get_pool_stats() is not None:
return True
return init_db_pool(pool_size=pool_size)
def load_config():
"""Load pyIRCX configuration"""
with open(DEFAULT_CONFIG, 'r') as f:
return json.load(f)
def save_config(config):
"""Save pyIRCX configuration"""
with open(DEFAULT_CONFIG, 'w') as f:
json.dump(config, f, indent=2)
return config
def invalidate_config_caches():
"""Clear cached config-derived API responses after writes."""
for func in (get_motd, get_server_config, get_full_config, get_newsflash_settings):
cache_clear = getattr(func, 'cache_clear', None)
if callable(cache_clear):
cache_clear()
@timed_cache(seconds=60)
@api_error_handler
def get_motd():
"""Get MOTD (Message of the Day) from configuration (cached for 60 seconds)"""
config = load_config()
if 'server' in config and 'motd' in config['server']:
motd = config['server']['motd']
# Return as array of lines
if isinstance(motd, str):
return {"motd": [motd]}
return {"motd": motd}
# Return empty MOTD if not configured (default should be in config file)
return {"motd": []}
@api_error_handler
def set_motd(motd_lines):
"""Set MOTD (Message of the Day) in configuration"""
config = load_config()
if 'server' not in config:
config['server'] = {}
# Parse motd_lines - can be JSON array or newline-separated string
if isinstance(motd_lines, str):
try:
# Try to parse as JSON first
parsed = json.loads(motd_lines)
if isinstance(parsed, list):
motd_lines = parsed
else:
# Split on newlines (preserve empty lines for spacing)
motd_lines = [line.rstrip() for line in motd_lines.split('\n')]
except json.JSONDecodeError:
# Not JSON, split on newlines (preserve empty lines for spacing)
motd_lines = [line.rstrip() for line in motd_lines.split('\n')]
config['server']['motd'] = motd_lines
save_config(config)
invalidate_config_caches()
return {"success": True}
def get_db_path():
"""Get database path from config or use default"""
config = load_config()
if 'database' in config and 'path' in config['database']:
db_path = config['database']['path']
# Handle relative paths
if not os.path.isabs(db_path):
if os.path.abspath(DEFAULT_CONFIG) == os.path.abspath(SYSTEM_CONFIG):
db_path = os.path.normpath(os.path.join(SYSTEM_INSTALL, db_path))
else:
config_dir = os.path.dirname(os.path.abspath(DEFAULT_CONFIG))
db_path = os.path.normpath(os.path.join(config_dir, db_path))
return db_path
return DEFAULT_DB
def get_admin_queue_path():
"""Get admin command queue path based on installation type"""
env_queue = os.environ.get("PYIRCX_ADMIN_QUEUE")
if env_queue:
return env_queue
if os.path.abspath(DEFAULT_CONFIG) == os.path.abspath(SYSTEM_CONFIG):
return os.path.join(SYSTEM_INSTALL, "admin_commands.queue")
config_dir = os.path.dirname(os.path.abspath(DEFAULT_CONFIG))
return os.path.join(config_dir, "admin_commands.queue")
def write_admin_command(command_string, success_message):
"""Write a command to the admin command queue file
Args:
command_string: Command string to write (e.g., "KILL_CHANNEL:#test")
success_message: Success message to return
Returns:
dict with success/error status
"""
try:
cmd_file = get_admin_queue_path()
queue_dir = os.path.dirname(os.path.abspath(cmd_file))
if queue_dir:
os.makedirs(queue_dir, exist_ok=True)
lock_file = f"{cmd_file}.lock"
with open(lock_file, 'a', encoding='utf-8') as lock:
if fcntl:
fcntl.flock(lock.fileno(), fcntl.LOCK_EX)
with open(cmd_file, 'a', encoding='utf-8') as f:
f.write(f"{command_string}\n")
f.flush()
os.fsync(f.fileno())
if fcntl:
fcntl.flock(lock.fileno(), fcntl.LOCK_UN)
return {"success": True, "message": success_message}
except Exception as e:
return {"error": SERVER_MESSAGES['api_admin_command_write_failed'].format(error=e)}
def init_db_pool(pool_size=10):
"""Initialize the database connection pool
Args:
pool_size: Number of connections to maintain in pool (default: 10)
Returns:
bool: True if initialized successfully, False otherwise
"""
try:
db_path = get_db_path()
db_pool.init_pool(db_path, pool_size=pool_size)
logger.info(get_log_message("api_pool_initialized", path=db_path, pool_size=pool_size))
return True
except Exception as e:
logger.error(get_log_message("api_pool_init_failed", error=e))
return False
# ============================================================================
# HEALTH CHECK
# ============================================================================
@api_error_handler
def health_check():
"""Health check endpoint for monitoring systems
Returns:
dict: Health status including database, status file, and pool stats
"""
health = {
'healthy': True,
'checks': {},
'timestamp': int(time.time())
}
# Check 1: Database connectivity
try:
ensure_db_pool()
with db_pool.get_connection(timeout=2.0) as conn:
cursor = conn.cursor()
cursor.execute("SELECT 1")
cursor.fetchone()
health['checks']['database'] = {'status': 'ok', 'message': SERVER_MESSAGES['api_health_db_ok']}
except Exception as e:
health['checks']['database'] = {'status': 'error', 'message': str(e)}
health['healthy'] = False
# Check 2: Status file freshness
try:
if os.path.exists(DEFAULT_STATUS):
with open(DEFAULT_STATUS, 'r') as f:
status = json.load(f)
age = time.time() - status.get('timestamp', 0)
if age < 60:
health['checks']['status_file'] = {'status': 'ok', 'message': SERVER_MESSAGES['api_health_status_fresh'].format(age=int(age))}
elif age < 300:
health['checks']['status_file'] = {'status': 'warning', 'message': SERVER_MESSAGES['api_health_status_stale'].format(age=int(age))}
else:
health['checks']['status_file'] = {'status': 'error', 'message': SERVER_MESSAGES['api_health_status_very_stale'].format(age=int(age))}
health['healthy'] = False
else:
health['checks']['status_file'] = {'status': 'warning', 'message': SERVER_MESSAGES['api_health_status_not_found']}
except Exception as e:
health['checks']['status_file'] = {'status': 'error', 'message': str(e)}
# Check 3: Connection pool stats
try:
pool_stats = db_pool.get_pool_stats()
if pool_stats:
health['checks']['connection_pool'] = {
'status': 'ok',
'pool_size': pool_stats['pool_size'],
'available': pool_stats['available'],
'in_use': pool_stats['in_use']
}
else:
health['checks']['connection_pool'] = {'status': 'error', 'message': SERVER_MESSAGES['api_health_pool_not_initialized']}
health['healthy'] = False
except Exception as e:
health['checks']['connection_pool'] = {'status': 'error', 'message': str(e)}
return health
# ============================================================================
# REAL-TIME STATUS
# ============================================================================
@api_error_handler
def get_realtime_status():
"""Get real-time connected users and active channels from status dump"""
if not os.path.exists(DEFAULT_STATUS):
return {"error": SERVER_MESSAGES['api_status_not_found']}
with open(DEFAULT_STATUS, 'r') as f:
status = json.load(f)
# Calculate age of status
age = time.time() - status.get('timestamp', 0)
status['status_age'] = age
return status
@api_error_handler
def get_services_list():
"""Get list of network services and ServiceBots with their status"""
config = load_config()
# Define core services (always present when server is running)
core_services = [
{
"nickname": "System",
"type": "Core Service",
"description": "Network Services",
"is_servicebot": False,
"channels": ["#System"]
},
{
"nickname": "Registrar",
"type": "Core Service",
"description": "Registration Services (nickname and channel registration)",
"is_servicebot": False,
"channels": ["#System"]
},
{
"nickname": "Messenger",
"type": "Core Service",
"description": "Message Services (mailbox and private messaging)",
"is_servicebot": False,
"channels": ["#System"]
},
{
"nickname": "NewsFlash",
"type": "Core Service",
"description": "News Broadcast Services (rotating and push messages)",
"is_servicebot": False,
"channels": ["#System"]
}
]
# Get ServiceBot configuration
servicebot_count = config.get('services', {}).get('servicebot_count', 10)
servicebot_max_channels = config.get('services', {}).get('servicebot_max_channels', 10)
# Create ServiceBot entries
servicebots = []
for i in range(1, servicebot_count + 1):
bot_name = f"ServiceBot{i:02d}"
servicebots.append({
"nickname": bot_name,
"type": "ServiceBot",
"description": f"Service Bot #{i} (channel monitoring and moderation)",
"is_servicebot": True,
"max_channels": servicebot_max_channels,
"channels": [] # Will be populated from status if available
})
# Try to get real-time channel information from status file
if os.path.exists(DEFAULT_STATUS):
try:
with open(DEFAULT_STATUS, 'r') as f:
status = json.load(f)
# Update service channel lists from status file services data
all_services = core_services + servicebots
for service_status in status.get('services', []):
service_nick = service_status.get('nickname')
service_channels = service_status.get('channels', [])
# Find matching service in our list and update its channels
for service in all_services:
if service['nickname'] == service_nick:
service['channels'] = service_channels
break
# Add timestamp for freshness
return {
"services": all_services,
"servicebot_count": servicebot_count,
"servicebot_enabled": config.get('servicebot', {}).get('enabled', True),
"timestamp": status.get('timestamp', 0),
"server_running": True
}
except Exception:
# If status file can't be read, still return service list
pass
# Return services list even if status file not available
return {
"services": core_services + servicebots,
"servicebot_count": servicebot_count,
"servicebot_enabled": config.get('servicebot', {}).get('enabled', True),
"server_running": False
}
# ============================================================================
# IRC SERVER COMMUNICATION
# ============================================================================
@api_error_handler
def send_irc_kill_channel(channel_name):
"""Kill a channel by writing to pyircx admin command queue
Args:
channel_name: Channel to kill (e.g. '#pyIRCX')
Returns:
dict with success/error status
"""
validate_channel_name(channel_name)
return write_admin_command(
f"KILL_CHANNEL:{channel_name}",
SERVER_MESSAGES['api_channel_reset'].format(channel=channel_name)
)
@api_error_handler
def send_irc_kill_user(nickname, reason=None):
"""Kill a user connection by writing to pyircx admin command queue
Args:
nickname: Nickname to kill
reason: Kill reason (optional)
Returns:
dict with success/error status
"""
validate_nickname(nickname)
if not reason:
reason = SERVER_MESSAGES['api_kill_default_reason']
if len(reason) > 500:
raise ValueError(SERVER_MESSAGES['api_reason_required'])
return write_admin_command(
f"KILL_USER:{nickname}:{reason}",
SERVER_MESSAGES['api_kill_success'].format(nickname=nickname)
)
@api_error_handler
def send_irc_ban_user(nickname, reason=None, duration=3600):
"""Ban a user by writing to pyircx admin command queue
Args:
nickname: Nickname to ban
reason: Ban reason (optional)
duration: Ban duration in seconds (default: 1 hour)
Returns:
dict with success/error status
"""
validate_nickname(nickname)
if not isinstance(duration, int) or duration < 0:
raise ValueError(SERVER_MESSAGES['api_ban_duration_invalid'])
if not reason:
reason = SERVER_MESSAGES['api_ban_default_reason']
if len(reason) > 500:
raise ValueError(SERVER_MESSAGES['api_reason_required'])
return write_admin_command(
f"BAN_USER:{nickname}:{duration}:{reason}",
SERVER_MESSAGES['api_ban_success'].format(nickname=nickname, duration=duration)
)
@api_error_handler
def send_irc_lock_channel(channel_name, owner="System"):
"""Lock a channel (register + set auth-only) by writing to pyircx admin command queue
Args:
channel_name: Channel to lock (e.g. '#channel')
owner: Owner for the channel (staff username or registered nickname)
Returns:
dict with success/error status
"""
validate_channel_name(channel_name)
if not owner or len(owner) > 30:
raise ValueError(SERVER_MESSAGES['api_owner_name_required'])
return write_admin_command(
f"LOCK_CHANNEL:{channel_name}:{owner}",
SERVER_MESSAGES['api_lock_channel_success'].format(channel_name=channel_name, owner=owner)
)
@api_error_handler
def set_channel_mode(channel_name, mode_string):
"""Set channel mode via admin command queue
Args:
channel_name: Channel name (e.g., #channel)
mode_string: Mode string (e.g., "+z" or "-z")
Returns:
dict with success/error status
"""
validate_channel_name(channel_name)
if not mode_string or len(mode_string) > 50:
raise ValueError(SERVER_MESSAGES['api_mode_string_required'])
if not re.match(r'^[+-][a-zA-Z]+$', mode_string):
raise ValueError(SERVER_MESSAGES['api_mode_string_invalid_format'])
return write_admin_command(
f"SET_CHANNEL_MODE:{channel_name}:{mode_string}",
SERVER_MESSAGES['api_set_mode_success'].format(mode_string=mode_string, channel_name=channel_name)
)
@api_error_handler
def set_channel_topic(channel_name, topic):
"""Set channel topic via admin command queue
Args:
channel_name: Channel name (e.g., #channel)
topic: New topic (empty string to clear)
Returns:
dict with success/error status
"""
validate_channel_name(channel_name)
if topic and len(topic) > 500:
raise ValueError(SERVER_MESSAGES['api_topic_too_long'])
return write_admin_command(
f"SET_CHANNEL_TOPIC:{channel_name}:{topic}",
SERVER_MESSAGES['api_set_topic_success'].format(channel_name=channel_name)
)
@api_error_handler
def apply_channel_modes_live(channel_name, modes):
"""Apply channel modes by killing channel to force reload from database
Args:
channel_name: Channel name (e.g., #channel)
modes: Mode string (e.g., "nt" or "*" to clear)
Returns:
dict with success/error status
"""
# Kill channel to force reload from database with new modes
return send_irc_kill_channel(channel_name)
@api_error_handler
def apply_channel_props_live(channel_name, topic=None, onjoin=None, onpart=None,
memberkey=None, hostkey=None, ownerkey=None):
"""Apply channel PROP settings by killing channel to force reload from database
Args:
channel_name: Channel name
topic: Channel topic (or "*" to clear)
onjoin: On-join message (or "*" to clear)
onpart: On-part message (or "*" to clear)
memberkey: Member key (or "*" to clear)
hostkey: Host key (or "*" to clear)
ownerkey: Owner key (or "*" to clear)
Returns:
dict with success/error status
"""
# Kill channel to force reload from database with new properties
return send_irc_kill_channel(channel_name)
# ============================================================================
# DATABASE STATISTICS
# ============================================================================
@api_error_handler
def get_server_stats():
"""Get server statistics from database and runtime status"""
db_path = get_db_path()
with db_pool.get_connection() as conn:
cursor = conn.cursor()
stats = {}
# Count staff users
cursor.execute("SELECT COUNT(*) as count, level FROM users GROUP BY level")
staff_counts = {}
total_staff = 0
for row in cursor.fetchall():
staff_counts[row['level']] = row['count']
total_staff += row['count']
stats['staff'] = {
'total': total_staff,
'by_level': staff_counts
}
# Count registered nicknames
cursor.execute("SELECT COUNT(*) as count FROM registered_nicks")
stats['registered_nicks'] = cursor.fetchone()['count']
# Count registered channels
cursor.execute("SELECT COUNT(*) as count FROM registered_channels")
stats['registered_channels'] = cursor.fetchone()['count']
# Count server access entries (bans) - exclude expired
now = int(time.time())
cursor.execute("""
SELECT COUNT(*) as count, type
FROM server_access
WHERE timeout = 0 OR timeout > ?
GROUP BY type
""", (now,))
access_counts = {}
for row in cursor.fetchall():
access_counts[row['type']] = row['count']
stats['server_access'] = access_counts
# Count unread messages
cursor.execute("SELECT COUNT(*) as count FROM mailbox WHERE read = 0")
stats['unread_mailbox'] = cursor.fetchone()['count']
# Count newsflash items
cursor.execute("SELECT COUNT(*) as count FROM newsflash")
stats['newsflash_count'] = cursor.fetchone()['count']
# Count memos
cursor.execute("SELECT COUNT(*) as count FROM memos WHERE read = 0")
stats['unread_memos'] = cursor.fetchone()['count']
# Read runtime status from JSON file (after db context)
status_file = os.path.join(os.path.dirname(db_path), 'pyircx_status.json')
if os.path.exists(status_file):
try:
with open(status_file, 'r') as f:
runtime_status = json.load(f)
stats['connected_users'] = len(runtime_status.get('connected_users', []))
stats['active_channels'] = len(runtime_status.get('active_channels', []))
stats['linked_servers'] = len(runtime_status.get('linked_servers', []))
# Calculate uptime if timestamp is available
if 'timestamp' in runtime_status:
stats['status_timestamp'] = runtime_status['timestamp']
# Get boot time from config or status
if 'boot_time' in runtime_status:
stats['boot_time'] = runtime_status['boot_time']
stats['uptime_seconds'] = int(time.time() - runtime_status['boot_time'])
# Get peak users if available
if 'peak_users' in runtime_status:
stats['peak_users'] = runtime_status['peak_users']
stats['server_running'] = True
except (json.JSONDecodeError, IOError) as e:
# Status file exists but couldn't be read
stats['server_running'] = False
stats['connected_users'] = 0
stats['active_channels'] = 0
stats['linked_servers'] = 0
else:
# No status file = server not running
stats['server_running'] = False
stats['connected_users'] = 0
stats['active_channels'] = 0
stats['linked_servers'] = 0
return stats
# ============================================================================
# SERVER ACCESS MANAGEMENT
# ============================================================================
@api_error_handler
def get_server_access_list():
"""Get all server access rules (bans)"""
with db_pool.get_connection() as conn:
cursor = conn.cursor()
cursor.execute("""
SELECT type, pattern, set_by, set_at, timeout, reason
FROM server_access
ORDER BY set_at DESC
""")
rules = []
current_time = int(time.time())
for row in cursor.fetchall():
timeout = row['timeout'] if row['timeout'] else 0
expired = timeout > 0 and current_time > timeout
rules.append({
'type': row['type'],
'pattern': row['pattern'],
'set_by': row['set_by'],
'set_at': row['set_at'],
'timeout': timeout,
'reason': row['reason'],
'expired': expired
})
return rules
@api_error_handler
def add_server_access(access_type, pattern, set_by, reason, timeout=0):
"""Add a server access rule (ban)
Args:
timeout: Duration in minutes (0 = permanent), will be converted to absolute timestamp
"""
# Validate inputs
validate_access_type(access_type)
validate_pattern(pattern)
validate_timeout(timeout)
with db_pool.get_connection() as conn:
cursor = conn.cursor()
set_at = int(time.time())
# Convert duration in minutes to absolute timestamp
# 0 means permanent (no expiry)
duration_minutes = int(timeout) if timeout else 0
if duration_minutes > 0:
timeout_val = set_at + (duration_minutes * 60)
else:
timeout_val = 0
cursor.execute("""
INSERT INTO server_access (type, pattern, set_by, set_at, timeout, reason)
VALUES (?, ?, ?, ?, ?, ?)
""", (access_type, pattern, set_by, set_at, timeout_val, reason))
return {"success": True, "message": SERVER_MESSAGES['api_server_access_added'].format(access_type=access_type, pattern=pattern)}
@api_error_handler
def remove_server_access(access_type, pattern):
"""Remove a server access rule"""
# Validate inputs
validate_access_type(access_type)
validate_pattern(pattern)
with db_pool.get_connection() as conn:
cursor = conn.cursor()
cursor.execute("""
DELETE FROM server_access WHERE type = ? AND pattern = ?
""", (access_type, pattern))
rows_affected = cursor.rowcount
if rows_affected > 0:
return {"success": True, "message": SERVER_MESSAGES['api_server_access_removed'].format(access_type=access_type, pattern=pattern)}
else:
return {"error": SERVER_MESSAGES['api_server_access_not_found'].format(pattern=pattern)}
# ============================================================================
# NEWSFLASH MANAGEMENT
# ============================================================================
@api_error_handler
def get_newsflash_list():
"""Get all NewsFlash messages"""
with db_pool.get_connection() as conn:
cursor = conn.cursor()
cursor.execute("""
SELECT id, message, priority, created_by, created_at
FROM newsflash
ORDER BY priority DESC, created_at DESC
""")
newsflash = []
for row in cursor.fetchall():
newsflash.append({
'id': row['id'],
'message': row['message'],
'priority': row['priority'],
'created_by': row['created_by'],
'created_at': row['created_at']
})
return newsflash
@api_error_handler
def add_newsflash(message, created_by, priority=0):
"""Add a NewsFlash message"""
# Validate inputs
if not message or len(message) > 500:
raise ValueError(SERVER_MESSAGES['api_newsflash_message_required'])
if priority < 0 or priority > 10:
raise ValueError(SERVER_MESSAGES['api_newsflash_priority_invalid'])
with db_pool.get_connection() as conn:
cursor = conn.cursor()
created_at = int(time.time())
cursor.execute("""
INSERT INTO newsflash (message, created_by, created_at, priority)
VALUES (?, ?, ?, ?)
""", (message, created_by, created_at, priority))
return {"success": True, "message": SERVER_MESSAGES['api_newsflash_added']}
@api_error_handler
def delete_newsflash(msg_id):
"""Delete a NewsFlash message"""
# Validate input
if not msg_id or int(msg_id) < 1:
raise ValueError(SERVER_MESSAGES['api_newsflash_id_invalid'])
with db_pool.get_connection() as conn:
cursor = conn.cursor()
cursor.execute("DELETE FROM newsflash WHERE id = ?", (int(msg_id),))
rows_affected = cursor.rowcount
if rows_affected > 0:
return {"success": True, "message": SERVER_MESSAGES['api_newsflash_deleted']}
else:
return {"error": SERVER_MESSAGES['api_newsflash_not_found'].format(msg_id=msg_id)}
# ============================================================================
# MAILBOX VIEWING
# ============================================================================
@api_error_handler
def get_mailbox_messages(limit=50):
"""Get recent mailbox messages"""
with db_pool.get_connection() as conn:
cursor = conn.cursor()
cursor.execute("""
SELECT m.id, m.sender_nick, m.message, m.sent_at, m.read,
rn.nickname as recipient
FROM mailbox m
LEFT JOIN registered_nicks rn ON m.recipient_uuid = rn.uuid
ORDER BY m.sent_at DESC
LIMIT ?
""", (limit,))
messages = []
for row in cursor.fetchall():
messages.append({
'id': row['id'],
'sender': row['sender_nick'],
'recipient': row['recipient'] if row['recipient'] else 'Unknown',
'message': row['message'],
'sent_at': row['sent_at'],
'read': bool(row['read'])
})
return messages
@api_error_handler
def send_mailbox_message(sender_nick, recipient_nick, message):
"""Send a mailbox message to a registered nickname
Args:
sender_nick: Sender's nickname
recipient_nick: Recipient's registered nickname
message: Message content
Returns:
dict with success/error status
"""
# Validate inputs
if not sender_nick or len(sender_nick) > 30:
raise ValueError(SERVER_MESSAGES['api_sender_nick_required'])
if not message or len(message) > 500:
raise ValueError(SERVER_MESSAGES['api_newsflash_message_required'])
validate_nickname(recipient_nick)
with db_pool.get_connection() as conn:
cursor = conn.cursor()
# Look up recipient's UUID in registered_nicks
cursor.execute("SELECT uuid FROM registered_nicks WHERE LOWER(nickname) = LOWER(?)", (recipient_nick,))
recipient_row = cursor.fetchone()
if not recipient_row:
# Auto-create registered_nicks entry for recipient
# This allows sending messages to any nickname via webadmin
import uuid as uuid_mod
recipient_uuid = str(uuid_mod.uuid4())
now = int(time.time())
cursor.execute("""
INSERT INTO registered_nicks (uuid, nickname, password_hash, registered_at, last_seen, registered_by)
VALUES (?, ?, ?, ?, ?, ?)
""", (recipient_uuid, recipient_nick, "", now, now, "AUTO (mailbox)"))
logger.info(get_log_message("api_auto_nick_mailbox", nickname=recipient_nick, sender=sender_nick))
else:
recipient_uuid = recipient_row[0]
sent_at = int(time.time())
# Insert message
cursor.execute("""
INSERT INTO mailbox (sender_nick, recipient_uuid, message, sent_at, read)
VALUES (?, ?, ?, ?, 0)
""", (sender_nick, recipient_uuid, message, sent_at))
return {"success": True, "message": SERVER_MESSAGES['api_mailbox_sent'].format(recipient_nick=recipient_nick)}
@api_error_handler
def delete_mailbox_message(message_id):
"""Delete a mailbox message by ID"""
with db_pool.get_connection() as conn:
cursor = conn.cursor()
# Check if message exists
cursor.execute("SELECT id FROM mailbox WHERE id = ?", (message_id,))
if not cursor.fetchone():
return {"error": SERVER_MESSAGES['api_mailbox_not_found'].format(message_id=message_id)}
# Delete the message
cursor.execute("DELETE FROM mailbox WHERE id = ?", (message_id,))
return {"success": True, "message": SERVER_MESSAGES['api_mailbox_deleted'].format(message_id=message_id)}
# ============================================================================
# SEARCH FUNCTIONS
# ============================================================================
@api_error_handler
def search_registered_nicks(query):
"""Search registered nicknames"""
with db_pool.get_connection() as conn:
cursor = conn.cursor()
cursor.execute("""
SELECT nickname, registered_at, last_seen, mfa_enabled, email
FROM registered_nicks
WHERE nickname LIKE ?
ORDER BY nickname
LIMIT 50
""", (f"%{query}%",))
results = []
for row in cursor.fetchall():
results.append({
'nickname': row['nickname'],
'registered_at': row['registered_at'],
'last_seen': row['last_seen'],
'mfa_enabled': bool(row['mfa_enabled']),
'email': row['email'] if row['email'] else 'Not set'
})
return results
@api_error_handler
def search_channels(query):
"""Search registered channels from registered_channels table"""
with db_pool.get_connection() as conn:
cursor = conn.cursor()
# Search registered_channels table
cursor.execute("""
SELECT channel_name, registered_at, last_used,
(SELECT nickname FROM registered_nicks WHERE uuid = registered_channels.owner_uuid) as owner
FROM registered_channels
WHERE channel_name LIKE ?
ORDER BY channel_name
LIMIT 50
""", (f"%{query}%",))
results = []
for row in cursor.fetchall():
# Use indices instead of keys to avoid issues with UNION
results.append({
'name': row[0], # channel_name
'registered_at': row[1], # registered_at
'last_used': row[2], # last_used
'owner': row[3] if row[3] else 'Unknown' # owner
})
return results
# ============================================================================
# EXISTING FUNCTIONS (keeping for compatibility)
# ============================================================================
@api_error_handler
def get_recent_registrations(limit=10):
"""Get recently registered nicknames"""
with db_pool.get_connection() as conn:
cursor = conn.cursor()
cursor.execute("""
SELECT nickname, registered_at, last_seen, mfa_enabled
FROM registered_nicks