This repository was archived by the owner on Jul 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrowser.py
More file actions
4032 lines (3553 loc) · 160 KB
/
browser.py
File metadata and controls
4032 lines (3553 loc) · 160 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
# -*- coding: utf-8 -*-
"""
-------------------------------
MSDAC Systems - Hymnal Browser
-------------------------------
A general hymnal browser for Seventh-day Adventist Church (formerly for Montevilla SDA Church)
Supports up to 474 Hymns based on SDA Hymnal Philippine Edition.
This module provides all functionality of operating and executing .pptx files,
configurations, and statistical data.
Pre-requisites:
- Microsoft(c) Office 2016 and above
Spacing Gap Formats:
• Class - 3 to 4 lines
• Functions - 2 to 3 lines
• Comments - 1 line
Tested working on:
Windows 10 -
• MS Office 2013
• MS Office 2019
• MS Office 2021
Windows 11 -
• MS Office 2021
This software is part of MSDAC System's collection of softwares
(c) 2021-present Ken Verdadero, Reynald Ycong
"""
import os
## Import Modules
import sys
from typing import Type
try:
import bz2
import configparser
import csv
import gc
import json
import operator
import shutil
import socket
import subprocess
import time
import winreg
from collections import namedtuple
from datetime import datetime, timedelta
from subprocess import DEVNULL
from threading import Thread
from zipfile import ZipFile
import dotenv
import humanize
import keyboard
import psutil
import pymongo
import requests
from BlurWindow import blurWindow
from kenverdadero.KCore import KPath, KString, KSystem, KTime
from kenverdadero.KCore.KCore import (
calcTimeExec,
convertDataUnit,
getFilename,
getFileStat,
getSize,
invert,
modHex,
nL,
p,
tP,
)
from kenverdadero.KLogging import KLog
from kenverdadero.KSoftware import KSoftware
from pptx import Presentation
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QEasingCurve, Qt
from PyQt5.QtGui import QFont
except ImportError as e:
print("System Error: " + str(e))
sys.exit()
class System:
"""
System Class Handler
This handles all system responsibilities for the browser such as:
- System properties
- Verifying all required files and directory
- Duplicate instances
- Background Tasks
- Application exit event
"""
def __init__(self):
"""
All variables have the following format:
self.TYPE_NAME_ATTRIBUTE_SUBATTR
Example: self.SOFTWARE_HYMNALBROWSER_UI_SETTINGS
"""
_DIR_TEMP_SUB = namedtuple("DIR_TEMP_SUB", "EN TL")
_RECENTS = namedtuple("RECENTS", "DEFAULT ALLOWEDMIN ALLOWEDMAX")
## External File and Directories
self.DIR_PARENT = r"C:\ProgramData\MSDAC Systems"
self.DIR_PROGRAM = self.DIR_PARENT + r"\Hymnal Browser"
self.DIR_TEMP = self.DIR_PROGRAM + r"\Temp"
self.DIR_LOG = self.DIR_TEMP + r"\Logs"
self.DIR_TEMP_SUB = _DIR_TEMP_SUB(
self.DIR_TEMP + r"\EN", self.DIR_TEMP + r"\TL"
)
self.FILE_DATA = self.DIR_PROGRAM + r"\data.json"
self.FILE_CONFIG = self.DIR_PROGRAM + r"\config.ini"
self.FILE_HYMNSDB = os.path.join(SW.DIR_CWD, "hymns.sda")
## Internal Directories
self.DIR_RES = "res"
self.DIR_BIN = "bin"
## Resources
self.RES_LOGO = "./res/images/logo.png"
self.RES_FONT_TITLE = "IntegralCF-Regular.otf"
## Properties
self.CURR_THEME = 0
self.HYMNS_MAX = 474 ## Number of Maximum Hymns (Will be deprecated soon due to customized hymns in future updates)
self.RECENTS = _RECENTS(
10, 3, 30
) ## Recent Files Properties: (Default, Minimum Allowed, Maximum Allowed)
self.CPLTR_MAX_VISIBLE_ITEMS = (
10 ## Number of files to be maintained in TEMP_DIR
)
self.PROCESS_NAME = "hymnalbrowser.exe" ## File name
self.USER_NAME = os.getenv("username") ## Get Username of the windows account
self.TBL_STATS_COLUMNS = 5
self.MIN_OPACITY = 50 ## Minimum Opacity of the application
self.PROCESS = psutil.Process(os.getpid())
self.LOG_FILE_LIMIT = 10
self.FORCE_OFFLINE = False
self.EXT_FEEDBACK = "fdback"
self.EXT_TELEMETRY = "tlm"
self.CNT_SESSION_PRESN = 0 ## Session Presentation (PPT) Counter
self.STARTUP_TIME = 0
self.UNIQ_MACHINE_ID = (
subprocess.check_output("wmic csproduct get uuid", shell=True)
.decode()
.split("\n")[1]
.strip()
)
self.HOST_NAME = socket.gethostname()
self.PPT_EXEC = ""
self.DUPLICATED = False
self.WORKER_1: ThreadBackground
## Functions
dotenv.load_dotenv(self.DIR_BIN + "/secrets.env")
def verifyDirectories(self):
"""
This method checks for directories and also generate new if the folders does not exist/
This verifies from parent directory down to subfolders via loop using a dict of directories.
.. - Root
<> - File
-> - Directory
Tree:
.. MSDAC Systems (Parent/Root)
-> Hymnal Browser (Program)
-> Temp (Temporary Folder)
-> English
-> Logs
-> Tagalog
<> Hymnal Files (ends with .pptx)
<> config.ini
-> POWERPNT.exe (MS Office)
"""
DIRECTORIES = {
self.DIR_PARENT: "Parent",
self.DIR_PROGRAM: "Program",
self.DIR_TEMP: "Temporary",
self.DIR_TEMP_SUB.EN: "English",
self.DIR_TEMP_SUB.TL: "Tagalog",
self.DIR_LOG: "Logs",
}
MISSING = 0
for DIR, NAME in DIRECTORIES.items():
if not KPath.exists(DIR, True):
LOG.warn(
f'{NAME} Directory "{DIR}" doesn\'t exist. Creating a new folder.'
)
MISSING += 1
## If Hymnal Database cannot be found
if not KPath.exists(self.FILE_HYMNSDB):
LOG.crit("Cannot find Hymnal database")
MSG_BOX = QtWidgets.QMessageBox()
MSG_BOX.setStandardButtons(QtWidgets.QMessageBox.Ok)
MSG_BOX.setIcon(QtWidgets.QMessageBox.Critical)
MSG_BOX.setWindowTitle("Error")
MSG_BOX.setText(
"Database Failure: Hymnal Database is missing.\nPlease contact the developers of this program to fix the issue."
)
MSG_BOX.setDetailedText(
f"Hymnal Database is non existent in this folder:\n\n{self.FILE_HYMNSDB}"
)
MSG_BOX.setWindowFlags(
Qt.WindowType.Drawer | Qt.WindowType.WindowStaysOnTopHint
)
MSG_BOX.setStyleSheet(Stylesheet().getStylesheet())
MSG_BOX.exec_()
LOG.sys("Program terminated due to an error.")
sys.exit()
if MISSING:
LOG.sys(
f"Verification complete. {MISSING} {KString.isPlural('folder', MISSING)} flagged as missing"
)
else:
LOG.sys("Successfully verified all directories.")
if MISSING == 6:
LOG.sys(
"Detected a first time launch of the application."
) ## Needs improvement
def verifyRequisites(self):
"""
Verifies all required programs to make the software run properly.
This method prevents the program to proceed if a valid Microsoft Office PowerPoint is not found in both 32-bit and 64-bit
"""
try:
self.PPT_EXEC = KPath.upFolder(
winreg.EnumValue(
winreg.OpenKey(
winreg.HKEY_LOCAL_MACHINE,
r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\powerpnt.exe",
),
0,
)[1]
)
LOG.info(
f'Using {"64" if "Program Files (x86)" not in self.PPT_EXEC else "32"}-Bit Version of Microsoft Office'
)
LOG.info(f"Root Dir: {self.PPT_EXEC}")
except FileNotFoundError:
self.showNotInstalledRequisites()
def showNotInstalledRequisites(self):
## No MS Office Installed
LOG.crit("Microsoft Office is not installed")
MSG_BOX = QtWidgets.QMessageBox()
MSG_BOX.setStandardButtons(QtWidgets.QMessageBox.Ok)
MSG_BOX.setIcon(QtWidgets.QMessageBox.Critical)
MSG_BOX.setText(
"Microsoft Office is not installed!\nThis program uses PowerPoint 2010 or later to run properly. \n"
)
MSG_BOX.setDetailedText(
"If you think this is a mistake, please contact the developers for further assistance.\n\nhttps://m.me/verdaderoken\nhttps://m.me/reynald.ycong"
)
MSG_BOX.setWindowTitle("Error")
MSG_BOX.setWindowFlags(
Qt.WindowType.Drawer | Qt.WindowType.WindowStaysOnTopHint
)
MSG_BOX.setStyleSheet(QSS.getStylesheet())
MSG_BOX.exec_()
LOG.sys("Program terminated due to an error.")
sys.exit()
def checkInstances(self):
## Asks the user if they want to run another instance
self.DUPLICATED = False
DUPLICATES = [
i
for i in str(
subprocess.check_output(
["wmic", "process", "list", "brief"], shell=True
)
).split()
if str(i) == SYS.PROCESS_NAME
]
# DUPLICATES = len(list(filter(lambda x: x == SYS.PROCESS_NAME, [i.name() for i in psutil.process_iter()]))) ## < -- Old
if (
len(DUPLICATES) > 2
): ## Set to threshold of 2 because .exe has 2 processes when built
MSG_BOX = QtWidgets.QMessageBox()
MSG_BOX.setStandardButtons(
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No
)
MSG_BOX.setIcon(QtWidgets.QMessageBox.Question)
MSG_BOX.setText(
"The program is already running.\nDo you want to open another instance?"
)
MSG_BOX.setWindowTitle("Duplicate Instance Detected")
MSG_BOX.setWindowFlags(
Qt.WindowType.Drawer | Qt.WindowType.WindowStaysOnTopHint
)
MSG_BOX.setStyleSheet(QSS.getStylesheet())
MSG_BOX.setStyleSheet("min-width: 250px; min-height: 30px;")
LOG.info("Duplicate Instance Detected")
RET = MSG_BOX.exec_()
if RET == QtWidgets.QMessageBox.StandardButton.Yes:
return
LOG.sys("Program terminated by user.")
self.DUPLICATED = True
sys.exit()
def isOnline(self) -> bool:
"""
Checks if the software can connect to the internet
"""
# return True
try:
with socket.create_connection(("www.mongodb.com", 80)) as sock:
if sock is not None:
sock.close()
return not SYS.FORCE_OFFLINE
except OSError:
return False
return False
def startBackgroundTask(self):
"""
Initiates the background thread
"""
self.WORKER_1 = ThreadBackground()
self.WORKER_1.start()
self.WORKER_1.UPT.connect(self.WORKER_1.loopFunction)
def QCl(self, c):
if "#" in c:
c = c[1:]
return QtGui.QColor(int(c[:2], 16), int(c[2:4], 16), int(c[4:6], 16))
def RGBtoHEX(self, rgb):
rgb = list(rgb)
del rgb[3]
return "#%02x%02x%02x" % tuple(rgb)
def centerWindow(self, ui: QtWidgets.QWidget):
"""
Relocates the specific UI from argument to center of the screen
"""
FRM_GEOMETRY = ui.frameGeometry()
SCREEN = QtWidgets.QApplication.desktop().screenNumber(
QtWidgets.QApplication.desktop().cursor().pos()
)
FRM_GEOMETRY.moveCenter(
QtWidgets.QApplication.desktop().screenGeometry(SCREEN).center()
)
ui.move(FRM_GEOMETRY.topLeft())
def centerInsideWindow(self, WGTA: QtWidgets.QWidget, WGTB: QtWidgets.QWidget):
"""
Relocates the Widget A centered with relation to Widget B
"""
WGTA.show()
WINDOW = (
WGTB.frameGeometry().width() - WGTA.frameGeometry().width(),
WGTB.frameGeometry().height() - WGTA.frameGeometry().height(),
)
WGTA.move(
WGTB.pos().x() + int(WINDOW[0] / 2), WGTB.pos().y() + int(WINDOW[1] / 2.2)
)
def closeEvent(self, _):
"""
Triggers this function when the UI is shut down
Reports back to the logger.
"""
if self.DUPLICATED:
LOG.sys("Duplicate instance was shut down.")
else:
LOG.sys("Shutting down")
UIB.close()
UIFB.close()
## Send Exit Data
MDB.sendExitData()
LOG.sys(f"Program terminated: Duration ({SW.runtime(2)} Seconds)")
LOG.sys(
f"END OF LOG - {datetime.now().strftime('%B %d, %Y - %I:%M:%S %p')}"
)
def windowBlur(self, _windowBlur: bool):
"""
Handles blur effect of a window
"""
try:
return ## < --- Temporarily placed due to Blur compatibility issues with Windows 11
# blurWindow.blur(UIA.winId(), False, True, True)
# blurWindow.blur(UIB.winId(), False, True, True)
# blurWindow.blur(UIC.winId(), False, True, True)
except NameError:
pass
class Mongo:
"""
Handles all online-related databases used for reports/feedbacks, analytics, and other necessary data.
"""
def __init__(self) -> None:
self.CLUSTER = None
self.DB = None
self.COL_GLOBAL = None
self.COL_REPORTS = None
self.COL_CLIENT_DATA = None
self.CLIENT_QUERY = {"_id": SYS.UNIQ_MACHINE_ID}
self.GLOBAL_QUERY = {"_id": "GLOBAL"}
self.REPORT_INITIAL = 0 ## Report Switch for Initialization
self.REPORT_TASK = 0 ## Report Switch for Task
self.WORKER = self.MongoReport()
self.WORKER.start()
class MongoReport(QtCore.QThread):
def run(self):
while True:
if MDB.REPORT_INITIAL:
START = time.time()
try:
## Database
MDB.CLUSTER = pymongo.MongoClient(
os.environ.get("MONGO_CLIENT_API")
)
MDB.DB = MDB.CLUSTER["HymnalBrowser"]
## Collections or Datasets
MDB.COL_GLOBAL = MDB.DB["Global"]
MDB.COL_REPORTS = MDB.DB["Reports"]
MDB.COL_CLIENT_DATA = MDB.DB["ClientData"]
MDB.reportGlobal()
MDB.reportClientData()
MDB.clientIsVerified(True)
MDB.checkPendingTelemetry(SYS.isOnline())
except KeyError as err:
## Insert repair code here
LOG.debug(f'Key Error at "{err}". Needs changes')
LOG.error("Application needs to terminate due to an error.")
sys.exit()
except pymongo.errors.ConfigurationError as err:
LOG.debug(err)
# MDB.reportHymnalData()
LOG.info(f"Report finished in {round(time.time()-START,3)} s.")
MDB.REPORT_INITIAL = 0
if MDB.REPORT_TASK:
## Check if the client has working internet connection
if SYS.isOnline():
if not SYS.FORCE_OFFLINE:
MDB.checkPendingTelemetry(True)
UIFB.TME_START = time.time()
ONLINE = True
else:
ONLINE = False
else:
LOG.info(
"Can't connect to the database. Exporting offline report."
)
ONLINE = False
PUBLIC_IP = (
requests.get("https://api.ipify.org", timeout=5).text
if ONLINE
else "Unavailable"
)
REPORT_METHOD = "Online" if ONLINE else "Offline"
TIMESTAMP = SW.DATE_NOW()
STATUS = "OK"
REPORT = {
"_id": time.time(),
"_tms": str(datetime.now().strftime("%F %I:%M:%S %p")),
"username": SYS.USER_NAME,
"status": STATUS,
"DATA": {
"client": {
"reportMethod": REPORT_METHOD,
"feedback": str(UIFB.USER_TEXT.encode("utf-8")),
"hostname": SYS.HOST_NAME,
"localIPAddress": socket.gethostbyname(SYS.HOST_NAME),
"publicIPAddress": PUBLIC_IP,
},
"software": {
"logFile": LOG.getContents(),
"programDataSize": getSize(SYS.DIR_PROGRAM),
"timeElapsed": SW.runtime(),
"timeLaunched": (time.time() - SW.runtime()),
"timestamp": time.time(),
"version": SW.VERSION,
"versionName": SW.VERSION_NAME,
"sessionLaunchedFiles": SYS.CNT_SESSION_PRESN,
},
"system": {
"assessment": KSystem.getSystemAssessment(),
"configuration": list(CFG.CONFIG[CFG.HEADNAME].items()),
"env": dict(os.environ.items()),
"info": KSystem.getSystemInfo(),
"pathPPT": SYS.PPT_EXEC,
},
},
}
REPORT["DATA"]["system"]["env"].pop(
"MONGO_CLIENT_API"
) ## Pop out CLIENT_API to hide from database
REPORT = json.dumps(
REPORT, indent=4, sort_keys=True
) ## Serialize dict to a JSON str
## Update User Feedback Count
MDB.COL_CLIENT_DATA.update_one(
MDB.CLIENT_QUERY,
{
"$set": {
"feedbackCount": MDB.getCollData(
MDB.COL_CLIENT_DATA, MDB.CLIENT_QUERY
)["feedbackCount"]
+ 1
}
},
)
if ONLINE:
## Upload to cloud database
LOG.info("Sending feedback and report...")
MDB.COL_REPORTS.insert_one(json.loads(REPORT))
else:
## Save offline for future use
with open(
f"{SYS.DIR_TEMP}/{TIMESTAMP}.{SYS.EXT_FEEDBACK}", "wb"
) as w:
w.write(bz2.compress(REPORT.encode("utf-8"), 9))
LOG.info(
f'{"Feedback successfully sent" if ONLINE else "Offline report was saved."} ({round((time.time()-UIFB.TME_START), 2)} s)'
)
MDB.REPORT_TASK = 0
time.sleep(1.5)
def clientIsVerified(self, dump=False):
if System().isOnline():
if (
SYS.UNIQ_MACHINE_ID
in self.getCollData(self.COL_GLOBAL, self.GLOBAL_QUERY)["BASIC"][
"machines"
]
):
return True
elif dump:
self.COL_GLOBAL.update_one(
self.GLOBAL_QUERY,
{"$push": {"BASIC.machines": SYS.UNIQ_MACHINE_ID}},
)
LOG.sys(f"Client data for {SYS.UNIQ_MACHINE_ID} is now verified")
return False
def checkPendingTelemetry(self, online=False):
"""
Checks for pending reports that can be delivered
"""
## [1] Check for pending System Telemetry
# TLMTRY = [f'{SYS.DIR_TEMP}\\{i}' for i in os.listdir(SYS.DIR_TEMP) if i.endswith(f'.{SYS.EXT_TELEMETRY}')]
## < Insert offline telemetry report here >
## < Insert offline telemetry report here >
## < Insert offline telemetry report here >
## [2] Check for pending User Feedbacks
FBCKS = [
f"{SYS.DIR_TEMP}\\{i}"
for i in os.listdir(SYS.DIR_TEMP)
if i.endswith(f".{SYS.EXT_FEEDBACK}")
]
if len(FBCKS):
if not online:
LOG.info(
f"There are {len(FBCKS)} pending report(s) but cannot be delivered due to offline."
)
return
LOG.info(f"Scanned {len(FBCKS)} pending report(s)")
## Decompress
for i, file in enumerate(FBCKS):
try:
with open(file, "rb") as f:
self.COL_REPORTS.insert_one(
json.loads(bz2.decompress(f.read()).decode("utf-8"))
)
LOG.info(
f"[{i+1}/{len(FBCKS)}] '{file}' Report was successfully sent"
)
except (
OSError,
json.decoder.JSONDecodeError,
pymongo.errors.DuplicateKeyError,
) as e:
LOG.debug(e)
try:
os.remove(file)
LOG.info(
f"[{i+1}/{len(FBCKS)}] Deleted a bad or invalid data report file"
)
except PermissionError:
pass
try:
os.remove(file)
except PermissionError:
pass
def createNewData(self, collTarget):
"""
Create a new data based on collection target parameter
"""
if System().isOnline():
## CLIENT DATA
if collTarget == self.COL_CLIENT_DATA:
DEFAULTS = {
"_id": SYS.UNIQ_MACHINE_ID,
"_initiated": time.time(),
"systemLaunchCount": 0,
"presnLaunchCount": 0,
"lastUpdated": time.time(),
"usageSince": 0,
"feedbackCount": 0,
"_username": SYS.USER_NAME,
"_hostname": SYS.HOST_NAME,
"PACKAGE": {
"hymnal": Data().load(),
},
}
DEFAULTS = json.dumps(DEFAULTS, indent=4, sort_keys=True)
self.COL_CLIENT_DATA.insert_one(json.loads(DEFAULTS))
if not self.clientIsVerified(True):
LOG.warn(f"Old client data was detected missing by the system.")
## GLOBAL DATA
if collTarget == self.COL_GLOBAL:
LOG.crit("Global data is inaccessible.")
DEFAULTS = {
"_id": "GLOBAL",
"BASIC": {
"launches": 0,
"launchTimes": [0, 0, 0, 0],
"machines": [],
"recentLaunchTimestamp": time.time(),
},
"CONFIG": {
"versionMin": SW.VERSION,
"opacity": [50, 100],
},
}
self.COL_GLOBAL.insert_one(DEFAULTS)
LOG.sys("Global data was generated")
else:
LOG.info(
"Cannot create a client record. (Reason: Unable to connect to the server.)"
)
def getCollData(self, collectionName, query):
"""
Returns a collection data as a dict type object based from a name given in parameter
"""
while True:
if System().isOnline():
try:
DATA = getattr(collectionName, "find")(query)[0]
except IndexError:
self.createNewData(collectionName)
continue
else:
return DATA
def reportGlobal(self):
"""
Reports to global data
"""
while True:
if System().isOnline():
DATA = self.getCollData(self.COL_GLOBAL, self.GLOBAL_QUERY)
DATA["BASIC"]["launchTimes"][
0
] = SYS.STARTUP_TIME ## CURRENT, MINIMUM, MAXIMUM
if DATA["BASIC"]["launchTimes"][1] == 0:
DATA["BASIC"]["launchTimes"][1] = SYS.STARTUP_TIME
## Sections
DATA["BASIC"]["launches"] += 1
DATA["BASIC"]["recentLaunchTimestamp"] = time.time()
if SYS.STARTUP_TIME < DATA["BASIC"]["launchTimes"][1]:
DATA["BASIC"]["launchTimes"][1] = SYS.STARTUP_TIME
if SYS.STARTUP_TIME > DATA["BASIC"]["launchTimes"][2]:
DATA["BASIC"]["launchTimes"][2] = SYS.STARTUP_TIME
DATA["BASIC"]["launchTimes"][3] = (
DATA["BASIC"]["launchTimes"][2] - DATA["BASIC"]["launchTimes"][1]
)
self.COL_GLOBAL.update_one(self.GLOBAL_QUERY, {"$set": DATA})
else:
pass
## < Insert Offline Reports here >
## < Insert Offline Reports here >
## < Insert Offline Reports here >
break
def reportClientData(self):
while True:
if System().isOnline():
DATA = self.getCollData(self.COL_CLIENT_DATA, self.CLIENT_QUERY)
DATA["usageSince"] = time.time() - DATA["_initiated"]
DATA["lastUpdated"] = time.time()
DATA["_username"], DATA["_hostname"] = SYS.USER_NAME, SYS.HOST_NAME
DATA["systemLaunchCount"] += 1
self.COL_CLIENT_DATA.update_one(self.CLIENT_QUERY, {"$set": DATA})
else:
LOG.debug("Client Report was not sent due to offline.")
break
def sendExitData(self):
# pymongo.errors.ServerSelectionTimeoutError:
while True:
if System().isOnline():
DATA = self.getCollData(self.COL_CLIENT_DATA, self.CLIENT_QUERY)
DATA["lastUpdated"] = time.time()
DATA["presnLaunchCount"] += SYS.CNT_SESSION_PRESN
self.COL_CLIENT_DATA.update_one(self.CLIENT_QUERY, {"$set": DATA})
else:
pass
break
# def reportHymnalData(self):
# """
# Sends the SDATA of client to database
# """
# while True:
# if System().isOnline():
# QUERY = {'_id': SYS.UNIQ_MACHINE_ID}
# try: DATA = self.COL_CLIENT_DATA.find(QUERY)[0]
# except IndexError:
# self.createNewData()
# continue
# else:
# ## Existing
# DATA['PACKAGE'] = Data().load()
# self.COL_CLIENT_DATA.update_one(QUERY, {"$set": DATA})
# exit()
# try: self.COL_CLIENT_DATA.insert_one(json.loads(DATA))
# except pymongo.errors.DuplicateKeyError: self.COL_CLIENT_DATA.update_one({'_id': UNIQ_MACHINE_ID}, {'$set': json.loads(DATA)})
# LOG.info('Statistical data for hymns was uploaded.')
# break
class Configuration:
"""
Handles all configuration for the software.
Uses basic configuration parser.
Default config name: config.ini
"""
def __init__(self):
self.DEFAULTS = [
("AlwaysOnTop", False),
("AutoScroll", True),
("AutoSlideshow", False),
("CompactMode", False),
("KeepFocusOnBrowser", True),
("MaxAllowedRecent", 10),
("Theme", 0),
("WindowOpacity", 100),
]
self.DEFAULTS_OPTIONS = [k[0] for k in self.DEFAULTS]
self.check()
def check(self):
"""
Checks, load, and parse the configuration file
Automatically fixes missing, corrupted, and bad config headers
"""
if not os.path.exists(SYS.FILE_CONFIG):
LOG.warn("Configuration is missing")
self.generateDefault()
self.CONFIG = configparser.ConfigParser() ## Initiate config parser object
self.CONFIG.optionxform = str ## Preserve case of strings
self.HEADNAME = "Settings" ## Head name for configuration
PROCEED = False
while not PROCEED:
try:
self.read()
self.CONFIG[self.HEADNAME]
except (
configparser.MissingSectionHeaderError,
configparser.ParsingError,
KeyError,
): ## Resets the configuration file when the configuration is corrupted or had a problem while parsing
LOG.error("Cannot load configuration file. Resetting to defaults.")
self.generateDefault()
self.read()
## Test every variables in config
idx = 0
try:
for k in self.DEFAULTS:
self.CONFIG[self.HEADNAME][k[0]]
idx += 1
except KeyError as e:
LOG.warn(
f"Configuration: Missing value for {e}. Fallback will be used."
)
self.CONFIG.set(
self.HEADNAME, self.DEFAULTS[idx][0], str(self.DEFAULTS[idx][1])
)
self.dump()
else:
## Remove unnecessary variables
UNUSED = [
i
for i in self.CONFIG.options(self.HEADNAME)
if i not in self.DEFAULTS_OPTIONS
] ## Filter two lists by comparing what are the differences.
if UNUSED:
for u in UNUSED:
self.CONFIG[self.HEADNAME].pop(u)
LOG.info(f"Configuration: Removed unnecessary option: {u}")
self.dump()
PROCEED = True
LOG.info("Configuration was loaded successfully")
def read(self):
"""
Reads the configuration file. Equivalent to loading the file with updated values
"""
self.CONFIG.read(SYS.FILE_CONFIG)
def dump(self, data=None):
"""
Dumps the current config data and executes the read for updating values
"""
if data is None:
pass
with open(SYS.FILE_CONFIG, "w") as w:
self.CONFIG.write(w)
self.read() ## Read the file again update values
def getDefaults(self):
"""
Returns default configuration string
"""
return (
f"[Settings]{nL}{f'{nL}'.join([f'{k[0]} = {k[1]}' for k in self.DEFAULTS])}"
)
def generateDefault(self):
"""
Generates Default Configuration values from defaults
"""
with open(SYS.FILE_CONFIG, "w") as config:
config.write(self.getDefaults())
LOG.info("Configuration file was regenerated with default values")
class Data:
"""
Manages the statistical database for Hymnal Browser.
Uses JSON to parse the data.
SDATA (or Statistical Database) is the dictionary of all stats of the hymns.
"""
def __init__(self):
self.check()
def check(self):
"""
Checks if the file is existent.
"""
if not os.path.exists(SYS.FILE_DATA):
LOG.warn("Data is missing. Generating new.")
self.generateDefault()
self.verifyContents()
self.DATA = self.load()
def load(self):
"""
Retrieves the data from system's data file.
"""
while True:
with open(SYS.FILE_DATA, "r") as read:
try:
CFG = json.load(read)
except json.decoder.JSONDecodeError:
LOG.error("Failed to load statistic data. Regenerating default.")
self.generateDefault()
else:
return CFG
def verifyContents(self):
"""
Verify the statistic file.
"""
TARGET = self.load()
try:
for i in range(SYS.HYMNS_MAX):
TARGET["DATA"][KString.toDigits(i + 1, 3)]
for j in range(3):
TARGET["DATA"][KString.toDigits(i + 1, 3)][j]
except KeyError as e:
LOG.crit(
f'System has found a corrupted "{KString.filterOnly(1,str(e))}" entry in statistical data. Regenerating new one with default values'
)
self.generateDefault()
def dump(self, data=None):
"""
Saves the passed data to system's data file.
Uses indention of 4 and sorted keys by default.
Can be processed with other data if 1st argument is specified.
"""
if data is None:
data = SDATA
with open(SYS.FILE_DATA, "w") as write:
json.dump(data, write, indent=None, sort_keys=True)
def generateDefault(self):
"""
Generates default data. Autofills all 474 Hymns' statistics by default (0 values).
"""
DATA = {
"__DATECREATED": time.time(),
"__FILETYPE__": f"{SW.NAME} Statistical Data",
"__CHECKSUM__": None,
"DATA": {str(i + 1).zfill(3): [0, 0, 0] for i in range(HDB.TOTAL_HYMNS)},
}
DATA.update({"__CHECKSUM__": KString.toHashMD5(DATA)})
self.dump(DATA)
LOG.info(
f"Default data was generated successfully. | Hash: {KString.toHashMD5(DATA)}"
)
def getStats(self):
"""
Returns statistics for database panel in Settings
"""
try:
STATS = [
SDB.load()["DATA"][KString.toDigits(i + 1, 3)]
for i in range(SYS.HYMNS_MAX)
]
except KeyError as e:
LOG.error(e)
SDB.check() ## Recheck the SDATA for possible corrupted keys
else:
_STATS = namedtuple("STATS", "queries launches lastAccessed")
a = sum([STATS[i][0] for i in range(len(STATS))])
b = sum([STATS[i][1] for i in range(len(STATS))])
c = timedelta(
seconds=max([STATS[i][2] for i in range(len(STATS))])
), timedelta(seconds=min([STATS[i][2] for i in range(len(STATS))]))
return _STATS(a, b, c)
class HymnsDatabase:
"""
Handles all Hymns from the hymns.sda Database
HYMNAL is the whole dict of information about the hymns
For parsing, the method `parseHymnDatabase` will do the following in order:
- Scan all files from hymns.sda using ZipFile module
- Splits the hymn filename into useful parts using `splitHymn`; would return (cat, num, title, ext)
- Appending all matching valid pptx files into its correct list; flags all unused file inside database as unnecessary
- Also lists all the missing files (by default)
- Merges all data collected into one dictionary (tuple)
- Returns the whole namedtuple dictionary (aka. Hymnal)
For retrieving stats, the method `getStats` will do the following in order: