-
Notifications
You must be signed in to change notification settings - Fork 8
/
JWLManager.py
executable file
·3030 lines (2728 loc) · 150 KB
/
JWLManager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
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
"""
JWLManager: Multi-platform GUI for managing JW Library files:
view, delete, edit, merge (via export/import), etc.
MIT License: Copyright (c) 2024 Eryk J.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
APP = 'JWLManager'
VERSION = 'v6.0.0'
from res.ui_main_window import Ui_MainWindow
from res.ui_extras import AboutBox, HelpBox, DataViewer, DropList, ThemeManager, ViewerItem
from PySide6.QtCore import QEvent, QPoint, QSettings, QSize, Qt, QTranslator
from PySide6.QtGui import QAction, QFont
from PySide6.QtWidgets import QApplication, QComboBox, QDialog, QDialogButtonBox, QFileDialog, QFormLayout, QGridLayout, QLabel, QMainWindow, QMenu, QMessageBox, QProgressDialog, QPushButton, QTextEdit, QTreeWidgetItem, QTreeWidgetItemIterator, QVBoxLayout, QWidget
from datetime import datetime, timezone
from filehash import FileHash
from functools import partial
from pathlib import Path
from PIL import Image
from platform import platform
from random import randint
from tempfile import mkdtemp
from time import time
from traceback import format_exception
from xlsxwriter import Workbook
from zipfile import ZipFile, ZIP_DEFLATED
import argparse, gettext, glob, json, puremagic, os, regex, requests, shutil, sqlite3, sys, uuid
import pandas as pd
#### Initial language setting based on passed arguments
def get_language():
global available_languages, tr
available_languages = { # add/enable completed languages
'de': 'German (Deutsch)',
'en': 'English (default)',
'es': 'Spanish (español)',
'fr': 'French (français)',
'it': 'Italian (italiano)',
'pl': 'Polish (Polski)',
'pt': 'Portuguese (Português)',
'ru': 'Russian (Pусский)',
'uk': 'Ukrainian (українська)'
}
tr = {}
localedir = project_path / 'res/locales/'
parser = argparse.ArgumentParser(description='Manage .jwlibrary backup archives')
parser.add_argument('-v', '--version', action='version', version=f'{APP} {VERSION}', help='show version and exit')
language_group = parser.add_argument_group('interface language', 'English by default')
group = language_group.add_mutually_exclusive_group(required=False)
for k in sorted(available_languages.keys()):
group.add_argument(f'-{k}', action='store_true', help=available_languages[k])
tr[k] = gettext.translation('messages', localedir, fallback=True, languages=[k])
args = vars(parser.parse_args())
lng = settings.value('JWLManager/language', 'en')
for l in args.keys():
if args[l]:
lng = l
return lng
def read_resources(lng):
def load_bible_books(lng):
for row in con.execute(f'SELECT Number, Name FROM BibleBooks WHERE Language = {lng};').fetchall():
bible_books[row[0]] = row[1]
def load_languages():
for row in con.execute('SELECT Language, Name, Code, Symbol FROM Languages;').fetchall():
lang_name[row[0]] = row[1]
lang_symbol[row[0]] = row[3]
if row[2] == lng:
ui_lang = row[0]
return ui_lang
global _, bible_books, favorites, lang_name, lang_symbol, publications
_ = tr[lng].gettext
lang_name = {}
lang_symbol = {}
bible_books = {}
con = sqlite3.connect(project_path / 'res/resources.db')
ui_lang = load_languages()
load_bible_books(ui_lang)
pubs = pd.read_sql_query(f"SELECT Symbol, ShortTitle Short, Title 'Full', Year, [Group] Type FROM Publications p JOIN Types USING (Type, Language) WHERE Language = {ui_lang};", con)
extras = pd.read_sql_query(f"SELECT Symbol, ShortTitle Short, Title 'Full', Year, [Group] Type FROM Extras p JOIN Types USING (Type, Language) WHERE Language = {ui_lang};", con)
publications = pd.concat([pubs, extras], ignore_index=True)
favorites = pd.read_sql_query("SELECT * FROM Favorites;", con)
con.close()
def set_settings_path():
if getattr(sys, 'frozen', False):
application_path = os.path.dirname(sys.executable)
else:
try:
application_path = os.path.dirname(os.path.realpath(__file__))
except NameError:
application_path = os.getcwd()
return QSettings(application_path+'/'+APP+'.conf', QSettings.Format.IniFormat)
project_path = Path(__file__).resolve().parent
tmp_path = mkdtemp(prefix='JWLManager_')
db_name = 'userData.db'
settings = set_settings_path()
lang = get_language()
read_resources(lang)
#### Main app
class Window(QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
def center():
qr = self.frameGeometry()
cp = QWidget.screen(self).availableGeometry().center()
qr.moveCenter(cp)
return qr.topLeft()
def connect_signals():
self.actionQuit.triggered.connect(self.close)
self.actionHelp.triggered.connect(self.help_box)
self.actionAbout.triggered.connect(self.about_box)
self.actionNew.triggered.connect(self.new_file)
self.actionOpen.triggered.connect(self.load_file)
self.actionQuit.triggered.connect(self.clean_up)
self.actionSave.triggered.connect(self.save_file)
self.actionSave_As.triggered.connect(self.save_as_file)
self.actionObscure.triggered.connect(self.obscure_items)
self.actionReindex.triggered.connect(self.reindex_db)
self.actionSort.triggered.connect(self.sort_notes)
self.actionExpand_All.triggered.connect(self.expand_all)
self.actionCollapse_All.triggered.connect(self.collapse_all)
self.actionSelect_All.triggered.connect(self.select_all)
self.actionUnselect_All.triggered.connect(self.unselect_all)
self.actionTheme.triggered.connect(self.toggle_theme)
self.menuTitle_View.triggered.connect(self.change_title)
self.menuLanguage.triggered.connect(self.change_language)
self.combo_grouping.currentTextChanged.connect(self.regroup)
self.combo_category.currentTextChanged.connect(self.switchboard)
self.treeWidget.itemChanged.connect(self.tree_selection)
self.treeWidget.doubleClicked.connect(self.double_clicked)
self.button_export.clicked.connect(self.export_menu)
self.button_import.clicked.connect(self.import_items)
self.button_add.clicked.connect(self.add_items)
self.button_delete.clicked.connect(self.delete_items)
self.button_view.clicked.connect(self.data_viewer)
def set_vars():
self.total.setText('')
self.int_total = 0
self.modified = False
self.title_format = settings.value('JWLManager/title','short')
options = { 'code': 0, 'short': 1, 'full': 2 }
self.titleChoices.actions()[options[self.title_format]].setChecked(True)
self.save_filename = ''
self.current_archive = settings.value('JWLManager/archive', '')
if not os.path.exists(self.current_archive):
self.current_archive = ''
self.working_dir = Path.home()
self.lang = lang
self.latest = None
for item in self.menuLanguage.actions():
if item.toolTip() not in available_languages.keys():
item.setVisible(False)
if item.toolTip() == self.lang:
item.setChecked(True)
self.current_data = []
self.mode = settings.value('JWLManager/theme', 'light')
self.setupUi(self)
self.combo_category.setCurrentIndex(int(settings.value('JWLManager/category', 0)))
self.combo_category.view().setMinimumWidth(190)
self.combo_grouping.setCurrentText(_('Type'))
self.viewer_pos = settings.value('Viewer/position', QPoint(50, 25))
self.viewer_size = settings.value('Viewer/size', QSize(755, 500))
self.help_pos = settings.value('Help/position', QPoint(50, 50))
self.help_size = settings.value('Help/size', QSize(350, 400))
self.setAcceptDrops(True)
self.status_label = QLabel()
self.statusBar.addPermanentWidget(self.status_label, 0)
self.treeWidget.setSortingEnabled(True)
self.treeWidget.sortByColumn(int(settings.value('JWLManager/sort', 1)), settings.value('JWLManager/direction', Qt.DescendingOrder))
self.treeWidget.setColumnWidth(0, int(settings.value('JWLManager/column1', 500)))
self.treeWidget.setColumnWidth(1, int(settings.value('JWLManager/column2', 30)))
self.treeWidget.setExpandsOnDoubleClick(False)
self.button_add.setVisible(False)
self.resize(settings.value('Main_Window/size', QSize(680, 500)))
self.move(settings.value('Main_Window/position', center()))
self.viewer_window = QDialog(self)
connect_signals()
set_vars()
self.about_window = AboutBox(self, app=APP, version=VERSION)
self.help_window = HelpBox(_('Help'), self.help_size, self.help_pos)
self.theme = ThemeManager()
self.theme.set_theme(app, self.mode)
self.theme.update_icons(self, self.mode)
self.load_file(self.current_archive) if self.current_archive else self.new_file()
def changeEvent(self, event):
if event.type() == QEvent.LanguageChange:
self.retranslateUi(self)
def closeEvent(self, event):
if self.modified:
reply = QMessageBox.question(self, _('Exit'), _('Save before quitting?'), QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel, QMessageBox.Yes)
if reply == QMessageBox.Yes:
if self.save_file() == False:
event.ignore()
return
elif reply == QMessageBox.Cancel:
event.ignore()
return
event.accept()
self.clean_up()
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.accept()
else:
event.ignore()
def dropEvent(self, event):
file = event.mimeData().urls()[0].toLocalFile()
suffix = Path(file).suffix
if suffix == '.jwlibrary':
self.load_file(file)
elif not self.combo_category.isEnabled():
QMessageBox.warning(self, _('Error'), _('No archive has been opened!'), QMessageBox.Cancel)
elif suffix == '.jwlplaylist':
self.import_items(file, _('Playlists'))
elif suffix == '.txt':
with open(file, 'r', encoding='utf-8', errors='namereplace') as f:
header = f.readline().strip()
if header == r'{ANNOTATIONS}':
self.import_items(file, _('Annotations'))
elif header == r'{BOOKMARKS}':
self.import_items(file, _('Bookmarks'))
elif header == r'{HIGHLIGHTS}':
self.import_items(file, _('Highlights'))
elif regex.search('{NOTES=', header):
self.import_items(file, _('Notes'))
else:
QMessageBox.warning(self, _('Error'), _('File "{}" not recognized!').format(file), QMessageBox.Cancel)
else:
QMessageBox.warning(self, _('Error'), _('File "{}" not recognized!').format(file), QMessageBox.Cancel)
def help_box(self):
self.help_window.show()
self.help_window.raise_()
self.help_window.activateWindow()
self.help_pos = self.help_window.pos()
self.help_size = self.help_window.size()
def about_box(self):
def version_compare(version, release):
for r, v in zip(release.strip('v').split('.'), version.strip('v').split('.')):
if int(r) > int(v):
return True
elif int(r) < int(v):
return None
return False
if not self.latest:
url = 'https://api.github.com/repos/erykjj/jwlmanager/releases/latest'
headers = { 'X-GitHub-Api-Version': '2022-11-28' }
try:
r = requests.get(url, headers=headers, timeout=5)
self.latest = json.loads(r.content.decode('utf-8'))['name']
comp = version_compare(VERSION, self.latest)
if comp is None:
text = f'<div style="text-align:center;"><small>'+'Pre-release'+'</small></div>'
elif comp:
text = f'<div style="text-align:center;"><a style="color:red; text-decoration:none;" href="https://github.com/erykjj/jwlmanager/releases/latest"><small><b>{self.latest.lstrip("v")} '+_('update available!')+'</b></small></a></div>'
else:
text = f'<div style="text-align:center;"><small>'+_('Latest version')+'</small></div>'
except:
text = f'<div style="text-align:center;"><small><i>'+_('Error while checking for updates!')+'</u></small></div>'
self.about_window.update_label.setText(text)
self.about_window.exec()
def crash_box(self, ex):
tb_lines = format_exception(ex.__class__, ex, ex.__traceback__)
tb_text = ''.join(tb_lines)
dialog = QDialog(self)
dialog.setMinimumSize(650, 375)
dialog.setWindowTitle(_('Error!'))
label1 = QLabel()
label1.setText("<p style='text-align: left;'>"+_('Oops! Something went wrong…')+"</p></p><p style='text-align: left;'>"+_('Take note of what you were doing and')+" <a style='color: #666699;' href='https://github.com/erykjj/jwlmanager/issues'>"+_('inform the developer')+"</a>:</p>")
label1.setOpenExternalLinks(True)
text = QTextEdit()
text.setReadOnly(True)
text.setText(f'{APP} {VERSION}\n{platform()}\n\n{tb_text}')
label2 = QLabel()
label2.setText(_('The app will terminate.'))
button = QDialogButtonBox(QDialogButtonBox.Abort)
layout = QVBoxLayout(dialog)
layout.addWidget(label1)
layout.addWidget(text)
layout.addWidget(label2)
layout.addWidget(button)
button.clicked.connect(dialog.close)
dialog.exec()
def toggle_theme(self):
if self.mode == 'light':
self.mode = 'dark'
else:
self.mode = 'light'
self.theme.set_theme(app, self.mode)
self.theme.update_icons(self, self.mode)
def change_language(self): # FIX: something wrong when changing between en <> fr
changed = False
self.combo_grouping.blockSignals(True)
for item in self.langChoices.actions():
if item.isChecked() and (self.lang != item.toolTip()):
app.removeTranslator(translator[self.lang])
self.lang = item.toolTip()
changed = True
break
if not changed:
return
read_resources(self.lang)
if self.lang not in translator.keys():
translator[self.lang] = QTranslator()
translator[self.lang].load(f'{project_path}/res/locales/UI/qt_{self.lang}.qm')
app.installTranslator(translator[self.lang])
app.processEvents()
self.combo_grouping.blockSignals(False)
def change_title(self):
changed = False
options = ['code', 'short', 'full']
counter = 0
for item in self.titleChoices.actions():
if item.isChecked() and (self.title_format != options[counter]):
self.title_format = options[counter]
changed = True
counter += 1
if changed:
self.regroup(True)
def expand_all(self):
self.treeWidget.expandAll()
def collapse_all(self):
self.treeWidget.collapseAll()
def right_clicked(self, item):
if item.checkState(0) == Qt.Checked:
item.setCheckState(0, Qt.Unchecked)
else:
item.setCheckState(0, Qt.Checked)
def double_clicked(self, item):
if self.treeWidget.isExpanded(item):
self.treeWidget.setExpanded(item, False)
else:
self.treeWidget.expandRecursively(item, -1)
def select_all(self):
for item in QTreeWidgetItemIterator(self.treeWidget):
item.value().setCheckState(0, Qt.Checked)
def unselect_all(self):
for item in QTreeWidgetItemIterator(self.treeWidget):
item.value().setCheckState(0, Qt.Unchecked)
def tree_selection(self):
self.selected_items = len(self.list_selected())
self.selected.setText(f'**{self.selected_items:,}**')
self.button_delete.setEnabled(self.selected_items)
self.button_view.setEnabled(self.selected_items and self.combo_category.currentText() in (_('Notes'), _('Annotations')))
self.button_export.setEnabled(self.selected_items and self.combo_category.currentText() in (_('Notes'), _('Highlights'), _('Annotations'), _('Playlists'), _('Bookmarks')))
def list_selected(self):
selected = []
it = QTreeWidgetItemIterator(self.treeWidget, QTreeWidgetItemIterator.Checked)
for item in it:
index = item.value()
for i in self.leaves.get(index):
selected.append(i)
return selected
def switchboard(self, selection):
def disable_options(lst=[], add=False, exp=False, imp=False, view=False):
self.button_add.setVisible(add)
self.button_view.setVisible(view)
self.button_export.setVisible(exp)
self.button_import.setEnabled(imp)
self.button_import.setVisible(imp)
app.processEvents()
for item in range(6):
self.combo_grouping.model().item(item).setEnabled(True)
for item in lst:
self.combo_grouping.model().item(item).setEnabled(False)
if self.combo_grouping.currentText() == self.combo_grouping.itemText(item):
self.combo_grouping.setCurrentText(_('Type'))
self.combo_grouping.blockSignals(True)
if selection == _('Notes'):
self.combo_grouping.setCurrentText(_('Type'))
disable_options([], False, True, True, True)
elif selection == _('Highlights'):
# self.combo_grouping.setCurrentText(_('Type'))
disable_options([4], False, True, True, False)
elif selection == _('Bookmarks'):
disable_options([4,5], False, True, True, False)
elif selection == _('Annotations'):
disable_options([2,4,5], False, True, True, True)
elif selection == _('Favorites'):
disable_options([4,5], True, False, False, False)
elif selection == _('Playlists'):
self.combo_grouping.setCurrentText(_('Title'))
disable_options([1,2,3,4,5], True, True, True, False)
self.regroup()
self.combo_grouping.blockSignals(False)
def regroup(self, same_data=False, message=None):
def get_data():
if category == _('Bookmarks'):
get_bookmarks()
elif category == _('Favorites'):
get_favorites()
elif category == _('Highlights'):
get_highlights()
elif category == _('Notes'):
get_notes()
elif category == _('Annotations'):
get_annotations()
elif category == _('Playlists'):
get_playlists()
def process_code(code, issue):
if code == 'ws' and issue == 0: # Worldwide Security book - same code as simplified Watchtower
code = 'ws-'
elif not code:
code = ''
yr = ''
dated = regex.search(code_yr, code) # Year included in code
if dated:
prefix = dated.group(1)
suffix = dated.group(2)
if prefix not in {'bi', 'br', 'brg', 'kn', 'ks', 'pt', 'tp'}:
code = prefix
if int(suffix) >= 50:
yr = '19' + suffix
else:
yr = '20' + suffix
return code, yr
def process_color(col):
return (_('Grey'), _('Yellow'), _('Green'), _('Blue'), _('Red'), _('Orange'), _('Purple'))[int(col)]
def process_detail(symbol, book, chapter, issue, year):
if symbol in {'Rbi8', 'bi10', 'bi12', 'bi22', 'bi7', 'by', 'int', 'nwt', 'nwtsty', 'rh', 'sbi1', 'sbi2'}: # Bible appendix notes, etc.
detail1 = _('* OTHER *')
else:
detail1 = None
if issue > 19000000:
y = str(issue)[0:4]
m = str(issue)[4:6]
d = str(issue)[6:]
if d == '00':
detail1 = f'{y}-{m}'
else:
detail1 = f'{y}-{m}-{d}'
if not year:
year = y
if book and chapter:
bk = str(book).rjust(2, '0') + f': {bible_books[book]}'
detail1 = bk
detail2 = _('Chap.') + str(chapter).rjust(4, ' ')
else:
detail2 = None
if not detail1 and year:
detail1 = year
if not year:
year = _('* YEAR UNCERTAIN *')
return detail1, year, detail2
def merge_df(df):
df = pd.merge(df, publications, how='left', on=['Symbol'], sort=False)
df['Full'] = df['Full'].fillna(df['Symbol'])
df['Short'] = df['Short'].fillna(df['Symbol'])
df['Type'] = df[['Type']].fillna(_('Other'))
df['Year'] = df['Year_y'].fillna(df['Year_x']).fillna(_('* NO YEAR *'))
df = df.drop(['Year_x', 'Year_y'], axis=1)
df['Year'] = df['Year'].astype(str).str.replace('.0', '',regex=False)
return df
def get_annotations():
lst = []
for row in con.execute('SELECT LocationId, l.KeySymbol, l.MepsLanguage, l.IssueTagNumber, TextTag, l.BookNumber, l.ChapterNumber, l.Title FROM InputField JOIN Location l USING (LocationId);').fetchall():
lng = lang_name.get(row[2], _('* NO LANGUAGE *'))
code, year = process_code(row[1], row[3])
detail1, year, detail2 = process_detail(row[1], row[5], row[6], row[3], year)
item = row[0]
rec = [ item, lng, code, year, detail1, detail2 ]
lst.append(rec)
annotations = pd.DataFrame(lst, columns=[ 'Id', 'Language', 'Symbol', 'Year', 'Detail1', 'Detail2' ])
self.current_data = merge_df(annotations)
def get_bookmarks():
lst = []
for row in con.execute('SELECT LocationId, l.KeySymbol, l.MepsLanguage, l.IssueTagNumber, BookmarkId, l.BookNumber, l.ChapterNumber, l.Title FROM Bookmark b JOIN Location l USING (LocationId);').fetchall():
lng = lang_name.get(row[2], f'#{row[2]}')
code, year = process_code(row[1], row[3])
detail1, year, detail2 = process_detail(row[1], row[5], row[6], row[3], year)
item = row[4]
rec = [ item, lng, code or _('* OTHER *'), year, detail1, detail2 ]
lst.append(rec)
bookmarks = pd.DataFrame(lst, columns=[ 'Id', 'Language', 'Symbol', 'Year', 'Detail1', 'Detail2' ])
self.current_data = merge_df(bookmarks)
def get_favorites():
lst = []
for row in con.execute('SELECT LocationId, l.KeySymbol, l.MepsLanguage, l.IssueTagNumber, TagMapId FROM TagMap tm JOIN Location l USING (LocationId) WHERE tm.NoteId IS NULL ORDER BY tm.Position;').fetchall():
lng = lang_name.get(row[2], f'#{row[2]}')
code, year = process_code(row[1], row[3])
detail1, year, detail2 = process_detail(row[1], None, None, row[3], year)
item = row[4]
rec = [ item, lng, code or _('* OTHER *'), year, detail1, detail2 ]
lst.append(rec)
favorites = pd.DataFrame(lst, columns=[ 'Id', 'Language', 'Symbol','Year', 'Detail1', 'Detail2' ])
self.current_data = merge_df(favorites)
def get_highlights():
lst = []
for row in con.execute('SELECT LocationId, l.KeySymbol, l.MepsLanguage, l.IssueTagNumber, b.BlockRangeId, u.UserMarkId, u.ColorIndex, l.BookNumber, l.ChapterNumber FROM UserMark u JOIN Location l USING (LocationId), BlockRange b USING (UserMarkId);').fetchall():
lng = lang_name.get(row[2], f'#{row[2]}')
code, year = process_code(row[1], row[3])
detail1, year, detail2 = process_detail(row[1], row[7], row[8], row[3], year)
col = process_color(row[6] or 0)
item = row[4]
rec = [ item, lng, code, col, year, detail1, detail2 ]
lst.append(rec)
highlights = pd.DataFrame(lst, columns=[ 'Id', 'Language', 'Symbol', 'Color', 'Year', 'Detail1', 'Detail2' ])
self.current_data = merge_df(highlights)
def get_notes():
def load_independent():
lst = []
for row in con.execute("SELECT NoteId Id, ColorIndex Color, GROUP_CONCAT(Name, ' | ') Tags, substr(LastModified, 0, 11) Modified FROM (SELECT * FROM Note n LEFT JOIN TagMap tm USING (NoteId) LEFT JOIN Tag t USING (TagId) LEFT JOIN UserMark u USING (UserMarkId) ORDER BY t.Name) n WHERE n.BlockType = 0 AND LocationId IS NULL GROUP BY n.NoteId;").fetchall():
col = row[1] or 0
yr = row[3][0:4]
note = [ row[0], _('* NO LANGUAGE *'), _('* OTHER *'), process_color(col), row[2] or _('* NO TAG *'), row[3] or '', yr, None, _('* OTHER *'), _('* OTHER *'), _('* INDEPENDENT *') ]
lst.append(note)
return pd.DataFrame(lst, columns=['Id', 'Language', 'Symbol', 'Color', 'Tags', 'Modified', 'Year', 'Detail1', 'Short', 'Full', 'Type'])
lst = []
for row in con.execute("SELECT NoteId Id, MepsLanguage Language, KeySymbol Symbol, IssueTagNumber Issue, BookNumber Book, ChapterNumber Chapter, ColorIndex Color, GROUP_CONCAT(Name, ' | ') Tags, substr(LastModified, 0, 11) Modified FROM (SELECT * FROM Note n JOIN Location l USING (LocationId) LEFT JOIN TagMap tm USING (NoteId) LEFT JOIN Tag t USING (TagId) LEFT JOIN UserMark u USING (UserMarkId) ORDER BY t.Name) n GROUP BY n.NoteId;").fetchall():
lng = lang_name.get(row[1], f'#{row[1]}')
code, year = process_code(row[2], row[3])
detail1, year, detail2 = process_detail(row[2], row[4], row[5], row[3], year)
col = process_color(row[6] or 0)
note = [ row[0], lng, code or _('* OTHER *'), col, row[7] or _('* NO TAG *'), row[8] or '', year, detail1, detail2 ]
lst.append(note)
notes = pd.DataFrame(lst, columns=[ 'Id', 'Language', 'Symbol', 'Color', 'Tags', 'Modified', 'Year', 'Detail1', 'Detail2' ])
notes = merge_df(notes)
i_notes = load_independent()
notes = pd.concat([i_notes, notes], axis=0, ignore_index=True)
self.current_data = notes
def get_playlists():
lst = []
for row in con.execute('SELECT PlaylistItemId, Name, Position, Label FROM PlaylistItem JOIN TagMap USING ( PlaylistItemId ) JOIN Tag t USING ( TagId ) WHERE t.Type = 2 ORDER BY Name, Position;').fetchall():
rec = [ row[0], None, _('* OTHER *'), row[1], '', row[3] ]
lst.append(rec)
playlists = pd.DataFrame(lst, columns=['Id', 'Language', 'Symbol', 'Tags', 'Year', 'Detail1'])
self.current_data = merge_df(playlists)
def enable_options(enabled):
self.button_import.setEnabled(enabled)
self.combo_grouping.setEnabled(enabled)
self.combo_category.setEnabled(enabled)
self.actionReindex.setEnabled(enabled)
self.actionObscure.setEnabled(enabled)
self.actionSort.setEnabled(enabled)
self.actionExpand_All.setEnabled(enabled)
self.actionCollapse_All.setEnabled(enabled)
self.actionSelect_All.setEnabled(enabled)
self.actionUnselect_All.setEnabled(enabled)
self.menuTitle_View.setEnabled(enabled)
self.menuLanguage.setEnabled(enabled)
def build_tree():
def add_node(parent, label, data):
child = QTreeWidgetItem(parent)
child.setFlags(child.flags() | Qt.ItemIsAutoTristate | Qt.ItemIsUserCheckable)
child.setCheckState(0, Qt.Unchecked)
child.setText(0, str(label))
child.setData(1, Qt.DisplayRole, data)
child.setTextAlignment(1, Qt.AlignCenter)
return child
def traverse(df, idx, parent):
if len(idx) > 0:
filter = idx[0]
for i, df in df.groupby(filter):
app.processEvents()
self.leaves[parent] = []
child = add_node(parent, i, df.shape[0])
self.leaves[child] = df['Id'].to_list()
traverse(df, idx[1:], child)
def define_views(category):
if category == _('Bookmarks'):
views = {
_('Type'): [ 'Type', 'Title', 'Language', 'Detail1' ],
_('Title'): [ 'Title', 'Language', 'Detail1', 'Detail2' ],
_('Language'): [ 'Language', 'Title', 'Detail1', 'Detail2' ],
_('Year'): [ 'Year', 'Title', 'Language', 'Detail1' ] }
elif category == _('Favorites'):
views = {
_('Type'): [ 'Type', 'Title', 'Language' ],
_('Title'): [ 'Title', 'Language' ],
_('Language'): [ 'Language', 'Title' ],
_('Year'): [ 'Year', 'Title', 'Language' ] }
elif category == _('Playlists'):
views = { _('Title'): [ 'Tags', 'Detail1' ], }
elif category == _('Highlights'):
views = {
_('Type'): [ 'Type', 'Title', 'Language', 'Detail1' ],
_('Title'): [ 'Title', 'Language', 'Detail1', 'Detail2' ],
_('Language'): [ 'Language', 'Title', 'Detail1', 'Detail2' ],
_('Year'): [ 'Year', 'Title', 'Language', 'Detail1' ],
_('Color'): [ 'Color', 'Title', 'Language', 'Detail1' ] }
elif category == _('Notes'):
views = {
_('Type'): [ 'Type', 'Title', 'Language', 'Detail1' ],
_('Title'): [ 'Title', 'Language', 'Detail1', 'Detail2' ],
_('Language'): [ 'Language', 'Title', 'Detail1', 'Detail2' ],
_('Year'): [ 'Year', 'Title', 'Language', 'Detail1' ],
_('Tag'): [ 'Tags', 'Title', 'Language', 'Detail1' ],
_('Color'): [ 'Color', 'Title', 'Language', 'Detail1' ] }
elif category == _('Annotations'):
views = {
_('Type'): [ 'Type', 'Title', 'Detail1', 'Detail2' ],
_('Title'): [ 'Title', 'Detail1', 'Detail2' ],
_('Year'): [ 'Year', 'Title', 'Detail1', 'Detail2' ] }
return views
if self.title_format == 'code':
title = 'Symbol'
elif self.title_format == 'short':
title = 'Short'
else:
title = 'Full'
self.current_data['Title'] = self.current_data[title]
views = define_views(category)
self.int_total = self.current_data.shape[0]
self.total.setText(f'**{self.int_total:,}**')
filters = views[grouping]
traverse(self.current_data, filters, self.treeWidget)
if same_data is not True:
same_data = False
if message:
msg = message + '… '
else:
msg = ' '
self.statusBar.showMessage(msg+_('Processing…'))
enable_options(False)
app.processEvents()
category = self.combo_category.currentText()
grouping = self.combo_grouping.currentText()
code_yr = regex.compile(r'(.*?[^\d-])(\d{2}$)')
start = time()
try:
con = sqlite3.connect(f'{tmp_path}/{db_name}')
con.executescript("PRAGMA temp_store = 2; PRAGMA journal_mode = 'OFF';")
if not same_data:
get_data()
self.leaves = {}
self.treeWidget.clear()
self.treeWidget.repaint()
build_tree()
con.commit()
con.close()
except Exception as ex:
self.crash_box(ex)
self.clean_up()
sys.exit()
delta = 4000 - (time()-start) * 1000
if message:
self.statusBar.showMessage(msg, delta)
else:
self.statusBar.showMessage('')
enable_options(True)
self.selected.setText('**0**')
if self.combo_grouping.currentText() == _('Type'):
self.treeWidget.expandToDepth(0)
app.processEvents()
def check_save(self):
reply = QMessageBox.question(self, _('Save'), _('Save current archive?'),
QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel,
QMessageBox.Yes)
if reply == QMessageBox.Yes:
self.save_file()
# elif reply == QMessageBox.Cancel:
# return
def new_file(self):
if self.modified:
self.check_save()
self.status_label.setText('* '+_('NEW ARCHIVE')+' * ')
self.modified = False
self.save_filename = ''
self.current_archive = ''
global db_name
try:
for f in glob.glob(f'{tmp_path}/*', recursive=True):
os.remove(f)
except:
pass
db_name = 'userData.db'
with ZipFile(project_path / 'res/blank','r') as zipped:
zipped.extractall(tmp_path)
m = {
'name': APP,
'creationDate': datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'),
'version': 1,
'type': 0,
'userDataBackup': {
'lastModifiedDate': datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'),
'deviceName': f'{APP}_{VERSION}',
'databaseName': 'userData.db',
'hash': '',
'schemaVersion': 14 } }
with open(f'{tmp_path}/manifest.json', 'w') as json_file:
json.dump(m, json_file, indent=None, separators=(',', ':'))
self.file_loaded()
def load_file(self, archive = ''):
if self.modified:
self.check_save()
if not archive:
fname = QFileDialog.getOpenFileName(self, _('Open archive'), str(self.working_dir),_('JW Library archives')+' (*.jwlibrary)')
if not fname[0]:
return
archive = fname[0]
self.current_archive = Path(archive)
self.working_dir = Path(archive).parent
self.status_label.setText(f'{Path(archive).stem} ')
global db_name
try:
for f in glob.glob(f'{tmp_path}/*', recursive=True):
os.remove(f)
except:
pass
with ZipFile(archive,'r') as zipped:
zipped.extractall(tmp_path)
db_name = 'userData.db'
self.file_loaded()
def file_loaded(self):
self.actionReindex.setEnabled(True)
self.actionObscure.setEnabled(True)
self.actionSort.setEnabled(True)
self.combo_grouping.setEnabled(True)
self.combo_category.setEnabled(True)
self.actionSave.setEnabled(False)
self.actionSave_As.setEnabled(True)
self.actionCollapse_All.setEnabled(True)
self.actionExpand_All.setEnabled(True)
self.actionSelect_All.setEnabled(True)
self.actionUnselect_All.setEnabled(True)
self.menuTitle_View.setEnabled(True)
self.total.setText('**0**')
self.selected.setText('**0**')
try:
self.viewer_window.close()
except:
pass
self.switchboard(self.combo_category.currentText())
def save_file(self):
if not self.save_filename:
return self.save_as_file()
else:
self.zip_file()
def save_as_file(self):
fname = ()
if not self.save_filename:
now = datetime.now().strftime('%Y-%m-%d')
fname = QFileDialog.getSaveFileName(self, _('Save archive'), f'{self.working_dir}/MODIFIED_{now}.jwlibrary', _('JW Library archives')+'(*.jwlibrary)')
else:
fname = QFileDialog.getSaveFileName(self, _('Save archive'), self.save_filename, _('JW Library archives')+'(*.jwlibrary)')
if not fname[0]:
self.statusBar.showMessage(' '+_('NOT saved!'), 4000)
return False
elif Path(fname[0]) == self.current_archive:
reply = QMessageBox.critical(self, _('Save'), _("It's recommended to save under another name.\nAre you absolutely sure you want to replace the original?"),
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.No:
return self.save_file()
self.save_filename = fname[0]
self.working_dir = Path(fname[0]).parent
self.current_archive = self.save_filename
self.status_label.setText(f'{Path(fname[0]).stem} ')
self.zip_file()
def zip_file(self):
def update_manifest():
with open(f'{tmp_path}/manifest.json', 'r') as json_file:
m = json.load(json_file)
m['name'] = APP
m['creationDate'] = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
m['userDataBackup']['deviceName'] = f'{APP}_{VERSION}'
m['userDataBackup']['lastModifiedDate'] = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
sha256hash = FileHash('sha256')
m['userDataBackup']['hash'] = sha256hash.hash_file(f'{tmp_path}/{db_name}')
m['userDataBackup']['databaseName'] = db_name
con = sqlite3.connect(f'{tmp_path}/{db_name}')
con.execute('UPDATE LastModified SET LastModified = ?;', (m['userDataBackup']['lastModifiedDate'],))
con.commit()
con.close()
with open(f'{tmp_path}/manifest.json', 'w') as json_file:
json.dump(m, json_file, indent=None, separators=(',', ':'))
update_manifest()
with ZipFile(self.save_filename, 'w', compression=ZIP_DEFLATED) as newzip:
files = os.listdir(tmp_path)
for f in files:
newzip.write(f'{tmp_path}/{f}', f)
self.archive_saved()
def archive_modified(self):
self.modified = True
self.actionSave.setEnabled(True)
self.actionSave.setProperty('icon_name', 'save')
self.actionSave_As.setEnabled(True)
self.status_label.setStyleSheet('font: italic;')
def archive_saved(self):
self.modified = False
self.actionSave.setEnabled(False)
self.status_label.setStyleSheet('font: normal;')
self.statusBar.showMessage(' '+_('Saved'), 4000)
def export_menu(self):
if self.combo_category.currentText() == _('Notes') or self.combo_category.currentText() == _('Annotations'):
submenu = QMenu(self)
italic_font = QFont()
italic_font.setItalic(True)
action1 = QAction(_('MS Excel file'), self)
action1.setFont(italic_font)
action2 = QAction(_('Custom text file'), self)
action2.setFont(italic_font)
action3 = QAction(_('Markdown files'), self)
action3.setFont(italic_font)
action1.triggered.connect(lambda: self.export_items('xlsx'))
action2.triggered.connect(lambda: self.export_items('txt'))
action3.triggered.connect(lambda: self.export_items('md'))
submenu.addAction(action1)
submenu.addAction(action2)
submenu.addAction(action3)
submenu.exec(self.button_export.mapToGlobal(self.button_export.rect().bottomLeft()))
else:
self.export_items('')
def export_items(self, form):
def process_issue(i):
issue = str(i)
yr = issue[0:4]
m = issue[4:6]
d = issue[6:]
if d == '00':
d = ''
else:
d = '-' + d
return f'{yr}-{m}{d}'
def export_file(category, form):
now = datetime.now().strftime('%Y-%m-%d')
if category == _('Highlights') or category == _('Bookmarks'):
return QFileDialog.getSaveFileName(self, _('Export file'), f'{self.working_dir}/JWL_{category}_{now}.txt', _('Text files')+' (*.txt)')[0]
elif category == _('Playlists'):
return QFileDialog.getSaveFileName(self, _('Export file'), f'{self.working_dir}/JWL_{category}_{now}.jwlplaylist', _('JW Library playlists')+' (*.jwlplaylist)')[0]
else:
if form == 'xlsx':
return QFileDialog.getSaveFileName(self, _('Export file'), f'{self.working_dir}/JWL_{category}_{now}.xlsx', _('MS Excel files')+' (*.xlsx)')[0]
elif form == 'txt':
return QFileDialog.getSaveFileName(self, _('Export file'), f'{self.working_dir}/JWL_{category}_{now}.txt', _('Text files')+' (*.txt)')[0]
else:
return QFileDialog.getExistingDirectory(self, _('Export directory'), f'{self.working_dir}/', QFileDialog.ShowDirsOnly)
def create_xlsx(fields):
last_field = fields[-1]
wb = Workbook(fname)
wb.set_properties({'comments': _('Exported from')+f' {current_archive} '+_('by')+f' {APP} ({VERSION})\n'+_('on')+f" {datetime.now().strftime('%Y-%m-%d @ %H:%M:%S')}"})
bold = wb.add_format({'bold': True})
ws = wb.add_worksheet(APP)
ws.write_row(row=0, col=0, cell_format=bold, data=fields)
ws.autofilter(first_row=0, last_row=99999, first_col=0, last_col=len(fields)-1)
for index, item in enumerate(item_list):
row = map(lambda field_id: item.get(field_id, ''), fields)
ws.write_row(row=index+1, col=0, data=row)
ws.write_string(row=index+1, col=len(fields)-1, string=item_list[index][last_field]) # overwrite any that may have been formatted as URLs
ws.freeze_panes(1, 0)
ws.set_column(0, 2, 20)
ws.set_column(3, len(fields)-1, 12)
wb.close()
def export_header(category):
# Note: invisible char on first line to force UTF-8 encoding
return category + '\n \n' + _('Exported from') + f' {current_archive}\n' + _('by') + f' {APP} ({VERSION}) ' + _('on') + f" {datetime.now().strftime('%Y-%m-%d @ %H:%M:%S')}\n" + '*'*76
def export_annotations(fname):
def get_annotations():
sql = f'''
SELECT TextTag,
Value,
l.DocumentId doc,
l.IssueTagNumber,
l.KeySymbol,
CAST (TRIM(TextTag, 'abcdefghijklmnopqrstuvwxyz') AS INT) i
FROM InputField
LEFT JOIN
Location l USING (
LocationId
)
WHERE LocationId IN {items}
ORDER BY doc, i;
'''
for row in con.execute(sql).fetchall():
item = {
'LABEL': row[0],
'VALUE': row[1].rstrip() if row[1] else '* '+_('NO TEXT')+' *',
'DOC': row[2],
'PUB': row[4]
}
if row[3] > 10000000:
item['ISSUE'] = row[3]
else:
item['ISSUE'] = None
item_list.append(item)
get_annotations()
if form == 'xlsx':
fields = ['PUB', 'ISSUE', 'DOC', 'LABEL', 'VALUE']
create_xlsx(fields)
elif form == 'txt':
with open(fname, 'w', encoding='utf-8') as f:
f.write(export_header('{ANNOTATIONS}'))
for item in item_list: