-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsuperuserScript.py
853 lines (760 loc) · 31.7 KB
/
superuserScript.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
import os, sys, json, datetime, requests, time
from pprint import pprint
from getpass import getpass
print("Welcome to the MakanMatch System Superuser Console.")
print("With this script, easily manage admin accounts and operational settings of a MakanMatch Backend system.")
print()
# Define the base URL of the Key Server
baseURL = input("Enter MakanMatch system location (e.g. http://localhost:5000): ")
if baseURL == "":
baseURL = "https://makanmatchb.prakhar.app"
serverPath = lambda path: baseURL + path
headers = {
"Content-Type": "application/json"
}
serverKey = None
# Check connection to the MakanMatch System
print()
print("Checking connection to server...")
try:
healthCheck = requests.get(serverPath("/admin/super"))
healthCheck.raise_for_status()
if not healthCheck.text.startswith("SUCCESS"):
print("ERROR: MakanMatch Superuser API is not healthy.")
sys.exit(1)
print("Connection successful!")
except Exception as e:
print("ERROR: Could not connect to MakanMatch system. Error: " + str(e))
sys.exit(1)
# Authenticate using server admin credentials
print()
serverKey = input("Enter superuser access key: ")
while True:
print()
print("Authorising...")
headers["AccessKey"] = serverKey
authResponse = None
try:
authResponse = requests.post(
url=serverPath("/admin/super/authenticate"),
headers=headers
)
authResponse.raise_for_status()
if authResponse.text.startswith("ERROR"):
raise Exception(authResponse.text[len("ERROR: "):])
if not authResponse.text.startswith("SUCCESS"):
raise Exception("Unknown response received: " + authResponse.text)
print("Authorised successfully!")
break
except Exception as e:
del headers["AccessKey"]
print("Error occurred in authenticating with server. Error: " + str(e))
try:
print("Server response: " + authResponse.text)
except:
print("Server response: <No response>")
retry = input("Retry? (y/n): ").lower()
if retry != "y":
sys.exit(1)
print()
serverKey = input("Enter superuser access key: ")
continue
# Start main functions
def retrieveAccountInfo():
print()
identifierType = input("Enter identifier type (ID/username/email): ").strip().lower()
while identifierType not in ["id", "username", "email"]:
identifierType = input("Invalid identifier type. Enter identifier type (ID/username/email): ").strip().lower()
data = {}
if identifierType == "id":
data["userID"] = input("Enter user ID: ").strip()
while data["userID"] == "":
data["userID"] = input("User ID cannot be empty. Please enter a user ID: ").strip()
elif identifierType == "username":
data["username"] = input("Enter username: ").strip()
while data["username"] == "":
data["username"] = input("Username cannot be empty. Please enter a username: ").strip()
else:
data["email"] = input("Enter email: ").strip()
while data["email"] == "":
data["email"] = input("Email cannot be empty. Please enter an email: ").strip()
print()
print("Retrieving account information...")
retrieveResponse = None
while True:
try:
retrieveResponse = requests.post(
url=serverPath("/admin/super/accountInfo"),
headers=headers,
json=data
)
retrieveResponse.raise_for_status()
if retrieveResponse.text.startswith("ERROR"):
raise Exception(retrieveResponse.text[len("ERROR: "):])
elif retrieveResponse.text.startswith("UERROR"):
raise Exception(retrieveResponse.text[len("UERROR: "):])
print("Account information retrieved successfully!")
print()
responseJSON = json.loads(retrieveResponse.text)
print("Retrieved information:")
for key in responseJSON:
print("\t{}: {}".format(key, responseJSON[key]))
break
except Exception as e:
print("Error occurred in retrieving account information. Error: " + str(e))
try:
print("Server response: " + retrieveResponse.text)
except:
print("Server response: <No response>")
retry = input("Retry? (y/n): ").lower()
print()
if retry != "y":
print("Retrieve account information aborted.")
break
print("Retrieving account information...")
def createAdmin():
print()
username = input("Enter username for new MakanMatch admin: ").strip()
while username == "":
username = input("Username cannot be empty. Please enter a username: ").strip()
fname = input("Enter first name: ").strip()
while fname == "" or not fname.isalpha():
fname = input("Invalid first name. Please re-enter: ").strip()
lname = input("Enter last name: ").strip()
while lname == "" or not lname.isalpha():
lname = input("Invalid last name. Please re-enter: ").strip()
email = input("Enter email: ").strip()
while email == "" or "@" not in email:
email = input("Invalid email. Please re-enter: ").strip()
password = getpass("Enter password: ").strip()
while password == "":
password = getpass("Password cannot be empty. Please enter a password: ").strip()
confirm = getpass("Confirm password: ").strip()
while confirm != password:
confirm = getpass("Passwords do not match. Please confirm password: ").strip()
role = input("Enter admin's role: ").strip()
while role == "":
role = input("Role cannot be empty. Please enter a role: ").strip()
print()
print("Creating admin account...")
createResponse = None
while True:
try:
createResponse = requests.post(
url=serverPath("/admin/super/createAdmin"),
headers=headers,
json={
"username": username,
"fname": fname,
"lname": lname,
"email": email,
"password": password,
"role": role
}
)
createResponse.raise_for_status()
if createResponse.text.startswith("ERROR"):
raise Exception(createResponse.text[len("ERROR: "):])
elif createResponse.text.startswith("UERROR"):
raise Exception(createResponse.text[len("UERROR: "):])
if not createResponse.text.startswith("SUCCESS"):
raise Exception("Unknown response received: " + createResponse.text)
print("Admin account created successfully! Username: '{}', Password: '{}'.".format(username, password))
break
except Exception as e:
print("Error occurred in creating admin account. Error: " + str(e))
try:
print("Server response: " + createResponse.text)
except:
print("Server response: <No response>")
retry = input("Retry? (y/n): ").lower()
print()
if retry != "y":
print("Create account aborted.")
break
print("Creating admin account...")
def deleteAdmin():
print()
identifierType = input("Enter identifier type (ID/username/email): ").strip().lower()
while identifierType not in ["id", "username", "email"]:
identifierType = input("Invalid identifier type. Enter identifier type (ID/username/email): ").strip().lower()
data = {}
if identifierType == "id":
data["userID"] = input("Enter admin ID: ").strip()
while data["userID"] == "":
data["id"] = input("Admin ID cannot be empty. Please enter an admin ID: ").strip()
elif identifierType == "username":
data["username"] = input("Enter admin username: ").strip()
while data["username"] == "":
data["username"] = input("Username cannot be empty. Please enter a username: ").strip()
else:
data["email"] = input("Enter admin email: ").strip()
while data["email"] == "":
data["email"] = input("Email cannot be empty. Please enter an email: ").strip()
print()
print("Deleting admin account...")
deleteResponse = None
while True:
try:
deleteResponse = requests.post(
url=serverPath("/admin/super/deleteAdmin"),
headers=headers,
json=data
)
deleteResponse.raise_for_status()
if deleteResponse.text.startswith("ERROR"):
raise Exception(deleteResponse.text[len("ERROR: "):])
elif deleteResponse.text.startswith("UERROR"):
raise Exception(deleteResponse.text[len("UERROR: "):])
if not deleteResponse.text.startswith("SUCCESS"):
raise Exception("Unknown response received: " + deleteResponse.text)
print("Admin account deleted successfully!")
break
except Exception as e:
print("Error occurred in deleting admin account. Error: " + str(e))
try:
print("Server response: " + deleteResponse.text)
except:
print("Server response: <No response>")
retry = input("Retry? (y/n): ").lower()
print()
if retry != "y":
print("Delete account aborted.")
break
print("Deleting admin account...")
def retrieveAnalytics():
print()
print("Retrieving analytics...")
analyticsResponse = None
responseJSON = None
while True:
try:
analyticsResponse = requests.post(
url=serverPath("/admin/super/getAnalytics"),
headers=headers
)
analyticsResponse.raise_for_status()
if analyticsResponse.text.startswith("ERROR"):
raise Exception(analyticsResponse.text[len("ERROR: "):])
print("Analytics retrieved successfully!")
print()
responseJSON = json.loads(analyticsResponse.text)
print("Retrieved analytics:")
print()
pprint(responseJSON)
print()
break
except Exception as e:
print("Error occurred in retrieving analytics. Error: " + str(e))
try:
print("Server response: " + analyticsResponse.text)
except:
print("Server response: <No response>")
retry = input("Retry? (y/n): ").lower()
print()
if retry != "y":
print("Retrieve analytics aborted.")
break
print("Retrieving analytics...")
print()
saveAnalyticsToFile = input("Save analytics data to file? (y/n) ").strip().lower()
while saveAnalyticsToFile not in ["y", "n"]:
saveAnalyticsToFile = input("Invalid choice. Save analytics data to file? (y/n) ").strip().lower()
if saveAnalyticsToFile == "y":
print()
print("Saving analytics data to file...")
with open("MakanMatchAnalytics.json", "w") as f:
json.dump(responseJSON, f)
print("Analytics data saved to MakanMatchAnalytics.json.")
def retrieveFileManagerContext():
print()
print("Retrieving file manager context...")
contextResponse = None
while True:
try:
contextResponse = requests.get(
url=serverPath("/admin/super/getFileManagerContext"),
headers=headers
)
contextResponse.raise_for_status()
if contextResponse.text.startswith("ERROR"):
raise Exception(contextResponse.text[len("ERROR: "):])
print("File manager context retrieved successfully!")
print()
responseJSON = json.loads(contextResponse.text)
print("Retrieved file manager context:")
print()
pprint(responseJSON)
print()
break
except Exception as e:
print("Error occurred in retrieving file manager context. Error: " + str(e))
try:
print("Server response: " + contextResponse.text)
except:
print("Server response: <No response>")
retry = input("Retry? (y/n): ").lower()
print()
if retry != "y":
print("Retrieve file manager context aborted.")
return
print("Retrieving file manager context...")
saveToFile = input("Save file manager context to file? (y/n) ").strip().lower()
if saveToFile == "y":
print()
print("Saving file manager context to file...")
with open("MakanMatchFileManagerContext.json", "w") as f:
json.dump(responseJSON, f)
print("File manager context saved to MakanMatchFileManagerContext.json.")
def accessMakanMatchLogs():
print()
print("Accessing MakanMatch system logs...")
logsResponse = None
while True:
try:
logsResponse = requests.post(
url=serverPath("/admin/super/getLogs"),
headers=headers
)
logsResponse.raise_for_status()
if logsResponse.text.startswith("ERROR"):
raise Exception(logsResponse.text[len("ERROR: "):])
print("Logs retrieved successfully!")
print()
break
except Exception as e:
print("Error occurred in accessing MakanMatch system logs. Error: " + str(e))
try:
print("Server response: " + logsResponse.text)
except:
print("Server response: <No response>")
retry = input("Retry? (y/n): ").lower()
print()
if retry != "y":
print("Access logs aborted.")
return
print("Accessing MakanMatch system logs...")
try:
logs = logsResponse.json()
print("Logs:")
for log in logs:
print("\t" + log)
except Exception as e:
print("Failed to parse logs. Error: " + str(e))
print("Raw logs:")
print(logsResponse.text)
return
print()
saveLogsToFile = input("Save logs to file? (y/n) ").lower()
while saveLogsToFile not in ["y", "n"]:
saveLogsToFile = input("Invalid choice. Save logs to file? (y/n) ").lower()
if saveLogsToFile == "y":
print()
print("Saving logs to file...")
with open("MakanMatchLogs.txt", "w") as f:
f.write("\n".join(logs))
print("Logs saved to MakanMatchLogs.txt.")
def toggleAnalytics():
print()
toggleStatus = input("Enable analytics? (y/n) ").strip().lower()
while toggleStatus not in ["y", "n"]:
toggleStatus = input("Invalid choice. Enable analytics? (y/n) ").strip().lower()
toggleStatus = toggleStatus == "y"
print()
print("Toggling analytics...")
toggleResponse = None
while True:
try:
toggleResponse = requests.post(
url=serverPath("/admin/super/toggleAnalytics"),
headers=headers,
json={
"newStatus": toggleStatus
}
)
toggleResponse.raise_for_status()
if toggleResponse.text.startswith("ERROR"):
raise Exception(toggleResponse.text[len("ERROR: "):])
elif toggleResponse.text.startswith("UERROR"):
raise Exception(toggleResponse.text[len("UERROR: "):])
if not toggleResponse.text.startswith("SUCCESS"):
raise Exception("Unknown response received: " + toggleResponse.text)
print("Analytics toggled successfully! Server: {}".format(toggleResponse.text))
break
except Exception as e:
print("Error occurred in toggling analytics. Error: " + str(e))
try:
print("Server response: " + toggleResponse.text)
except:
print("Server response: <No response>")
retry = input("Retry? (y/n): ").lower()
print()
if retry != "y":
print("Toggle analytics aborted.")
break
print("Toggling analytics...")
def toggleOpenAIChat():
print()
toggleStatus = input("Enable MakanBot (OpenAI Chat)? (y/n) ").strip().lower()
while toggleStatus not in ["y", "n"]:
toggleStatus = input("Invalid choice. Enable MakanBot (OpenAI Chat)? (y/n) ").strip().lower()
toggleStatus = toggleStatus == "y"
print()
print("Toggling MakanBot (OpenAI Chat)...")
toggleResponse = None
while True:
try:
toggleResponse = requests.post(
url=serverPath("/admin/super/toggleMakanBot"),
headers=headers,
json={
"newStatus": toggleStatus
}
)
toggleResponse.raise_for_status()
if toggleResponse.text.startswith("ERROR"):
raise Exception(toggleResponse.text[len("ERROR: "):])
elif toggleResponse.text.startswith("UERROR"):
raise Exception(toggleResponse.text[len("UERROR: "):])
if not toggleResponse.text.startswith("SUCCESS"):
raise Exception("Unknown response received: " + toggleResponse.text)
print("MakanBot (OpenAI Chat) toggled successfully! Server: {}".format(toggleResponse.text))
break
except Exception as e:
print("Error occurred in toggling MakanBot (OpenAI Chat). Error: " + str(e))
try:
print("Server response: " + toggleResponse.text)
except:
print("Server response: <No response>")
retry = input("Retry? (y/n): ").lower()
print()
if retry != "y":
print("Toggle MakanBot (OpenAI Chat) aborted.")
break
print("Toggling MakanBot (OpenAI Chat)...")
def toggleUsageLock():
print()
lockStatus = input("Lock system usage? (y/n) ").strip().lower()
while lockStatus not in ["y", "n"]:
lockStatus = input("Invalid choice. Lock system usage? (y/n) ").strip().lower()
lockStatus = lockStatus == "y"
print()
print("Toggling usage lock...")
toggleResponse = None
while True:
try:
toggleResponse = requests.post(
url=serverPath("/admin/super/toggleUsageLock"),
headers=headers,
json={
"newStatus": lockStatus
}
)
toggleResponse.raise_for_status()
if toggleResponse.text.startswith("ERROR"):
raise Exception(toggleResponse.text[len("ERROR: "):])
elif toggleResponse.text.startswith("UERROR"):
raise Exception(toggleResponse.text[len("UERROR: "):])
if not toggleResponse.text.startswith("SUCCESS"):
raise Exception("Unknown response received: " + toggleResponse.text)
print("Usage lock toggled successfully! Server: {}".format(toggleResponse.text))
break
except Exception as e:
print("Error occurred in toggling usage lock. Error: " + str(e))
try:
print("Server response: " + toggleResponse.text)
except:
print("Server response: <No response>")
retry = input("Retry? (y/n): ").lower()
print()
if retry != "y":
print("Toggle usage lock aborted.")
break
print("Toggling usage lock...")
def toggleSuperuserSensitive():
print()
print("Toggling superuser sensitive mode...")
toggleResponse = None
while True:
try:
toggleResponse = requests.post(
url=serverPath("/admin/super/toggleSuperuserSensitive"),
headers=headers
)
toggleResponse.raise_for_status()
if toggleResponse.text.startswith("ERROR"):
raise Exception(toggleResponse.text[len("ERROR: "):])
elif toggleResponse.text.startswith("UERROR"):
raise Exception(toggleResponse.text[len("UERROR: "):])
if not toggleResponse.text.startswith("SUCCESS"):
raise Exception("Unknown response received: " + toggleResponse.text)
print("Superuser sensitive mode toggled successfully! Server: {}".format(toggleResponse.text))
break
except Exception as e:
print("Error occurred in toggling superuser sensitive mode. Error: " + str(e))
try:
print("Server response: " + toggleResponse.text)
except:
print("Server response: <No response>")
retry = input("Retry? (y/n): ").lower()
print()
if retry != "y":
print("Toggle superuser sensitive mode aborted.")
break
print("Toggling superuser sensitive mode...")
def clearFM():
print()
if input("This is a sensitive action and could cripple system operation? Continue? (y/n) ").lower() != "y":
print("Clear FileManager aborted.")
return
print("Clearing file manager...")
clearResponse = None
while True:
try:
clearResponse = requests.post(
url=serverPath("/admin/super/clearFM"),
headers=headers
)
clearResponse.raise_for_status()
if clearResponse.text.startswith("ERROR"):
raise Exception(clearResponse.text[len("ERROR: "):])
elif clearResponse.text.startswith("UERROR"):
raise Exception(clearResponse.text[len("UERROR: "):])
if not clearResponse.text.startswith("SUCCESS"):
raise Exception("Unknown response received: " + clearResponse.text)
print("File manager cleared successfully! Server: {}".format(clearResponse.text))
break
except Exception as e:
print("Error occurred in clearing file manager. Error: " + str(e))
try:
print("Server response: " + clearResponse.text)
except:
print("Server response: <No response>")
retry = input("Retry? (y/n): ").lower()
print()
if retry != "y":
print("Clear file manager aborted.")
break
print("Clearing file manager...")
def softReset():
print()
if input("This is a sensitive action and could cripple system operation? Continue? (y/n) ").lower() != "y":
print("Soft reset aborted.")
return
print("Soft resetting system database...")
while True:
try:
resetResponse = requests.post(
url=serverPath("/admin/super/softReset"),
headers=headers
)
resetResponse.raise_for_status()
if resetResponse.text.startswith("ERROR"):
raise Exception(resetResponse.text[len("ERROR: "):])
elif resetResponse.text.startswith("UERROR"):
raise Exception(resetResponse.text[len("UERROR: "):])
if not resetResponse.text.startswith("SUCCESS"):
raise Exception("Unknown response received: " + resetResponse.text)
print("System database soft reset successfully! Server: {}".format(resetResponse.text))
break
except Exception as e:
print("Error occurred in soft resetting system database. Error: " + str(e))
try:
print("Server response: " + resetResponse.text)
except:
print("Server response: <No response>")
retry = input("Retry? (y/n): ").lower()
print()
if retry != "y":
print("Soft reset aborted.")
break
print("Soft resetting system database...")
def presentationTransform():
print()
if input("This is a sensitive action and could cripple system operation? Continue? (y/n) ").lower() != "y":
print("Presentation transform aborted.")
return
print("Transforming system database for presentation...")
while True:
try:
transformResponse = requests.post(
url=serverPath("/admin/super/presentationTransform"),
headers=headers
)
transformResponse.raise_for_status()
if transformResponse.text.startswith("ERROR"):
raise Exception(transformResponse.text[len("ERROR: "):])
elif transformResponse.text.startswith("UERROR"):
raise Exception(transformResponse.text[len("UERROR: "):])
responseJSON = json.loads(transformResponse.text)
print("Transformation messages:")
print()
if responseJSON["messages"]:
for message in responseJSON["messages"]:
print(message)
else:
print("Could not parse messages.")
print()
print("System database transformation for presentation successfully!")
break
except Exception as e:
print("Error occurred in transforming system database for presentation. Error: " + str(e))
try:
print("Server response: " + transformResponse.text)
except:
print("Server response: <No response>")
retry = input("Retry? (y/n): ").lower()
print()
if retry != "y":
print("Transformation aborted.")
break
print("Transforming system database for presentation...")
class Logger:
@staticmethod
def readAll():
try:
if os.path.exists(os.path.join(os.getcwd(), "MakanMatchLogs.txt")):
with open("MakanMatchLogs.txt", "r") as f:
logs = f.readlines()
for logIndex in range(len(logs)):
logs[logIndex] = logs[logIndex].replace("\n", "")
return logs
else:
return []
except Exception as e:
print("LOGGER READALL ERROR: Failed to check and read MakanMatchLogs.txt file. Error: {}".format(e))
return "ERROR: Failed to check and read MakanMatchLogs.txt file. Error: {}".format(e)
@staticmethod
def manageLogs():
print("LOGGER: Welcome to the Logging Management Console.")
while True:
print("""
Commands:
read <number of lines, e.g 50 (optional)>: Reads the last <number of lines> of logs. If no number is specified, all logs will be displayed.
exit: Exit the Logging Management Console.
""")
userChoice = input("Enter command: ")
userChoice = userChoice.lower()
while not userChoice.startswith("read") and (userChoice != "destroy") and (userChoice != "exit"):
userChoice = input("Invalid command. Enter command: ")
userChoice = userChoice.lower()
if userChoice.startswith("read"):
allLogs = Logger.readAll()
targetLogs = []
userChoice = userChoice.split(" ")
# Log filtering feature
if len(userChoice) == 1:
targetLogs = allLogs
elif userChoice[1] == ".filter":
if len(userChoice) < 3:
print("Invalid log filter. Format: read .filter <keywords>")
continue
else:
try:
keywords = userChoice[2:]
for log in allLogs:
logTags = log[23::]
logTags = logTags[:logTags.find(":")].upper().split(" ")
## Check if log contains all keywords
containsAllKeywords = True
for keyword in keywords:
if keyword.upper() not in logTags:
containsAllKeywords = False
break
if containsAllKeywords:
targetLogs.append(log)
print("Filtered logs with keywords: {}".format(keywords))
print()
except Exception as e:
print("LOGGER: Failed to parse and filter logs. Error: {}".format(e))
continue
else:
logCount = 0
try:
logCount = int(userChoice[1])
if logCount > len(allLogs):
logCount = len(allLogs)
elif logCount <= 0:
raise Exception("Invalid log count. Must be a positive integer above 0 lower than or equal to the total number of logs.")
targetLogs = allLogs[-logCount::]
except Exception as e:
print("LOGGER: Failed to read logs. Error: {}".format(e))
continue
logCount = len(targetLogs)
print()
print("Displaying {} log entries:".format(logCount))
print()
for log in targetLogs:
print("\t{}".format(log))
elif userChoice == "exit":
print("LOGGER: Exiting Logging Management Console...")
break
return
while True:
print("""
What would you like to do?
1. Retrieve an account's information
2. Create a new admin account
3. Delete an existing admin account
4. Retrieve collected analytics
5. Retrieve system logs
6. Retrieve FileManager context
7. Toggle analytics
8. Toggle MakanBot (OpenAIChat)
9. Toggle usage lock
10. Toggle superuser sensitive mode
11. Clear FileManager
12. Soft reset system
13. Transform system database for presentation
14. Activate Logs Console
0. Exit
""")
choice = input("Enter your choice: ")
while (not choice.isdigit()) or (int(choice) not in range(0, 15)):
choice = input("Invalid choice. Please enter your choice: ")
choice = int(choice)
if choice == 1:
retrieveAccountInfo()
print()
elif choice == 2:
createAdmin()
print()
elif choice == 3:
deleteAdmin()
print()
elif choice == 4:
retrieveAnalytics()
print()
elif choice == 5:
accessMakanMatchLogs()
print()
elif choice == 6:
retrieveFileManagerContext()
print()
elif choice == 7:
toggleAnalytics()
print()
elif choice == 8:
toggleOpenAIChat()
print()
elif choice == 9:
toggleUsageLock()
print()
elif choice == 10:
toggleSuperuserSensitive()
print()
elif choice == 11:
clearFM()
print()
elif choice == 12:
softReset()
print()
elif choice == 13:
presentationTransform()
print()
elif choice == 14:
Logger.manageLogs()
print()
else:
print("Bye!")
break