-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
6802 lines (6229 loc) · 378 KB
/
Copy pathmain.py
File metadata and controls
6802 lines (6229 loc) · 378 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
#import debugpy
#debugpy.debug_this_thread()
from asyncio.windows_events import NULL
import sys
import platform
from loguru import logger
import os, os.path
from os import path
from queue import Queue
import datetime, time
import requests
import traceback
import sqlite3
from playwright.async_api import async_playwright
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
from PySide2.QtSql import *
from mypackages.mainwindow_ui import Ui_MainWindow
from mypackages.wis_cred_dialog import Ui_WISCredentialDialog
from mypackages.new_season_dialog import Ui_DialogNewSeason
from mypackages.load_season_dialog import Ui_DialogLoadSeason
from mypackages.bold_attributes_dialog import Ui_DialogBoldAttributes
from mypackages.grab_season_data_widget import Ui_WidgetGrabSeasonData
from mypackages.role_ratings_dialog import Ui_DialogRoleRatings
from mypackages.role_ratings_update_db import Ui_DialogRoleRatingUpdateDB_Progress
from mypackages.advanced_config_options import Ui_DialogAdvancedConfigOptions
from mypackages.mark_watchlist_potential_dialog import Ui_DialogMarkWatchlistPotential
from mypackages.update_considering_dialog import Ui_DialogUpdateConsidering
from mypackages.show_columns import Ui_DialogShowColumns
from mypackages.world_lookup import wid_world_list
from mypackages.browser import *
import mypackages.config as myconfig
import configparser
from progress.bar import Bar
import pandas as pd
import numpy as np
from pathlib import Path
# https://stackoverflow.com/questions/61316258/how-to-overwrite-qdialog-accept
def logQueryError(query):
logger.error(f"{datetime.datetime.now()}: query: last error: {query.lastError().text()}")
logger.error(f"{datetime.datetime.now()}: query: last query: {query.lastQuery()}")
logger.error(f"{datetime.datetime.now()}: query: bound values: {query.boundValues()}")
def query_Recruit_IDs(type, dbconn):
openDB(dbconn)
logger.info(f"query_Recruit_IDs: Database name = {dbconn.databaseName()} Connection name = {dbconn.connectionName()} Tables = {dbconn.tables()}")
rids = []
if 'recruits' in dbconn.tables():
logger.debug("Found table 'recruits' in database")
queryRecruitIDs = QSqlQuery(dbconn)
if type == "all":
if not queryRecruitIDs.exec_("SELECT id,pos FROM recruits"):
logQueryError(queryRecruitIDs)
while queryRecruitIDs.next():
r = queryRecruitIDs.value('id')
position = queryRecruitIDs.value('pos')
rids.append([r, position])
elif type == "unsigned":
if not queryRecruitIDs.exec_("SELECT id FROM recruits WHERE signed=0"):
logQueryError(queryRecruitIDs)
while queryRecruitIDs.next():
rids.append(queryRecruitIDs.value('id'))
elif type == "update_role_ratings":
if not queryRecruitIDs.exec_("Select id,pos,ath,spd,dur,we,sta,str,blk,tkl,han,gi,elu,tec FROM recruits"):
logQueryError(queryRecruitIDs)
while queryRecruitIDs.next():
r = queryRecruitIDs.value('id')
pos = queryRecruitIDs.value('pos')
ath = queryRecruitIDs.value('ath')
spd = queryRecruitIDs.value('spd')
dur = queryRecruitIDs.value('dur')
we = queryRecruitIDs.value('we')
sta = queryRecruitIDs.value('sta')
strength = queryRecruitIDs.value('str')
blk = queryRecruitIDs.value('blk')
tkl = queryRecruitIDs.value('tkl')
han = queryRecruitIDs.value('han')
gi = queryRecruitIDs.value('gi')
elu = queryRecruitIDs.value('elu')
tec = queryRecruitIDs.value('tec')
rids.append([r, pos, ath, spd, dur, we, sta, strength, blk, tkl, han, gi, elu, tec])
queryRecruitIDs.finish()
logger.info(f"Closing {dbconn.databaseName()}...")
dbconn.close()
else:
logger.debug("Table 'recruits' does not exist in database")
dbconn.close()
logger.info("End of query_Recruit_IDs function")
return rids
def calculate_role_rating(ratings):
attributes = ['ath', 'spd', 'dur', 'we', 'sta', 'str', 'blk', 'tkl', 'han', 'gi', 'elu', 'tec']
rating_formulas = {
'QB': {
'r1': list(myconfig.role_ratings_df.loc['qbr1'][attributes]),
'r2': list(myconfig.role_ratings_df.loc['qbr2'][attributes]),
'r3': list(myconfig.role_ratings_df.loc['qbr3'][attributes]),
'r4': list(myconfig.role_ratings_df.loc['qbr4'][attributes]),
'r5': list(myconfig.role_ratings_df.loc['qbr5'][attributes]),
'r6': list(myconfig.role_ratings_df.loc['qbr6'][attributes])
},
'RB': {
'r1': list(myconfig.role_ratings_df.loc['rbr1'][attributes]),
'r2': list(myconfig.role_ratings_df.loc['rbr2'][attributes]),
'r3': list(myconfig.role_ratings_df.loc['rbr3'][attributes]),
'r4': list(myconfig.role_ratings_df.loc['rbr4'][attributes]),
'r5': list(myconfig.role_ratings_df.loc['rbr5'][attributes]),
'r6': list(myconfig.role_ratings_df.loc['rbr6'][attributes])
},
'WR': {
'r1': list(myconfig.role_ratings_df.loc['wrr1'][attributes]),
'r2': list(myconfig.role_ratings_df.loc['wrr2'][attributes]),
'r3': list(myconfig.role_ratings_df.loc['wrr3'][attributes]),
'r4': list(myconfig.role_ratings_df.loc['wrr4'][attributes]),
'r5': list(myconfig.role_ratings_df.loc['wrr5'][attributes]),
'r6': list(myconfig.role_ratings_df.loc['wrr6'][attributes])
},
'TE': {
'r1': list(myconfig.role_ratings_df.loc['ter1'][attributes]),
'r2': list(myconfig.role_ratings_df.loc['ter2'][attributes]),
'r3': list(myconfig.role_ratings_df.loc['ter3'][attributes]),
'r4': list(myconfig.role_ratings_df.loc['ter4'][attributes]),
'r5': list(myconfig.role_ratings_df.loc['ter5'][attributes]),
'r6': list(myconfig.role_ratings_df.loc['ter6'][attributes])
},
'OL': {
'r1': list(myconfig.role_ratings_df.loc['olr1'][attributes]),
'r2': list(myconfig.role_ratings_df.loc['olr2'][attributes]),
'r3': list(myconfig.role_ratings_df.loc['olr3'][attributes]),
'r4': list(myconfig.role_ratings_df.loc['olr4'][attributes]),
'r5': list(myconfig.role_ratings_df.loc['olr5'][attributes]),
'r6': list(myconfig.role_ratings_df.loc['olr6'][attributes])
},
'DL': {
'r1': list(myconfig.role_ratings_df.loc['dlr1'][attributes]),
'r2': list(myconfig.role_ratings_df.loc['dlr2'][attributes]),
'r3': list(myconfig.role_ratings_df.loc['dlr3'][attributes]),
'r4': list(myconfig.role_ratings_df.loc['dlr4'][attributes]),
'r5': list(myconfig.role_ratings_df.loc['dlr5'][attributes]),
'r6': list(myconfig.role_ratings_df.loc['dlr6'][attributes])
},
'LB': {
'r1': list(myconfig.role_ratings_df.loc['lbr1'][attributes]),
'r2': list(myconfig.role_ratings_df.loc['lbr2'][attributes]),
'r3': list(myconfig.role_ratings_df.loc['lbr3'][attributes]),
'r4': list(myconfig.role_ratings_df.loc['lbr4'][attributes]),
'r5': list(myconfig.role_ratings_df.loc['lbr5'][attributes]),
'r6': list(myconfig.role_ratings_df.loc['lbr6'][attributes])
},
'DB': {
'r1': list(myconfig.role_ratings_df.loc['dbr1'][attributes]),
'r2': list(myconfig.role_ratings_df.loc['dbr2'][attributes]),
'r3': list(myconfig.role_ratings_df.loc['dbr3'][attributes]),
'r4': list(myconfig.role_ratings_df.loc['dbr4'][attributes]),
'r5': list(myconfig.role_ratings_df.loc['dbr5'][attributes]),
'r6': list(myconfig.role_ratings_df.loc['dbr6'][attributes])
},
'K': {
'r1': list(myconfig.role_ratings_df.loc['kr1'][attributes]),
'r2': list(myconfig.role_ratings_df.loc['kr2'][attributes]),
'r3': list(myconfig.role_ratings_df.loc['kr3'][attributes]),
'r4': list(myconfig.role_ratings_df.loc['kr4'][attributes]),
'r5': list(myconfig.role_ratings_df.loc['kr5'][attributes]),
'r6': list(myconfig.role_ratings_df.loc['kr6'][attributes])
},
'P': {
'r1': list(myconfig.role_ratings_df.loc['pr1'][attributes]),
'r2': list(myconfig.role_ratings_df.loc['pr2'][attributes]),
'r3': list(myconfig.role_ratings_df.loc['pr3'][attributes]),
'r4': list(myconfig.role_ratings_df.loc['pr4'][attributes]),
'r5': list(myconfig.role_ratings_df.loc['pr5'][attributes]),
'r6': list(myconfig.role_ratings_df.loc['pr6'][attributes])
}
}
recruit = [
ratings['ath'],
ratings['spd'],
ratings['dur'],
ratings['we'],
ratings['sta'],
ratings['str'],
ratings['blk'],
ratings['tkl'],
ratings['han'],
ratings['gi'],
ratings['elu'],
ratings['tec']
]
pos = ratings['pos']
recruit_role_ratings = {
'r1': round(np.dot(rating_formulas[pos]['r1'], recruit)/100, 1),
'r2': round(np.dot(rating_formulas[pos]['r2'], recruit)/100, 1),
'r3': round(np.dot(rating_formulas[pos]['r3'], recruit)/100, 1),
'r4': round(np.dot(rating_formulas[pos]['r4'], recruit)/100, 1),
'r5': round(np.dot(rating_formulas[pos]['r5'], recruit)/100, 1),
'r6': round(np.dot(rating_formulas[pos]['r6'], recruit)/100, 1)
}
return recruit_role_ratings
class RoleRatingDBWorker(QObject):
finished = Signal()
progress = Signal(int)
def run(self):
"""Long-running Initialize Recruit task goes here."""
logger.info("Started RoleRatingDBWorker.run function")
# Thread signaling start
self.progress.emit(0)
# Update role ratings for all recruits in DB
if db.databaseName() != "":
# Returned list of lists should contain this data:
# [r, pos, ath, spd, dur, we, sta, strength, blk, tkl, han, gi, elu, tec]
ratings_keys = ['ath', 'spd', 'dur', 'we', 'sta', 'str', 'blk', 'tkl', 'han', 'gi', 'elu', 'tec']
recruits = query_Recruit_IDs("update_role_ratings", db)
openDB(db)
query = QSqlQuery(db)
query.prepare("UPDATE recruits "
"SET r1 = :r1, "
"r2 = :r2, "
"r3 = :r3, "
"r4 = :r4, "
"r5 = :r5, "
"r6 = :r6 "
"WHERE id = :id")
with Bar('Updating recruit role ratings in DB...', max=len(recruits)) as bar:
logger.info(f"Updating recruit role ratings in database...")
for r in recruits:
rid = r[0]
pos = r[1]
rating_values = r[2:]
ratings = dict(zip(ratings_keys, rating_values))
ratings['pos'] = pos
role_ratings = calculate_role_rating(ratings)
query.bindValue(":r1", float(role_ratings['r1']))
query.bindValue(":r2", float(role_ratings['r2']))
query.bindValue(":r3", float(role_ratings['r3']))
query.bindValue(":r4", float(role_ratings['r4']))
query.bindValue(":r5", float(role_ratings['r5']))
query.bindValue(":r6", float(role_ratings['r6']))
query.bindValue(":id", rid)
if not query.exec_():
logQueryError(query)
bar.next()
self.progress.emit(round(bar.index / bar.max * 100))
settings = QSettings()
dbname_short = db.databaseName().split('\\')[-1]
logger.info(f"Storing new role rating hash in registry for season...")
role_ratings_hash = settings.setValue(f"{dbname_short}/role_ratings_hash", myconfig.role_ratings_df_hash)
logger.debug(f"role_ratings_hash = {role_ratings_hash}")
query.finish()
db.close()
self.finished.emit()
class InitializeWorker(QObject):
finished = Signal()
progress = Signal(int, int)
def run(self):
"""Long-running Initialize Recruit task goes here."""
logger.info("Started InitializeWorker.run function")
# Thread signaling start
self.progress.emit(0, 1)
#c = load_config()
#config = c['config']
#requests_session = requests.Session()
db_t.setDatabaseName(db.databaseName())
openDB(db_t)
createRecruitTableQuery = QSqlQuery(db_t)
if not createRecruitTableQuery.exec_(
"""
CREATE TABLE IF NOT EXISTS recruits (
id INTEGER PRIMARY KEY,
name TEXT,
pos TEXT,
height TEXT,
weight INTEGER,
rating INTEGER,
rank INTEGER,
hometown TEXT,
miles INTEGER,
considering TEXT,
ath INTEGER,
spd INTEGER,
dur INTEGER,
we INTEGER,
sta INTEGER,
str INTEGER,
blk INTEGER,
tkl INTEGER,
han INTEGER,
gi INTEGER,
elu INTEGER,
tec INTEGER,
r1 REAL,
r2 REAL,
r3 REAL,
r4 REAL,
r5 REAL,
r6 REAL,
gpa REAL,
pot TEXT,
signed INTEGER,
watched INTEGER,
division TEXT
)
"""
):
logQueryError(createRecruitTableQuery)
createRecruitTableQuery.finish()
logger.info(f"db tables = {db_t.tables()}")
# The above query only creates a new table if it doesn't already exist
# This next step ensures deletion of any prior data in recruits table
createRecruitTableQuery2 = QSqlQuery(db_t)
if db_t.tables() == ['recruits']:
if not createRecruitTableQuery2.exec_("DELETE from recruits"):
logQueryError(createRecruitTableQuery2)
createRecruitTableQuery2.finish()
logger.info(f"db tables = {db_t.tables()}")
db_t.close()
#Thread progress signaling DB was created
self.progress.emit(1, 1)
result = wis_browser("scrape_recruit_IDs", db_t, self.progress)
if result:
# After grabbing all Recruit IDs and storing in DB.
# This thread is finished and now need to signal
# creation of new threads for grabbing static attributes of recruits.
self.finished.emit()
else:
# Implies there was an error authenticating to WIS
self.progress.emit(999999,1)
self.finished.emit()
class UpdateWorker(QObject):
finished = Signal()
progress = Signal(int, int)
def run(self):
"""Long-running Update Recruit task goes here."""
logger.info("Started UpdateWorker.run function")
# Thread signaling start
self.progress.emit(0, 1)
self.progress.emit(1, 1)
db_t.setDatabaseName(db.databaseName())
logger.debug(f"db_t is open? = {db_t.isOpen()}")
result = wis_browser("update_considering", db_t, self.progress)
if result:
# After grabbing all Recruit IDs and storing in DB.
# This thread is finished and now need to signal
# creation of new threads for grabbing static attributes of recruits.
self.finished.emit()
else:
# Implies there was an error authenticating to WIS
self.progress.emit(999999,1)
self.finished.emit()
#https://www.learnpyqt.com/courses/concurrent-execution/multithreading-pyqt-applications-qthreadpool/
class Worker(QRunnable):
"""Worker thread for running background tasks."""
def __init__(self, fn, *args, **kwargs):
super(Worker, self).__init__()
# Store constructor arguments (re-used for processing)
self.fn = fn
self.args = args
self.kwargs = kwargs
self.signals = WorkerSignals()
self.kwargs['progress_callback'] = self.signals.progress
@Slot()
def run(self):
try:
logger.debug("Worker QRunnable 'try' section")
result = self.fn(
*self.args, **self.kwargs,
)
except:
logger.debug("Worker QRunnable 'except' section")
traceback.print_exc()
exctype, value = sys.exc_info()[:2]
self.signals.error.emit((exctype, value, traceback.format_exc()))
else:
logger.debug("Worker QRunnable 'else' section")
self.signals.result.emit(result)
finally:
logger.debug("Worker QRunnable 'finally' section")
self.signals.finished.emit()
class WorkerSignals(QObject):
"""
Defines the signals available from a running worker thread.
Supported signals are:
finished
No data
error
`tuple` (exctype, value, traceback.format_exc() )
result
`object` data returned from processing, anything
"""
finished = Signal()
error = Signal(tuple)
result =Signal(object)
progress = Signal(int)
# This class is no longer needed as-is when using the new Advanced Search page to gather recruits
class QueueMonitorWorker(QObject):
finished = Signal()
progress = Signal(int)
def __init__(self, q, rc, rl, t):
super(QueueMonitorWorker, self).__init__()
self.q = q # Queue object
self.rc = rc # recruit ID list, either an initialize list or update list
self.rl = rl # recruit list length
self.t = t # type = 'initialize' or 'update'
def run(self):
logger.info("Started QueueMonitorWorker.run function")
# Loop to monitor queue size
while self.q.qsize() > 0:
logger.debug(f"Queue size = {self.q.qsize()}")
self.progress.emit(self.q.qsize())
time.sleep(1)
# Once queue is empty, update each recruit in the DB
self.progress.emit(self.q.qsize())
logger.debug(f"Queue is empty -> Queue size = {self.q.qsize()}")
db_t.setDatabaseName(db.databaseName())
openDB(db_t)
query = QSqlQuery(db_t)
if self.t == "initialize":
logger.info(f"Initializing recruit attributes in database...")
query.prepare("UPDATE recruits "
"SET ath = :ath, "
"spd = :spd, "
"dur = :dur, "
"we = :we, "
"sta = :sta, "
"str = :str, "
"blk = :blk, "
"tkl = :tkl, "
"han = :han, "
"gi = :gi, "
"elu = :elu, "
"tec = :tec, "
"r1 = :r1, "
"r2 = :r2, "
"r3 = :r3, "
"r4 = :r4, "
"r5 = :r5, "
"r6 = :r6, "
"gpa = :gpa "
"WHERE id = :id")
# Signal that we are now updating DB
self.progress.emit(11111111)
counter = 1000000
with Bar('Initializing Recruit Static Data...', max=self.rl) as bar:
for r in self.rc:
query.bindValue(":ath", r['ath'])
query.bindValue(":spd", r['spd'])
query.bindValue(":dur", r['dur'])
query.bindValue(":we", r['we'])
query.bindValue(":sta", r['sta'])
query.bindValue(":str", r['strength'])
query.bindValue(":blk", r['blk'])
query.bindValue(":tkl", r['tkl'])
query.bindValue(":han", r['han'])
query.bindValue(":gi", r['gi'])
query.bindValue(":elu", r['elu'])
query.bindValue(":tec", r['tec'])
query.bindValue(":r1", float(r['role_rating']['r1']))
query.bindValue(":r2", float(r['role_rating']['r2']))
query.bindValue(":r3", float(r['role_rating']['r3']))
query.bindValue(":r4", float(r['role_rating']['r4']))
query.bindValue(":r5", float(r['role_rating']['r5']))
query.bindValue(":r6", float(r['role_rating']['r6']))
query.bindValue(":gpa", r['gpa'])
query.bindValue(":id", r['rid'])
if not query.exec_():
logQueryError(query)
counter += 1
self.progress.emit(counter)
bar.next()
elif self.t == "update":
logger.info(f"Updating recruit considering in database...")
query.prepare("UPDATE recruits "
"SET considering = :considering, "
"signed = :signed "
"WHERE id = :id")
with Bar('Update Recruits Considering...', max=self.rl) as bar:
emit_progress = 1000000
self.progress.emit(emit_progress)
for each in self.rc:
rid = each[0]
signed = each[1]
considering = each[2]
query.bindValue(":considering", considering[:-1]) # remove newline at end
query.bindValue(":signed", signed)
query.bindValue(":id", rid)
if not query.exec_():
logQueryError(query)
bar.next()
emit_progress += 1
self.progress.emit(emit_progress)
query.finish()
db_t.close()
self.finished.emit()
class BrowserAuthWorker(QObject):
finished = Signal()
progress = Signal(int)
def run(self):
"""Long-running Initialize Recruit task goes here."""
# Thread signaling start
logger.debug("progress.emit(0)")
self.progress.emit(0)
page = wis_browser("auth_to_store_cookies", db_t, self.progress)
if not page:
logger.debug("progress.emit(999999)")
self.progress.emit(999999)
logger.debug("finished.emit()")
self.finished.emit()
# This class is no longer needed as-is when using the new Advanced Search page to gather recruits
class MarkRecruitsWorker(QObject):
finished = Signal()
progress = Signal(int)
def run(self):
potential_lookup = {
'?': '?',
'VL': "0-VL",
'L': "1-L",
'A': "2-A",
'H': "3-H",
'VH': "4-VH"
}
"""Long-running Initialize Recruit task goes here."""
# Thread signaling start
self.progress.emit(0)
# Launch playwright browser to grab watched recruits
#c = load_config()
#config = c['config']
db_m.setDatabaseName(db.databaseName())
page = wis_browser("grab_watched_recruits", db_m, self.progress)
if page == "":
# Implies issues loading Recruit Summary page.
self.progress.emit(2000)
elif page == False:
# Implies issue with WIS Authentication
self.progress.emit(999999)
else:
self.progress.emit(3)
# Check if total watched recruits list is empty
total_unsigned_recruits_span = page.find(id="ctl00_ctl00_ctl00_Main_Main_Main_TotalRecruitCountLbl")
#print(total_unsigned_recruits_span)
if total_unsigned_recruits_span != None:
total_unsigned_watched = int(total_unsigned_recruits_span.next_sibling)
else:
total_unsigned_watched = 0
unsigned_table = page.find(id="recruits")
watchlist = {}
myconfig.watchlist_length = len(watchlist)
if total_unsigned_watched == 0 or "Not watching any recruits." in unsigned_table.text:
logger.info("There are no unsigned recruits in the watchlist.")
else:
# https://stackoverflow.com/questions/14257717/python-beautifulsoup-wildcard-attribute-id-search
unsigned_recruit_rows = unsigned_table.find_all("tr",
{"id": lambda L: L and L.startswith("ctl00_ctl00_ctl00_Main_Main_Main_rptPriorities_ct")}
)
for row in unsigned_recruit_rows:
columns = row.find_all("td")
recruit_a_tag = columns[4].find("a")
link = recruit_a_tag.attrs['href']
link_re = re.search(r"(\d{8})", link)
rid = int(link_re.group(1))
potential = potential_lookup[columns[9].text]
watchlist.update({rid: potential})
signed_table = page.find(id="signed")
if signed_table.text == "\n\n\n":
logger.info("There are no signed recruits in the watchlist.")
else:
signed_recruit_tbody = signed_table.find_all("tbody")
# The first tbody is the header row for signed recruits table.
# The second tbody is the table with signed recruits.
signed_recruit_rows = signed_recruit_tbody[1].find_all("tr")
for row in signed_recruit_rows:
columns = row.find_all("td")
recruit_a_tag = columns[4].find("a")
link = recruit_a_tag.attrs['href']
link_re = re.search(r"(\d{8})", link)
rid = int(link_re.group(1))
potential = potential_lookup[columns[9].text]
watchlist.update({rid: potential})
myconfig.watchlist_length = len(watchlist)
logger.info(f"Length of watchlist = {myconfig.watchlist_length}")
# First we clear all watched recruits from the db
if db.isOpen():
logger.debug("closing 'db' connection...")
db.close()
if db_t.isOpen():
logger.debug("closing 'db_t' connection...")
db_t.close()
openDB(db_m)
queryUpdate = QSqlQuery(db_m)
if not queryUpdate.exec_(
"""
UPDATE recruits SET watched = 0
"""
):
logQueryError(queryUpdate)
queryUpdate.finish()
# Now we set watched = 1 for the rids in watchlist
query_watched_update = QSqlQuery(db_m)
query_watched_update.prepare("UPDATE recruits "
"SET watched = 1, "
"pot = :pot "
"WHERE id = :id")
for k, v in watchlist.items():
query_watched_update.bindValue(":id", k)
query_watched_update.bindValue(":pot", v)
if not query_watched_update.exec_():
logQueryError(query_watched_update)
query_watched_update.finish()
db_m.close()
# Report done
self.progress.emit(1000)
mw.statusbar.showMessage(f"{len(watchlist)} recruits marked from watchlist.")
self.finished.emit()
class GrabSeasonData(QDialog, Ui_WidgetGrabSeasonData):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.settings = QSettings()
geometry = self.settings.value('GrabSeasonDataGeometry', bytes('', 'utf-8'))
self.restoreGeometry(geometry)
# Queue to process recruit IDs
self.rid_queue = Queue()
self.threadpool = QThreadPool()
self.threadCount = QThreadPool.globalInstance().maxThreadCount()
self.requests_session = requests.Session()
self.recruit_initialize_list = []
self.rids_all = query_Recruit_IDs("all", db)
myconfig.rids_all_length = len(self.rids_all)
if myconfig.rids_all_length == 0:
self.pushButtonInitializeRecruits.setText(QCoreApplication.translate("MainWindow", u"&Initialize Recruits", None))
else:
self.labelRecruitsInitialized.setText(f"Recruits Initialized = {myconfig.rids_all_length}")
self.labelRecruitsInitialized.setStyleSheet(u"color: rgb(0, 128, 0);")
self.pushButtonInitializeRecruits.setText(QCoreApplication.translate("MainWindow", u"&Re-Initialize Recruits", None))
self.checkBoxGrabHigherRecruits.setChecked(myconfig.higher_division_recruits)
# Hide all progress check marks and text until button is pressed
self.labelCheckMarkAuthWIS_Error.setVisible(False)
self.labelCheckMarkCreateDB.setVisible(False)
self.labelCheckMarkAuthWIS.setVisible(False)
self.labelCheckMarkDivisionSearch1.setVisible(False)
self.labelCheckMarkDivisionSearch2.setVisible(False)
self.labelCheckMarkRecruitDataInitialized.setVisible(False)
self.labelProgressCreateRecruitDB.setVisible(False)
self.labelAuthWIS.setVisible(False)
self.labelDivisionSearch1.setVisible(False)
self.labelDivisionSearch2.setVisible(False)
self.labelRecruitDataInitialized.setVisible(False)
self.progressBarInitializeRecruits.setVisible(False)
self.progressBarInitializeRecruits.setValue(0)
self.pushButtonInitializeRecruits.clicked.connect(self.runInitializeJob)
self.checkBoxGrabHigherRecruits.stateChanged.connect(self.save_higher_recruit_config)
self.buttonBox.button(QDialogButtonBox.Close).clicked.connect(self.accept)
def accept(self):
geometry = self.saveGeometry()
self.settings.setValue('GrabSeasonDataGeometry', geometry)
super().close()
def save_higher_recruit_config(self):
data = {0: False, 2: True}
myconfig.higher_division_recruits = data[self.checkBoxGrabHigherRecruits.checkState()]
logger.debug(f"myconfig.higher_division_recruits = {myconfig.higher_division_recruits}")
def runInitializeJob(self):
logger.info("Button Pressed: Initialize Recruits")
# Step 1: Create a QThread object
self.thread = QThread()
# Step 2: Create a worker object
self.worker = InitializeWorker()
# Step 3: Move worker to the thread
self.worker.moveToThread(self.thread)
# Step 4: Connect signals and slots
self.thread.started.connect(self.worker.run)
self.worker.finished.connect(self.thread.quit)
self.worker.finished.connect(self.worker.deleteLater)
self.thread.finished.connect(self.thread.deleteLater)
self.worker.progress.connect(self.reportInitializeProgress)
# Step 6: Start the thread
self.thread.start()
# Final resets
self.buttonBox.button(QDialogButtonBox.Close).setEnabled(False)
self.labelRecruitsInitialized.setStyleSheet(u"color: rgb(255, 0, 0);")
self.labelRecruitsInitialized.setText(f"Recruits Initialized = 0")
self.pushButtonInitializeRecruits.setEnabled(False)
self.labelCheckMarkCreateDB.setVisible(False)
self.labelCheckMarkAuthWIS.setVisible(False)
self.labelCheckMarkAuthWIS_Error.setVisible(False)
self.labelCheckMarkDivisionSearch1.setVisible(False)
self.labelCheckMarkDivisionSearch2.setVisible(False)
self.labelCheckMarkRecruitDataInitialized.setVisible(False)
self.checkBoxGrabHigherRecruits.setEnabled(False)
self.thread.finished.connect(self.initialize_finished)
def reportInitializeProgress(self, n, m):
divisions = {1: 'D-IA', 2: 'D-IAA', 3: 'D-II', 4: 'D-III'}
if n == 0:
self.labelProgressCreateRecruitDB.setVisible(True)
self.labelAuthWIS.setVisible(True)
if n == 1:
# DB created
self.labelCheckMarkCreateDB.setVisible(True)
if n == 2:
# WIS Auth Completed
self.labelCheckMarkAuthWIS.setVisible(True)
if m == 1:
self.labelDivisionSearch1.setText("Grab Recruits from D-IA")
self.labelDivisionSearch1.setVisible(True)
self.labelCheckMarkDivisionSearch1.setVisible(True)
if m == 2:
self.labelDivisionSearch1.setText("Grab Recruits from D-IA")
self.labelDivisionSearch1.setVisible(True)
self.labelDivisionSearch2.setText("Grab Recruits from D-IAA")
self.labelDivisionSearch2.setVisible(True)
self.labelCheckMarkDivisionSearch1.setVisible(True)
self.labelCheckMarkDivisionSearch2.setVisible(True)
if m == 3:
self.labelDivisionSearch1.setText("Grab Recruits from D-IAA")
self.labelDivisionSearch1.setVisible(True)
self.labelCheckMarkDivisionSearch1.setVisible(True)
if m == 4:
self.labelDivisionSearch1.setText("Grab Recruits from D-IAA")
self.labelDivisionSearch1.setVisible(True)
self.labelDivisionSearch2.setText("Grab Recruits from D-IA")
self.labelDivisionSearch2.setVisible(True)
self.labelCheckMarkDivisionSearch1.setVisible(True)
self.labelCheckMarkDivisionSearch2.setVisible(True)
if m == 5:
self.labelDivisionSearch1.setText("Grab Recruits from D-II")
self.labelDivisionSearch1.setVisible(True)
self.labelCheckMarkDivisionSearch1.setVisible(True)
if m == 6:
self.labelDivisionSearch1.setText("Grab Recruits from D-II")
self.labelDivisionSearch1.setVisible(True)
self.labelDivisionSearch2.setText("Grab Recruits from D-IAA")
self.labelDivisionSearch2.setVisible(True)
self.labelCheckMarkDivisionSearch1.setVisible(True)
self.labelCheckMarkDivisionSearch2.setVisible(True)
if m == 7:
self.labelDivisionSearch1.setText("Grab Recruits from D-III")
self.labelDivisionSearch1.setVisible(True)
self.labelCheckMarkDivisionSearch1.setVisible(True)
if m == 8:
self.labelDivisionSearch1.setText("Grab Recruits from D-III")
self.labelDivisionSearch1.setVisible(True)
self.labelDivisionSearch2.setText("Grab Recruits from D-II")
self.labelDivisionSearch2.setVisible(True)
self.labelCheckMarkDivisionSearch1.setVisible(True)
self.labelCheckMarkDivisionSearch2.setVisible(True)
self.labelRecruitDataInitialized.setText("Saving Recruit Data...")
self.labelRecruitDataInitialized.setVisible(True)
self.labelCheckMarkRecruitDataInitialized.setVisible(False)
self.progressBarInitializeRecruits.setRange(0, 100)
self.progressBarInitializeRecruits.setValue(0)
self.progressBarInitializeRecruits.setVisible(True)
if n == 1000:
# Starting to grab recruit static data
self.labelRecruitsInitialized.setText(f"Analyzing {m} Recruits...")
self.progressBarInitializeRecruits.setRange(0, m)
self.progressBarInitializeRecruits.setValue(0)
self.progressBarInitializeRecruits.value()
if n > 1000:
#percent_done = (n - 1000) / m * 100
#print(percent_done)
self.progressBarInitializeRecruits.setValue(n - 1000)
if n > 1000 and (n - 1000) == m:
self.labelRecruitDataInitialized.setText("Recruit Data Saved")
self.labelCheckMarkRecruitDataInitialized.setVisible(True)
self.labelRecruitsInitialized.setText(f"Recruits Initialized = {m}")
self.checkBoxGrabHigherRecruits.setEnabled(True)
if n == 999999:
self.labelCheckMarkAuthWIS_Error.setVisible(True)
mw.statusbar.showMessage("ERROR: There was a problem authenticating to WIS.")
self.progressBarInitializeRecruits.setVisible(False)
def initialize_finished(self):
logger.debug("Running initialized_finished function")
self.labelRecruitsInitialized.setStyleSheet(u"color: rgb(0, 0, 255);")
self.labelRecruitsInitialized.setText(f"Initialized {myconfig.rids_all_length} Recruits...")
self.buttonBox.button(QDialogButtonBox.Close).setEnabled(True)
def closeEvent(self, event):
# Now we define the closeEvent
# This is called whenever a window is closed.
# It is passed an event which we can choose to accept or reject, but in this case we'll just pass it on after we're done.
# First we need to get the current size and position of the window.
# This can be fetchesd using the built in saveGeometry() method.
# This is got back as a byte array. It won't really make sense to a human directly, but it makes sense to Qt.
geometry = self.saveGeometry()
# Once we know the geometry we can save it in our settings under geometry
self.settings.setValue('GrabSeasonDataGeometry', geometry)
# Finally we pass the event to the class we inherit from. It can choose to accept or reject the event, but we don't need to deal with it ourselves
super(GrabSeasonData, self).closeEvent(event)
class UpdateConsidering(QDialog, Ui_DialogUpdateConsidering):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.settings = QSettings()
geometry = self.settings.value('UpdateConsideringGeometry', bytes('', 'utf-8'))
self.restoreGeometry(geometry)
self.buttonBox.button(QDialogButtonBox.Close).setEnabled(False)
self.labelCheckmarkUpdateConsidering.setVisible(False)
self.run_update_considering()
self.buttonBox.button(QDialogButtonBox.Close).clicked.connect(self.accept)
def accept(self):
geometry = self.saveGeometry()
self.settings.setValue('UpdateConsideringGeometry', geometry)
super().accept()
def closeEvent(self, event):
# Now we define the closeEvent
# This is called whenever a window is closed.
# It is passed an event which we can choose to accept or reject, but in this case we'll just pass it on after we're done.
# First we need to get the current size and position of the window.
# This can be fetchesd using the built in saveGeometry() method.
# This is got back as a byte array. It won't really make sense to a human directly, but it makes sense to Qt.
geometry = self.saveGeometry()
# Once we know the geometry we can save it in our settings under geometry
self.settings.setValue('UpdateConsideringGeometry', geometry)
# Finally we pass the event to the class we inherit from. It can choose to accept or reject the event, but we don't need to deal with it ourselves
super(UpdateConsidering, self).closeEvent(event)
def run_update_considering(self):
self.progressBarUpdateConsidering.setVisible(True)
if db.isOpen():
db.close()
db_t.setDatabaseName(db.databaseName())
myconfig.rids_unsigned = query_Recruit_IDs("unsigned", db_t)
myconfig.rids_unsigned_length = len(myconfig.rids_unsigned)
self.progressBarUpdateConsidering.setRange(0, myconfig.rids_unsigned_length)
logger.info("Button Pressed: Update Recruits")
# Step 1: Create a QThread object
self.thread = QThread()
# Step 2: Create a worker object
self.worker = UpdateWorker()
# Step 3: Move worker to the thread
self.worker.moveToThread(self.thread)
# Step 4: Connect signals and slots
self.thread.started.connect(self.worker.run)
self.worker.finished.connect(self.thread.quit)
self.worker.finished.connect(self.worker.deleteLater)
self.thread.finished.connect(self.thread.deleteLater)
self.worker.progress.connect(self.queue_monitor_update_progress)
# Step 6: Start the thread
self.thread.start()
# Final resets
self.labelUpdateStatusText.setText(f"Grabbing updates for {myconfig.rids_unsigned_length} recruits...")
self.labelUpdateStatusText.setVisible(True)
self.thread.finished.connect(self.update_finished)
def update_finished(self):
logger.debug("Running update_finished function")
self.buttonBox.button(QDialogButtonBox.Close).setEnabled(True)
self.labelUpdateStatusText.setText("Update Considering action completed.")
self.labelCheckmarkUpdateConsidering.setVisible(True)
def queue_monitor_update_progress(self, n, m):
if n == 1000:
self.progressBarUpdateConsidering.setRange(0, m)
if n > 1000:
self.progressBarUpdateConsidering.setValue(n - 1000)
if (n - 1000) == m:
self.labelUpdateStatusText.setText(f"Saved {m} updates to database.")
self.labelCheckmarkUpdateConsidering.setVisible(True)
class MarkWatchlistPotential(QDialog, Ui_DialogMarkWatchlistPotential):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.settings = QSettings()
geometry = self.settings.value('MarkWatchlistPotentialGeometry', bytes('', 'utf-8'))
self.restoreGeometry(geometry)
self.buttonBox.button(QDialogButtonBox.Close).setEnabled(False)
self.runMarkRecruitsJob()
self.buttonBox.button(QDialogButtonBox.Close).clicked.connect(self.accept)
def accept(self):
geometry = self.saveGeometry()
self.settings.setValue('MarkWatchlistPotentialGeometry', geometry)
super().accept()
def closeEvent(self, event):
# Now we define the closeEvent
# This is called whenever a window is closed.
# It is passed an event which we can choose to accept or reject, but in this case we'll just pass it on after we're done.
# First we need to get the current size and position of the window.
# This can be fetchesd using the built in saveGeometry() method.
# This is got back as a byte array. It won't really make sense to a human directly, but it makes sense to Qt.
geometry = self.saveGeometry()
# Once we know the geometry we can save it in our settings under geometry
self.settings.setValue('MarkWatchlistPotentialGeometry', geometry)
# Finally we pass the event to the class we inherit from. It can choose to accept or reject the event, but we don't need to deal with it ourselves
super(MarkWatchlistPotential, self).closeEvent(event)
def runMarkRecruitsJob(self):
logger.info("Button Pressed: Mark Recruits From Watchlist")
# Step 1: Create a QThread object
self.thread = QThread()
# Step 2: Create a worker object
self.worker = MarkRecruitsWorker()
# Step 3: Move worker to the thread
self.worker.moveToThread(self.thread)
# Step 4: Connect signals and slots
self.thread.started.connect(self.worker.run)