This repository was archived by the owner on Sep 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRssDBPanel.py
More file actions
2482 lines (2189 loc) · 129 KB
/
RssDBPanel.py
File metadata and controls
2482 lines (2189 loc) · 129 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
'''rssDB GUI interface
rssDB is a tool to collect and store SEC XBRL feeds.
'''
import os, sys, time, json, gettext, re, datetime, threading, traceback, logging, queue
from collections import defaultdict
from dateutil import tz
from datetime import timedelta
from lxml import html, etree
from urllib import request
from arelle import ViewWinRssFeed, ModelDocument, ViewWinProperties, FileSource
from arelle.FileSource import openFileSource
from arelle.ViewWinList import ViewList
from arelle.Locale import format_string
from arelle.ModelXbrl import ModelXbrl, load as mXLoad
from arellepy.HelperFuncs import chkToList
from arelle.CntlrWinTooltip import ToolTip
from arelle.UiUtil import checkbox, gridCombobox, label, gridCell
from arelle.ViewWinTree import ViewTree
from arellepy.CntlrPy import CntlrPy, runFormulaFromDBonRssItems, makeFormulaDict
from arellepy.HelperFuncs import getExtractedXbrlInstance
# from arelle.DialogUserPassword import askDatabase
try:
from .RssDB import rssDBConnection
from .Constants import DBTypes, pathToResources
from .CommonFunctions import _makeRssFeedLikeXml, storeInToXbrlDB, _dbTypes, dbProduct
except:
from rssDB.RssDB import rssDBConnection
from rssDB.Constants import DBTypes, pathToResources
from rssDB.CommonFunctions import _makeRssFeedLikeXml, storeInToXbrlDB, _dbTypes, dbProduct
import tkinter as tkr
from tkinter import messagebox, simpledialog
from tkinter import filedialog
try:
import tkinter.ttk as ttk
except ImportError:
import ttk
# store UIs dependent on connection to handle when disconnecting while those UIs are still open.
con_dependent_ui = []
currDir = os.path.dirname(os.path.abspath(__file__))
# testing stuff
setConfigDir = None
targetResDir = None
getQueue_render = False
getQueue_update = False
MAKEDOTS_RSSDBPANEL = dict()
def dotted(cntlr, _key, xtext='Processing'):
'''Just let me know you are alive!'''
global MAKEDOTS_RSSDBPANEL
n = 1
while MAKEDOTS_RSSDBPANEL.get(_key, False):
_xtext = xtext + '.'*n
cntlr.waitForUiThreadQueue()
cntlr.uiThreadQueue.put((cntlr.showStatus,[_xtext]))
if n >=15:
n = 1
else:
n+=1
time.sleep(.8)
cntlr.waitForUiThreadQueue()
cntlr.uiThreadQueue.put((cntlr.showStatus,['']))
return
with open(os.path.join(pathToResources,'industryTree.json'), 'r') as industries:
res = json.load(industries)
def flatenIndustry(a: dict, res=dict()):
for k,v in a.items():
res[k] = v['description']
if 'children' in v.keys():
flatenIndustry(v['children'], res)
return res
flatIndustry = flatenIndustry(res)
industryCodesSelection = tuple()
DBDescriptions = ("Postgres", "SQLite", "MongoDB")
searchResults = 0
def makeWeight(frame, columns=True, rows=True, _weight=1):
cols, _rows = frame.grid_size()
if columns:
for c in range(0, cols):
frame.columnconfigure(c, weight=_weight)
if rows:
for r in range(0, _rows):
frame.rowconfigure(r, weight=_weight)
return
def toolBarExtender(cntlr, toolbar):
addTosysPath = cntlr.config.setdefault('rssDBaddToSysPath', [])
if addTosysPath:
for p in addTosysPath:
sys.path.append(p)
def openRssDBPanel(btn, cntlr=cntlr):
btn.config(state='disabled')
topL = tkr.Toplevel(cntlr.parent)
topL.title('SEC XBRL RSS DB')
frame_canvas = tkr.Frame(topL)
frame_canvas.grid(row=0, column=0, sticky=tkr.NSEW)
f = rssDBFrame(frame_canvas,cntlr=cntlr) #canvas
f.grid(row=0, column=0, sticky=tkr.NSEW, padx=3, pady=3)
makeWeight(frame_canvas)
makeWeight(topL)
def closeAction():
confirm = True
if f.dbConnection:
if f.dbConnection.checkConnection():
confirm = tkr.messagebox.askyesno(title=_('Exit RSS DB Connection'),
message=_('Closing this window will disconnect current connection\n\nDo you want to proceed?'), icon='warning')
if confirm:
chk = f.disconnectDB(1)
if chk:
cntlr.parent.focus_set()
btn.config(state='normal')
topL.destroy()
else:
return
else:
return
topL.protocol("WM_DELETE_WINDOW", closeAction)
if cntlr.isMac:
toolbarButtonPadding = 1
else:
toolbarButtonPadding = 4
tbControl = ttk.Separator(toolbar, orient=tkr.VERTICAL)
column, row = toolbar.grid_size()
tbControl.grid(row=0, column=column, padx=6)
image = os.path.join(currDir, 'resources/rssIcon.png')
image = tkr.PhotoImage(file=image)
cntlr.toolbar_images.append(image)
tbControl = ttk.Button(toolbar, image=image, command= lambda: openRssDBPanel(tbControl, cntlr), style="Toolbutton", padding=toolbarButtonPadding)
ToolTip(tbControl, _('Launch rssDB panel'))
column, row = toolbar.grid_size()
tbControl.grid(row=0, column=column)
return
def rssDB_showLoadedXbrl(cntlr, modelXbrl, attach, selectTopView=False, queryParams=None, q=None):
global searchResults
conParams = cntlr.dbConnection.conParams
conName = '{}{} - {}'.format(conParams.get('host', False) + '/' if conParams.get('host', False) else '',
os.path.basename(conParams.get('database', '')) if conParams.get('database', '') else '',
conParams.get('product', ''))
startedAt = time.time()
currentAction = "setting title"
topView = None
cntlr.currentView = None
try:
if attach:
modelXbrl.closeViews()
cntlr.parent.title(_("arelle - {0}").format(
os.path.basename(modelXbrl.modelDocument.uri)))
cntlr.setValidateTooltipText()
if modelXbrl.modelDocument.type == ModelDocument.Type.RSSFEED:
currentAction = "view of RSS feed"
# ViewWinRssFeed.viewRssFeed(modelXbrl, cntlr.tabWinTopRt)
searchResults +=1
rssDBviewRssFeed(modelXbrl, cntlr.tabWinTopRt, 'Search Result #{} {}'.format(str(searchResults), conName), queryParams, q)
topView = modelXbrl.views[-1]
else:
pass
currentAction = "property grid"
ViewWinProperties.viewProperties(modelXbrl, cntlr.tabWinTopLeft)
currentAction = "log view creation time"
viewTime = time.time() - startedAt
modelXbrl.profileStat("view", viewTime)
cntlr.addToLog(format_string(cntlr.modelManager.locale,
_("views %.2f secs"), viewTime))
if selectTopView and topView:
topView.select()
cntlr.currentView = topView
currentAction = "plugin method CntlrWinMain.Xbrl.Loaded"
except Exception as err:
msg = _("Exception preparing {0}: {1}, at {2}").format(
currentAction,
err,
traceback.format_tb(sys.exc_info()[2]))
tkr.messagebox.showwarning(_("Exception preparing view"),msg, parent=cntlr.parent)
cntlr.addToLog(msg)
cntlr.showStatus(_("Ready..."), 2000)
return
def rssDB_backgroundLoadXbrl(cntlr, filesource, importToDTS, selectTopView, queryParams=None, q=None):
'''Based on CntlrWinMain.backgroundLoadXbrl'''
startedAt = time.time()
try:
cntlr.dbConnection.searchResultsModelXbrl.reload('Updating View', True)
except:
try:
action = _("loaded")
profileStat = "load"
modelXbrl = cntlr.modelManager.load(filesource, _("views loading"), checkModifiedTime=False) # check modified time if GUI-loading from web
cntlr.dbConnection.searchResultsModelXbrl = modelXbrl
except ModelDocument.LoadingException:
cntlr.showStatus(_("Loading terminated, unrecoverable error"), 15000)
return
except Exception as err:
msg = _("Exception loading {0}: {1}, at {2}").format(
filesource.url,
err,
traceback.format_tb(sys.exc_info()[2]))
cntlr.addToLog(msg)
cntlr.showStatus(_("Loading terminated, unrecoverable error"), 15000)
return
if modelXbrl and modelXbrl.modelDocument:
statTime = time.time() - startedAt
modelXbrl.profileStat(profileStat, statTime)
cntlr.addToLog(format_string(cntlr.modelManager.locale,
_("%s in %.2f secs"),
(action, statTime)))
cntlr.showStatus(_("{0}, preparing views").format(action))
cntlr.waitForUiThreadQueue() # force status update
cntlr.uiThreadQueue.put((rssDB_showLoadedXbrl, [cntlr, modelXbrl, importToDTS, selectTopView, queryParams, q]))
else:
cntlr.addToLog(format_string(cntlr.modelManager.locale,
_("not successfully %s in %.2f secs"),
(action, time.time() - startedAt)))
cntlr.showStatus(_("Loading terminated"), 15000)
return
class rssDBFrame(tkr.Frame):
def __init__(self, master, cntlr=None, allInOne=False, **kw):
super().__init__(master, **kw)
if not cntlr:
cntlr = CntlrPy(instConfigDir=setConfigDir, useResDir=targetResDir, logFileName="logToBuffer")
_modelXbrl = ModelXbrl(cntlr.modelManager)
gettext.install('Arelle')
self.allInOne = allInOne
self.runGetStat = True
self.cntlr = cntlr
self.getQueue = True
self.multiprocessQueue = None #queue.Queue()
self.parent = master
self.dbConnection = None
self.priorDatabaseSettingsList = cntlr.config.setdefault('rssDBconnection', [])
self.currentSettingSelectionIndex = len(self.priorDatabaseSettingsList)-1 if len(self.priorDatabaseSettingsList) else 0
self.connectionFrame = tkr.LabelFrame(self, text = _('Database Connection'), padx=5, pady=5)
self.statFrame = tkr.Frame(self.connectionFrame)
self.connectionIndicatorCanvas = tkr.Canvas(self.statFrame, width=12, height=12)
self.connectionIndicatorCanvas.grid(row=0, column=0, sticky=tkr.W, padx=2, pady=2)
self.connectionIndicator = self.connectionIndicatorCanvas.create_oval(2,2,10,10, fill='red')
self.connectionIndicatorText = tkr.Label(self.statFrame, text=_('Not Connected to DB'), wraplength=350, justify="left")
self.connectionIndicatorText.grid(row=0, column=1, columnspan=6, sticky=tkr.W)
self.statFrame.grid(row=0, column=0, columnspan=7, sticky=(tkr.N, tkr.S, tkr.E, tkr.W), padx=2, pady=2)
self.btn_connectToDb = tkr.Button(self.connectionFrame, text="Connect To RSS DB", command=self.connectToDB,) # width=13
self.btn_disconnectDB = tkr.Button(self.connectionFrame,text="Disconnect RSS DB", command=lambda: self.disconnectDB(confirm=True),) #width=13
ToolTip(self.btn_disconnectDB, _('Disconnet Current Connection'))
self.btn_disconnectDB.config(state='disabled')
self.btn_checkDbStat = tkr.Button(self.connectionFrame, text="Get DB Stat", command= lambda: self.backgroundGetDbStats(self.dbConnection),) #width=8
ToolTip(self.btn_checkDbStat, _('Display DB stats in Arelle message panel'))
self.btn_checkDbStat.config(state='disabled')
self.btn_showReport = tkr.Button(self.connectionFrame, text="DB Report", command= self.startDash, ) #width=8
ToolTip(self.btn_showReport, _('Runs a web app the shows information about the submissions in the database, requires pandas, plotly and other packages '
'you will be prompted for the path where these packages are installed (probably a python virtual environment)'), wraplength=360)
self.btn_showReport.config(state='disabled')
self.btn_connectToDb.grid(row=1, column=0, columnspan=3, sticky=tkr.EW, pady=1, padx=1)
self.btn_disconnectDB.grid(row=1, column=3, columnspan=2, sticky=tkr.EW, pady=1, padx=1)
self.btn_checkDbStat.grid(row=1, column=5, columnspan=1, sticky=tkr.EW, pady=1, padx=1)
self.btn_showReport.grid(row=1, column=6, columnspan=1, sticky=tkr.EW, pady=1, padx=1)
r = 0
self.connectionFrame.grid(row=r, column=0, sticky=(tkr.N, tkr.S, tkr.E, tkr.W), padx=5, pady=5)
if allInOne:
r+=1
self.updateDBFrame = rssDBUpdateSettings(self, text=_('Update RSS DB'), padx=5, pady=5)
self.updateDBFrame.grid(row=r, column=0, sticky=(tkr.N, tkr.S, tkr.E, tkr.W), padx=5, pady=5)
self.updateDBFrame.rssDBFrame = self.master
self.updateDBFrame.update_btn.config(state='disabled')
r+=1
self.queryFrame = rssDBSearchDBPanel(self, text=_('Search RSS DB'), padx=5, pady=5)
self.queryFrame.grid(row=r, column=0, sticky=(tkr.N, tkr.S, tkr.E, tkr.W), padx=5, pady=5)
self.queryFrame.rssDBFrame = self
self.queryFrame.searchDB_btn.config(state='disabled')
# r+=1
# self.TestQueryFrame = tkr.LabelFrame(self, text=_('Search DB'), padx=5,pady=5)
# self.btn_industrySelect = tkr.Button(self.TestQueryFrame,text=_("Select Industry"), command=self.openIndustrySelector)
# self.btn_showIndustrySelection = tkr.Button(self.TestQueryFrame,text=_("Selection"), command=self.showSelections)
# self.btn_TestSearch = tkr.Button(self.TestQueryFrame, text=_("Test Search"), command= self.testSearch)
# self.btn_industrySelect.grid(row=0, column=0, sticky=tkr.W, pady=1, padx=1)
# self.btn_showIndustrySelection.grid(row=0, column=1, sticky=tkr.W, pady=1, padx=1)
# self.btn_TestSearch.grid(row=0, column=2, sticky=tkr.W, pady=1, padx=1)
# self.TestQueryFrame.grid(row=r, column=0, sticky=(tkr.N, tkr.S, tkr.E, tkr.W), padx=5, pady=5)
else:
r+=1
self.btn_updateDB = tkr.Button(self, text=_('Update Database (opens another window)'), command=self.btn_cmd_updateDB)
self.btn_updateDB.grid(row=r, column=0, sticky=(tkr.N, tkr.S, tkr.E, tkr.W), padx=5, pady=5)
ToolTip(self.btn_updateDB, text=_("Update SEC XBRL rss Feed database with specified options, opens in a new window"), wraplength=360)
self.btn_updateDB.config(state='disabled')
r+=1
self.btn_searchDB = tkr.Button(self, text=_('Search DB (opens another window)'), command=self.btn_cmd_searchDB)
self.btn_searchDB.grid(row=r, column=0, sticky=(tkr.N, tkr.S, tkr.E, tkr.W), padx=5, pady=5)
ToolTip(self.btn_searchDB, text=_("Search SEC XBRL rss Feed database with specified options, opens in a new window"), wraplength=360)
self.btn_searchDB.config(state='disabled')
makeWeight(self)
makeWeight(self.connectionFrame)
# self.bind("<Destroy>", self._destroy)
def btn_cmd_updateDB(self):
global con_dependent_ui
self.btn_updateDB.config(state='disabled')
topL = tkr.Toplevel(self)
topL.title(_('UPDATE SEC XBRL RSS DB'))
self.updateDBFrame = rssDBUpdateSettings(topL, text=_('Update RSS DB'), padx=5, pady=5)
self.updateDBFrame.grid(row=0, column=0, sticky=tkr.NSEW, padx=5, pady=5)
self.updateDBFrame.update_btn.config(state='normal')
topL.rssDBFrame = self
self.updateDBFrame.rssDBFrame = self
con_dependent_ui.append(topL)
def closeAction():
global con_dependent_ui
if getattr(self.updateDBFrame, 'setAutoUpdate', False):
confirm = messagebox.askyesno(_('Confirm Closing Update Settings'), _('Closing update settings will stop currently active DB auto-update.\n\nDo you want to proceed?'), parent=self)
if confirm:
self.stopAutoUpdate()
else:
return
delattr(topL.rssDBFrame, 'updateDBFrame')
con_dependent_ui.remove(topL)
self.btn_updateDB.config(state='normal')
topL.destroy()
topL.close = closeAction
topL.protocol("WM_DELETE_WINDOW", closeAction)
makeWeight(topL)
def btn_cmd_searchDB(self):
global con_dependent_ui
self.btn_searchDB.config(state='disabled')
topL = tkr.Toplevel(self)
topL.title(_('SEARCH SEC XBRL RSS DB'))
self.queryFrame = rssDBSearchDBPanel(topL, text=_('Search RSS DB'), padx=5, pady=5)
self.queryFrame.grid(row=0, column=0, sticky=tkr.NSEW, padx=5, pady=5)
self.queryFrame.searchDB_btn.config(state='normal')
topL.rssDBFrame = self
self.queryFrame.rssDBFrame = self
con_dependent_ui.append(topL)
def closeAction():
global con_dependent_ui
delattr(topL.rssDBFrame, 'queryFrame')
con_dependent_ui.remove(topL)
self.btn_searchDB.config(state='normal')
topL.destroy()
return
topL.close = closeAction
topL.protocol("WM_DELETE_WINDOW", closeAction)
makeWeight(topL)
return
def startDash(self):
dbReport = self.dbConnection.startDBReport()
if dbReport:
msg = "DB Report started at {}".format(dbReport[1])
messagebox.showinfo(title="RSS DB info", message=msg, parent=self.cntlr.parent)
self.cntlr.addToLog(msg, messageCode="RssDB.Info", file="", level=logging.INFO)
# except Exception as e:
# messagebox.showerror(title="RSS DB error", message=traceback.format_exc(), parent=self.cntlr.parent)
# self.cntlr.addToLog(traceback.format_exc(), messageCode="RssDB.Error", file="", level=logging.ERROR)
return
def stopAutoUpdate(self):
if getattr(self, 'backgroundUpdateConn', False):
con = self.backgroundUpdateConn
if con.autoUpdateSet:
con.autoUpdateSet = False
if con.updateStarted:
self.cntlr.addToLog(_('Auto-updated will be stopped after current update'), messageCode="RssDB.Info", file=self.dbConnection.conParams.get('databae', ""), level=logging.INFO)
else:
self.cntlr.addToLog(_('No connection is set to auto-update currently'), messageCode="RssDB.Info", file=self.dbConnection.conParams.get('databae', ""), level=logging.INFO)
return
def _updateDB(self, cntrl, connParams: dict, doAllParams: dict):
global getQueue_update
self.updateDBFrame.update_btn.config(state='disabled')
color = self.updateDBFrame.btn_stopAutoUpdate.cget("background")
text = 'Updating Now'
if self.updateDBFrame.setAutoUpdate:
self.updateDBFrame.btn_stopAutoUpdate.config(state='normal', bg='orange', fg='white')
text = 'Auto-Update ON'
try:
self.backgroundUpdateConn = rssDBConnection(cntrl, **connParams, createDB=False)
self.updateDBFrame.update_btn.config(text=text)
self.backgroundUpdateConn.doAll(**doAllParams)
except Exception as e:
getQueue_update = False
tkr.messagebox.showerror(title='RSS DB Error - updateDB', message=str(e) + '\n' + traceback.format_exc())
self.backgroundUpdateConn.close()
self.backgroundUpdateConn = None
if hasattr(self, 'updateDBFrame'): # might happen after window is closed
self.updateDBFrame.setAutoUpdate = False
self.updateDBFrame.update_btn.config(text="Update DB")
self.updateDBFrame.update_btn.config(state='normal')
self.updateDBFrame.btn_stopAutoUpdate.config(state='disabled', bg=color, fg='black')
getQueue_update = False
return
def _backgroundGetQ(self):
global getQueue_update
cntlr = self.cntlr
callback = {'showStatus': cntlr.showStatus, 'addToLog': cntlr.addToLog}
while getQueue_update:
if not self.multiprocessQueue.empty():
callbackName, args = self.multiprocessQueue.get()
cntlr.waitForUiThreadQueue()
cntlr.uiThreadQueue.put((callback[callbackName],args))
return
def backGroundUpdateDB(self, doAllArgs: dict = None):
global getQueue_update
connArgs = {k:v for k, v in self.dbConnection.conParams.items() if not k == 'cntlr'}
doAllArgs['q'] = self.multiprocessQueue
getQueue_update = True
self.t1 = threading.Thread(target=self._updateDB, args=(self.cntlr, connArgs, doAllArgs), daemon=True)
# self.t2 = threading.Thread(target=self._backgroundGetQ, daemon=True)
# self.t2.start()
self.t1.start()
return
def backgroundSearchDB(self, params:dict):
conn = self.dbConnection
if not conn or not getattr(conn, 'conParams', False):
self.cntlr.addToLog(_('No SEC RSS DB Connection'), messageCode="RssDB.Info", file="", level=logging.INFO)
self.cntlr.addToLog('')
self.cntlr.logView.listBox.see(tkr.END)
return
if conn.product == 'sqlite':
_conParams = conn.conParams
_conParams['cntlr'] = self.cntlr
conn = rssDBConnection(**_conParams)
if not conn.checkConnection():
self.cntlr.addToLog(_('No SEC RSS DB Connection'), messageCode="RssDB.Info", file="", level=logging.INFO)
self.cntlr.logView.listBox.see(tkr.END)
return
elif conn.checkConnection():
res = conn.searchFilings(**params, getFiles=True)
saveAs = None
if self.dbConnection.searchResultsModelXbrl and os.path.isfile(self.dbConnection.searchResultsTempFile):
# save results to same temp file
saveAs = self.dbConnection.searchResultsTempFile
# tmpF = _makeRssFeedLikeXml(conn, res['filings'], res['files'], showcount=False)[0]
tmpF = _makeRssFeedLikeXml(conn=self.dbConnection, dbFilings_dicts=res['filings'], dbFiles_dicts=res['files'], saveAs=saveAs, showcount=False)[0]
self.dbConnection.searchResultsTempFile = tmpF
if hasattr(self.cntlr, 'hasGui'):
filesource = FileSource.FileSource(tmpF, self.cntlr)
threading.Thread(target=rssDB_backgroundLoadXbrl, args=(self.cntlr, filesource,False,False, params, self.multiprocessQueue), daemon=True).start()
elif hasattr(self.cntlr, 'runKwargs'):
self.cntlr.runKwargs(file=tmpF, keepOpen='')
ViewWinRssFeed.viewRssFeed(self.cntlr.modelManager.modelXbrl, self.tabWin)
if hasattr(self, 'queryFrame'):
self.queryFrame.searchDB_btn.config(state='normal')
return
def _destroy(self, event=None):
self.disconnectDB(destroy=1)
self.destroy()
return
def addPriorDatabaseSettings(self, dbSettings: tuple):
'''Cache up to 6 entries for database settings'''
dbSettingsList = list(dbSettings)
dbSettingsList[3] = '' # don't save password
# Add last connection to end of list
if dbSettingsList in self.priorDatabaseSettingsList:
self.priorDatabaseSettingsList.remove(dbSettingsList)
# if not dbSettingsList in self.priorDatabaseSettingsList:
self.priorDatabaseSettingsList.append(dbSettingsList)
if len(self.priorDatabaseSettingsList) > 6:
del self.priorDatabaseSettingsList[0]
self.cntlr.saveConfig()
return
def disconnectDB(self, destroy=0, confirm=True):
global con_dependent_ui
_confirm = True
msg = None
res = True
if self.dbConnection and self.dbConnection.checkConnection():
if confirm and len(con_dependent_ui):
_confirm = tkr.messagebox.askyesno(title=_('Disconnect RSS DB'),
message=_('Disconnecting from db will close the following windows:\n{}\n\nDo you want to proceed?').format('\n'.join(['- '+x.title() for x in con_dependent_ui])), icon='warning')
if _confirm:
while len(con_dependent_ui):
con_dependent_ui[0].close()
conParams = self.dbConnection.conParams
msg = _('[{}] Disconnected from {}{} - {}').format(datetime.datetime.today().strftime(
"%Y-%m-%d %H:%M:%S"), conParams['host'] + '/' if conParams['host'] else '', conParams['database'], self.dbConnection.product)
self.dbConnection.close()
chk = self.dbConnection.checkConnection()
if chk:
tkr.messagebox.showwarning(_("RSS DB message"),_("Could not disconnect, Connection still active!"))
res = False
else:
try:
self.cntlr.addToLog(msg if msg else _('disconnected!'), messageCode="RssDB.Info", file="", level=logging.INFO)
self.cntlr.addToLog('')
self.cntlr.logView.listBox.see(tkr.END)
except:
pass
if not destroy:
if hasattr(self, 'updateDBFrame'):
self.updateDBFrame.update_btn.config(state='disabled')
if hasattr(self, 'queryFrame'):
self.queryFrame.searchDB_btn.config(state='disabled')
if hasattr(self, 'btn_updateDB'):
self.btn_updateDB.config(state='disabled')
if hasattr(self, 'btn_searchDB'):
self.btn_searchDB.config(state='disabled')
# self.updateDBFrame.update_btn.config(state='disabled')
self.btn_disconnectDB.config(state='disabled')
self.btn_checkDbStat.config(state='disabled')
self.btn_showReport.config(state='disabled')
self.connectionIndicatorCanvas.itemconfig(self.connectionIndicator, fill='red')
self.connectionIndicatorText['text'] = _('Not Connected to DB')
self.btn_connectToDb.config(state='normal')
else:
res = False
return res
def backgroundGetDbStats(self, conn):
if conn:
try:
if conn.product == 'sqlite':
_conParams = conn.conParams
_conParams['cntlr'] = self.cntlr
conn = rssDBConnection(**_conParams)
# conn.showStatus = self.appendLines
dbStats = conn.getDbStats()['textResult']
l = ['Database Stats ({}) [{}]:'.format(dbStats['DatabaseSize'], datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S"))]
if dbStats:
_text = {'CountFeeds': 'Count of Feeds', 'LatestFeed': 'Latest Feed Month', 'EarliestFeed': 'Earliest Feed Month',
'CountFilings': 'Count of Filings', 'LatestFiling':'Latest Filing Publication Date',
'EarliestFiling':'Earliest Filing Publication Date', 'CountFilers': 'Count of Filers', 'CountFiles': 'Count of Files',
'missingTables': 'Missing Tables', 'noConnection': 'No DB Connection', 'missingCollections': 'Missing Collections', 'LastUpdate': 'Last Updated', 'DatabaseSize': 'DB Size'}
for k, v in dbStats.items():
if v.isdigit():
l.append('{}: {:,}'.format(_text[k],int(v)))
else:
l.append('{}: {}'.format(_text[k],v))
for _l in l:
self.cntlr.addToLog(_l, messageCode="RssDB.Info", file="", level=logging.INFO)
self.cntlr.addToLog('')
self.cntlr.logView.listBox.see(tkr.END)
if conn.product == 'sqlite':
conn.close()
del conn
self.cntlr.logView.listBox.see(tkr.END)
except Exception as e:
tkr.messagebox.showerror(title='RSS DB Error - getDBStats', message=traceback.format_exc(), parent=self.cntlr.parent)
else:
tkr.messagebox.showerror(title='RSS DB Error - getDBStats', message=_('No DB Connection'))
return
def connectToDB(self):
priorSettings = self.priorDatabaseSettingsList[-1] if len(self.priorDatabaseSettingsList) else None
res = self.askDatabase(self, priorSettings)
if res and self.runGetStat:
threading.Thread(target=self.backgroundGetDbStats, args=[self.dbConnection], daemon=True).start()
if not self.runGetStat:
self.runGetStat = True
try:
self.cntlr.logView.listBox.see(tkr.END)
except:
pass
return
def askDatabase(self, parent, priorDatabaseSettings):
res = False
if isinstance(priorDatabaseSettings, (tuple, list)) and len(priorDatabaseSettings) == 10:
urlAddr, urlPort, user, password, database, schema, createSchema, createDB, timeout, dbType = priorDatabaseSettings
else:
urlAddr = urlPort = user = password = database = schema = createSchema = createDB = timeout = dbType = None
dialog = DialogRssDBConnect(parent, urlAddr=urlAddr, urlPort=urlPort, user=user, password=password,
createSchema=createSchema if createSchema else False,
createDB=createDB if createDB else False,
schema=schema, database=database, timeout=timeout, dbType=dbType, showHost=False, showUrl=True,
showUser=True, showRealm=False, showDatabase=True)
if dialog.accepted:
res = True
return res
def showSelections(self):
global industryCodesSelection
py = sys.executable
self.cntlr.addToLog(sys.argv)
return
def openIndustrySelector(self):
selector = industrySelector(self, self.btn_industrySelect)
return
class DialogRssDBConnect(tkr.Toplevel):
"""Based on arelle/DialogUserPassword"""
def __init__(self, parent:rssDBFrame, urlAddr=None, urlPort=None, user=None, password=None, database=None,
timeout=None, dbType=None, schema=None, createSchema=False, createDB=False,
showUrl=False, showUser=False, showHost=True, showRealm=True, showDatabase=False,
userLabel=None, passwordLabel=None, hidePassword=True):
super(DialogRssDBConnect, self).__init__(parent)
self.parent = parent
parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.parent.master.master.geometry())
dialogX = int(parentGeometry.group(3))
dialogY = int(parentGeometry.group(4))
self.accepted = False
# self.transient(self.parent)
self.title(_("Connect to SEC XBRL Filings RSS DB"))
self.dbTypeVar = tkr.StringVar()
self.urlAddrVar = tkr.StringVar()
self.urlAddrVar.set(urlAddr if urlAddr else "")
self.urlPortVar = tkr.StringVar()
self.urlPortVar.set(urlPort if urlPort else "")
self.userVar = tkr.StringVar()
self.userVar.set(user if user else "")
self.passwordVar = tkr.StringVar()
self.passwordVar.set(password if password else "")
self.databaseVar = tkr.StringVar()
self.databaseVar.set(database if database else "")
self.timeoutVar = tkr.StringVar()
self.timeoutVar.set(timeout if timeout else "")
self.schemaVar = tkr.StringVar()
self.schemaVar.set(schema if schema else '')
self.createSchema = createSchema
self.createDatabase = createDB
self.enabledWidgets = []
frame = tkr.LabelFrame(self, text=_("Connection Parameters"))
y = 0
dbTypeLabel = tkr.Label(frame, text=_("DB type:"), underline=0, name='dbTypeLabel', width=8, anchor='w')
dbTypeLabel.grid(row=y, column=0, sticky=tkr.W, pady=0, padx=3)
cbDbType = ttk.Combobox(frame, textvar=self.dbTypeVar, values = DBTypes, state='readonly', name='dbTypeCombobox')
cbDbType.set(dbType if dbType else DBTypes[0])
cbDbType.grid(row=y, column=1, columnspan=4, sticky=tkr.EW, pady=3, padx=3)
self.dbTypeVar.trace('w', lambda x,y,z: self.dbTypeModified(clear=False))
self.enabledWidgets.append(cbDbType)
cbDbType.focus_set()
y += 1
urlAddrLabel = tkr.Label(frame, text=_("Address:"), underline=0, name='addressLabel',width=8, anchor='w')
urlAddrEntry = tkr.Entry(frame, textvariable=self.urlAddrVar, name='addressEntry')
urlPortLabel = tkr.Label(frame, text=_("Port:"), underline=0, name='portLabel')
urlPortEntry = tkr.Entry(frame, textvariable=self.urlPortVar, name='portEntry', width=10)
# urlAddrEntry.focus_set()
urlAddrLabel.grid(row=y, column=0, sticky=tkr.W, pady=0, padx=3)
urlAddrEntry.grid(row=y, column=1, columnspan=2, sticky=tkr.EW, pady=3, padx=3)
urlPortLabel.grid(row=y, column=3, sticky=tkr.E, pady=3, padx=3)
urlPortEntry.grid(row=y, column=4, sticky=tkr.EW, pady=3, padx=3)
ToolTip(urlPortEntry, text=_("Enter URL address and port number \n"
" e.g., address: 168.1.2.3 port: 8080 \n"
" or address: proxy.myCompany.com port: 8080 \n"
" or leave blank to specify no proxy server"), wraplength=360)
self.enabledWidgets.append(urlAddrEntry)
self.enabledWidgets.append(urlPortEntry)
y += 1
userLabel = tkr.Label(frame, text=userLabel or _("User:"), underline=0, name='userLabel', width=8, anchor='w')
userEntry = tkr.Entry(frame, textvariable=self.userVar, name='userEntry')
userLabel.grid(row=y, column=0, sticky=tkr.W, pady=0, padx=3)
userEntry.grid(row=y, column=1, columnspan=4, sticky=tkr.EW, pady=3, padx=3)
self.enabledWidgets.append(userEntry)
y += 1
passwordLabel = tkr.Label(frame, text=passwordLabel or _("Password:"), underline=0, name='passwordLabel',width=8, anchor='w')
passwordEntry = tkr.Entry(frame, textvariable=self.passwordVar, show=("*" if hidePassword else None), name='passwordEntry')
passwordLabel.grid(row=y, column=0, sticky=tkr.W, pady=0, padx=3)
passwordEntry.grid(row=y, column=1, columnspan=4, sticky=tkr.EW, pady=3, padx=3)
self.enabledWidgets.append(passwordEntry)
y += 1
urlDatabaseLabel = tkr.Label(frame, text=_("Database:"), underline=0, name='databaseLabel',width=8, anchor='w')
urlDatabaseEntry = tkr.Entry(frame, textvariable=self.databaseVar, name= 'databaseEntry')
urlDatabaseLabel.grid(row=y, column=0, sticky=tkr.W, pady=0, padx=3)
urlDatabaseEntry.grid(row=y, column=1, columnspan=3, sticky=tkr.EW, pady=3, padx=3)
ToolTip(urlDatabaseEntry, text=_("Enter database name (optional) or leave blank"), wraplength=360)
self.enabledWidgets.append(urlDatabaseEntry)
image = tkr.PhotoImage(file=os.path.join(self.parent.cntlr.imagesDir, "toolbarOpenFile.gif"))
self._image = image
btn_sqlite_db_file = tkr.Button(frame, image=image, command=self.openSqliteFile, name='sqlFileButton')
btn_sqlite_db_file.grid(row=y, column=4, sticky=tkr.EW, pady=3, padx=3)
self.enabledWidgets.append(btn_sqlite_db_file)
y += 1
dummyLabelA = tkr.Label(frame, text='', name='databaseLabel',width=8, anchor='w')
dummyLabelA.grid(row=y, column=0, sticky=tkr.W, pady=0, padx=3)
self.createDatabaseCb = checkbox(frame, 1, y, columnspan=4, text=_("Create Database and Tables (sqlite and mongodb)"))
self.createDatabaseCb._name ='databaseCreate'
self.createDatabaseCb.var = self.createDatabase
self.createDatabaseCb.valueVar.set(1 if createDB else 0)
if self.dbTypeVar.get() == 'postgres':
self.createDatabaseCb.config(state='disabled')
self.createDatabaseCb.valueVar.set(0)
self.createDatabaseCb.grid(padx=3)
ToolTip(self.createDatabaseCb, text=_("Whether to database and tables if not existing - only sqlite and mongodb if user has privileges"), wraplength=360)
self.enabledWidgets.append(self.createDatabaseCb)
y += 1
dbSchemaLabel = tkr.Label(frame, text=_("Schema:"), underline=0, name='schemaLabel',width=8, anchor='w')
dbSchemaEntry = tkr.Entry(frame, textvariable=self.schemaVar, name='schemaEntry')
if not self.dbTypeVar.get() == 'postgres':
dbSchemaEntry.config(state='disabled')
dbSchemaLabel.grid(row=y, column=0, sticky=tkr.W, pady=0, padx=3)
dbSchemaEntry.grid(row=y, column=1, columnspan=4, sticky=tkr.EW, pady=3, padx=3)
ToolTip(dbSchemaEntry, text=_("(optional) Enter schema name or leave blank defaults to 'rssFeeds' - postgres only"), wraplength=360)
self.enabledWidgets.append(dbSchemaEntry)
y+=1
dummyLabelB = tkr.Label(frame, text='', name='databaseLabel',width=8, anchor='w')
dummyLabelB.grid(row=y, column=0, sticky=tkr.W, pady=0, padx=3)
self.createSchemaCb = checkbox(frame, 1, y, text=_("Create Schema and Tables"))
self.createSchemaCb._name ='schemaCreate'
self.createSchemaCb.var = self.createSchema
self.createSchemaCb.valueVar.set(1 if createSchema else 0)
if not self.dbTypeVar.get() == 'postgres':
self.createSchemaCb.config(state='disabled')
self.createSchemaCb.valueVar.set(0)
self.createSchemaCb.grid(padx=(3,10))
ToolTip(self.createSchemaCb, text=_("Whether to create schema and tables if not exiting - postgres only if user has privileges"), wraplength=360)
self.enabledWidgets.append(self.createSchemaCb)
y += 1
urlTimeoutLabel = tkr.Label(frame, text=_("Timeout:"), underline=0, name='timeoutLabel', width=8, anchor='w')
urlTimeoutEntry = tkr.Entry(frame, textvariable=self.timeoutVar, name='timeoutEntry')
urlTimeoutLabel.grid(row=y, column=0, sticky=tkr.W, pady=0, padx=3)
urlTimeoutEntry.grid(row=y, column=1, columnspan=4, sticky=tkr.EW, pady=0, padx=3)
ToolTip(urlTimeoutEntry, text=_("Enter timeout seconds (optional) or leave blank for default (60 secs.)"), wraplength=360)
self.enabledWidgets.append(urlTimeoutEntry)
y += 1
clearButton = tkr.Button(frame, text = _("Clear"), command= self.setDialogueEntries)
removeFromCacheButton = tkr.Button(frame, text = _("Remove"), command= self.clearCachedConns)
clearCacheButton = tkr.Button(frame, text = _("Clear Cache"), command= lambda: self.clearCachedConns(False))
prevButton = tkr.Button(frame, text = _("< Previous"), command= lambda: self.browseDbSettings(-1), width=8, anchor='w')
nextButton = tkr.Button(frame, text = _("Next >"), command= lambda: self.browseDbSettings(1))
prevButton.grid(row=y, column=0, sticky=tkr.EW, pady=0, padx=3)
clearButton.grid(row=y, column=2, sticky=tkr.EW, pady=3,padx=(3,1))
removeFromCacheButton.grid(row=y, column=3, sticky=tkr.EW, pady=3,padx=(3,1))
clearCacheButton.grid(row=y, column=1, sticky=tkr.EW, pady=3,padx=(3,1))
nextButton.grid(row=y, column=4, sticky=tkr.EW, pady=3, padx=3)
ToolTip(clearButton, text=_("Clear Form"), wraplength=360)
ToolTip(clearCacheButton, text=_("Removes all cached connections params"), wraplength=360)
ToolTip(removeFromCacheButton, text=_("Remove current entry from cache"), wraplength=360)
y += 1
okButton = tkr.Button(frame, text=_("Connect"), command=self.ok)
cancelButton = tkr.Button(frame, text=_("Cancel"), command=self.close)
cancelButton.grid(row=y, column=3, sticky=tkr.E, pady=3, padx=3)
okButton.grid(row=y, column=4, sticky=tkr.EW, pady=3, padx=3)
# showWidz = tkr.Button(frame, text=_("Show Widgets"), command=self.showWid)
# showWidz.grid(row=y, column=0, sticky=tkr.EW, pady=3, padx=3)
frame.grid(row=0, column=0, sticky=(tkr.N,tkr.S,tkr.E,tkr.W), padx=3, pady=3)
# frame.columnconfigure(1, weight=1)
self.__frame = frame
self.__namedWidgets = [x for x in frame.winfo_children() if not x._name.startswith('!')]
window = self.winfo_toplevel()
# window.columnconfigure(0, weight=1)
self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
makeWeight(self)
makeWeight(frame)
frame.columnconfigure(4, weight=0)
frame.columnconfigure(0, weight=0)
# self.resizable(True, True)
self.bind("<Return>", self.ok)
self.bind("<Escape>", self.close)
self.protocol("WM_DELETE_WINDOW", self.close)
self.grab_set()
self.dbTypeModified(clear=False)
self.wait_window(self)
def showWid(self):
# testing
# print(self.__namedWidgets)
# print([x._name for x in self.__namedWidgets])
pass
def openSqliteFile(self):
fileName = filedialog.askopenfilename(parent=self,
title=_("Open Sqlite File"),
initialdir=".",
filetypes=[(("Sqlite db files"), ".db .sdb .sqlite .db3 .s3db .sqlite3 .sl3 .db2 .s2db .sqlite2 .sl2")])
if fileName:
dbEntry = [x for x in self.__namedWidgets if x._name == 'databaseEntry'][0]
dbEntry.delete(0, tkr.END)
dbEntry.insert(0, fileName)
return
def dbTypeModified(self, clear=True, i=None, v=None, o=None):
widgets = {'dbTypeLabel':{'postgres': 'normal', 'sqlite': 'normal', 'mongodb':'normal'},
'dbTypeCombobox':{'postgres': 'normal', 'sqlite': 'normal', 'mongodb':'normal'},
'addressLabel':{'postgres': 'normal', 'sqlite': 'disabled', 'mongodb':'normal'},
'addressEntry':{'postgres': 'normal', 'sqlite': 'disabled', 'mongodb':'normal'},
'portLabel':{'postgres': 'normal', 'sqlite': 'disabled', 'mongodb':'normal'},
'portEntry':{'postgres': 'normal', 'sqlite': 'disabled', 'mongodb':'normal'},
'userLabel':{'postgres': 'normal', 'sqlite': 'disabled', 'mongodb':'normal'},
'userEntry':{'postgres': 'normal', 'sqlite': 'disabled', 'mongodb':'normal'},
'passwordLabel':{'postgres': 'normal', 'sqlite': 'disabled', 'mongodb':'normal'},
'passwordEntry':{'postgres': 'normal', 'sqlite': 'disabled', 'mongodb':'normal'},
'databaseLabel':{'postgres': 'normal', 'sqlite': 'normal', 'mongodb':'normal'},
'databaseEntry':{'postgres': 'normal', 'sqlite': 'normal', 'mongodb':'normal'},
'databaseCreate':{'postgres': 'disabled', 'sqlite': 'normal', 'mongodb':'normal'},
'sqlFileButton':{'postgres': 'disabled', 'sqlite': 'normal', 'mongodb':'disabled'},
'schemaLabel':{'postgres': 'normal', 'sqlite': 'disabled', 'mongodb':'disabled'},
'schemaEntry':{'postgres': 'normal', 'sqlite': 'disabled', 'mongodb':'disabled'},
'schemaCreate':{'postgres': 'normal', 'sqlite': 'disabled', 'mongodb':'disabled'},
'timeoutLabel':{'postgres': 'normal', 'sqlite': 'normal', 'mongodb':'normal'},
'timeoutEntry':{'postgres': 'normal', 'sqlite': 'normal', 'mongodb':'normal'}}
for w in self.__namedWidgets:
wid_name = getattr(w, '_name')
db_Selection = self.dbTypeVar.get()
# clear schema entries
if type(w).__name__ == 'checkbox' and widgets[wid_name][db_Selection] == 'disabled':
w.valueVar.set(0)
w.var = False
elif type(w).__name__ == 'Entry' and widgets[wid_name][db_Selection] == 'disabled':
w.delete(0, 'end')
w.insert(0, '')
if clear:
if type(w).__name__ == 'Entry':
w.delete(0, 'end')
w.insert(0, '')
elif type(w).__name__ == 'checkbox':
w.valueVar.set(0)
w.var = False
w.config(state=widgets[wid_name][db_Selection])
return
def checkEntries(self):
errors = []
if self.urlPort and not self.urlPort.isdigit():
errors.append(_("Port number invalid"))
if self.timeout and not self.timeout.isdigit():
errors.append(_("Timeout seconds invalid"))
if hasattr(self,"cbDbType") and self.cbDbType.value not in DBDescriptions:
errors.append(_("DB type is invalid"))
if errors:
tkr.messagebox.showwarning(_("Dialog validation error(s)"),
"\n ".join(errors), parent=self)
return False
return True
def setDialogueEntries(self, dbSettings = None):
if not dbSettings or not len(dbSettings) == 10:
dbSettings = ['', '', '', '', '', '', False, False, '', 'postgres']
urlAddr, urlPort, user, password, database, schema, createSchema, createDB, timeout, dbType = dbSettings
for w in self.__namedWidgets:
if w._name == 'dbTypeCombobox':
w.set(dbType if dbType else DBTypes[0])
self.dbTypeModified()
elif w._name == 'addressEntry':
w.delete(0, 'end')
w.insert(0, urlAddr)
elif w._name == 'portEntry':
w.delete(0, 'end')
w.insert(0, urlPort)
elif w._name == 'userEntry':
w.delete(0, 'end')
w.insert(0, user)
elif w._name == 'passwordEntry':
w.delete(0, 'end')
w.insert(0, password)
elif w._name == 'databaseEntry':
w.delete(0, 'end')
w.insert(0, database)
elif w._name == 'schemaEntry':
w.delete(0, 'end')
w.insert(0, schema)
elif w._name == 'schemaCreate':
w.valueVar.set(1 if createSchema else 0)
elif w._name == 'databaseCreate':
w.valueVar.set(1 if createDB else 0)
elif w._name == 'timeoutEntry':
w.delete(0, 'end')
w.insert(0, timeout)
return
def clearCachedConns(self, currentOnly = True):
# global priorSettingsFile
lstLen = len(self.parent.priorDatabaseSettingsList)
if lstLen:
if currentOnly:
num = self.parent.currentSettingSelectionIndex
if num <= len(self.parent.priorDatabaseSettingsList):
del self.parent.priorDatabaseSettingsList[num]
else:
self.parent.priorDatabaseSettingsList = []
self.parent.cntlr.config['rssDBconnection'] = []
self.parent.cntlr.saveConfig()
self.setDialogueEntries()
return
def browseDbSettings(self, direction):
if not direction: # clears current form
self.setDialogueEntries()
return
if not len(self.parent.priorDatabaseSettingsList): # nothing to do
return
if not direction in (-1, 1) or direction > 0 :
direction = 1
elif direction < 0:
direction = -1
nextIndex = self.parent.currentSettingSelectionIndex + direction
settingLastIndex = len(self.parent.priorDatabaseSettingsList)-1
selectedIndex = nextIndex
if nextIndex > settingLastIndex:
selectedIndex = 0 # return to begining
elif nextIndex < 0:
selectedIndex = settingLastIndex # recycle
# print(selectedIndex)
self.setDialogueEntries(self.parent.priorDatabaseSettingsList[selectedIndex])
self.parent.currentSettingSelectionIndex = selectedIndex
return
def ok(self, event=None):
if hasattr(self, "useOsProxyCb"):
self.useOsProxy = self.useOsProxyCb.value
self.urlAddr = self.urlAddrVar.get()
if self.urlAddr.startswith("http://"): self.urlAddr = self.ulrAddr[7:] # take of protocol part if any
self.urlPort = self.urlPortVar.get()
self.user = self.userVar.get()
self.password = self.passwordVar.get()
self.database = self.databaseVar.get()
self.timeout = self.timeoutVar.get()
self.dbType = self.dbTypeVar.get()
self.schema = self.schemaVar.get()
self.createSchema = self.createSchemaCb.value if self.createSchemaCb else False
self.createDatabase = self.createDatabaseCb.value if self.createDatabaseCb else False
if not self.checkEntries():
return
try:
self.getDbConnection()
except:
pass
if self.accepted:
self.close()
return
def backgroundCreateDB(self, conn, product):
try:
if product == 'sqlite':
_conParams = conn.conParams
_conParams['cntlr'] = self.parent.cntlr
_con = rssDBConnection(**_conParams)
_con.verifyTables(createTables=True, dropPriorTables=False)
_con.close()
del _con
if product == 'postgres':
conn.verifyTables(createTables=True, dropPriorTables=False)
elif product == 'mongodb':
conn.verifyCollections(createCollections=True, dropPriorCollections=False)
self.parent.backgroundGetDbStats(conn)
except Exception as e:
tkr.messagebox.showerror(title='RSS DB Error - createDB', message=traceback.format_exc())
return