-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathConfiguration.py
1760 lines (1465 loc) · 75.1 KB
/
Configuration.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 python
# -*- coding: utf-8 -*-
"""Configuration.py
Handles fpdb/fpdb-hud configuration files.
"""
# Copyright 2008-2012, Ray E. Barker
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
########################################################################
#TODO fix / rethink edit stats - it is broken badly just now
# Standard Library modules
from __future__ import with_statement
import L10n
_ = L10n.get_translation()
import codecs
import os
import sys
import inspect
import string
import shutil
import locale
import re
import xml.dom.minidom
from xml.dom.minidom import Node
import platform
if platform.system() == 'Windows':
import winpaths
winpaths_appdata = winpaths.get_appdata()
else:
winpaths_appdata = False
import logging, logging.config
import ConfigParser
# config version is used to flag a warning at runtime if the users config is
# out of date.
# The CONFIG_VERSION should be incremented __ONLY__ if the add_missing_elements()
# method cannot update existing standard configurations
CONFIG_VERSION = 83
#
# Setup constants
# code is centralised here to ensure uniform handling of path names
# especially important when user directory includes non-ascii chars
#
# INSTALL_METHOD ("source" or "exe")
# FPDB_ROOT_PATH (path to the root fpdb installation dir root (normally ...../fpdb)
# APPDATA_PATH (root path for appdata eg /~ or appdata)
# CONFIG_PATH (path to the directory holding logs, sqlite db's and config)
# GRAPHICS_PATH (path to graphics assets (normally .gfx)
# OS_FAMILY (OS Family for installed system (Linux, Mac, XP, Win7)
# POSIX (True=Linux or Mac platform, False=Windows platform)
# PYTHON_VERSION (n.n)
if hasattr(sys, "frozen"):
if platform.system() == 'Windows':
INSTALL_METHOD = "exe"
elif platform.system() == 'Darwin':
INSTALL_METHOD = "app"
else:
INSTALL_METHOD = "source"
if INSTALL_METHOD == "exe" or INSTALL_METHOD == "app":
FPDB_ROOT_PATH = os.path.dirname(unicode(sys.executable, sys.getfilesystemencoding())) # should be exe path to \fpdbroot
elif sys.path[0] == "": # we are probably running directly (>>>import Configuration)
FPDB_ROOT_PATH = os.getcwdu() # should be source path to /fpdbroot
else: # all other cases
FPDB_ROOT_PATH = os.getcwdu() # should be source path to /fpdbroot
sysPlatform = platform.system() #Linux, Windows, Darwin
if sysPlatform[0:5] == 'Linux':
OS_FAMILY = 'Linux'
elif sysPlatform == 'Darwin':
OS_FAMILY = 'Mac'
elif sysPlatform == 'Windows':
if platform.release() <> 'XP':
OS_FAMILY = 'Win7' #Vista and win7
else:
OS_FAMILY = 'XP'
else:
OS_FAMILY = False
GRAPHICS_PATH = os.path.join(FPDB_ROOT_PATH, u"gfx")
if OS_FAMILY in ['XP', 'Win7']:
APPDATA_PATH = winpaths_appdata
CONFIG_PATH = os.path.join(APPDATA_PATH, u"fpdb")
elif OS_FAMILY == 'Mac':
APPDATA_PATH = os.getenv("HOME")
CONFIG_PATH = os.path.join(APPDATA_PATH, u".fpdb")
elif OS_FAMILY == 'Linux':
APPDATA_PATH = os.path.expanduser(u"~")
CONFIG_PATH = os.path.join(APPDATA_PATH, u".fpdb")
else:
APPDATA_PATH = False
CONFIG_PATH = False
if os.name == 'posix':
POSIX = True
else:
POSIX = False
PYTHON_VERSION = sys.version[:3]
# logging has been set up in fpdb.py or HUD_main.py, use their settings:
log = logging.getLogger("config")
LOGLEVEL = {'DEBUG' : logging.DEBUG,
'INFO' : logging.INFO,
'WARNING' : logging.WARNING,
'ERROR' : logging.ERROR,
'CRITICAL': logging.CRITICAL}
def get_config(file_name, fallback = True):
"""Looks in cwd and in self.default_config_path for a config file."""
#FIXME
# This function has become difficult to understand, plus it no-longer
# just looks for a config file, it actually does file copying
# look for example file even if not used here, path is returned to caller
config_found,example_found,example_copy = False,False,False
config_path, example_path = None,None
config_path = os.path.join(FPDB_ROOT_PATH, file_name)
#print "config_path=", config_path
if os.path.exists(config_path): # there is a file in the cwd
config_found = True # so we use it
else: # no file in the cwd, look where it should be in the first place
config_path = os.path.join(CONFIG_PATH, file_name)
#print "config path 2=", config_path
if os.path.exists(config_path):
config_found = True
#TODO: clean up the example path loading to ensure it behaves the same on all OSs
# Example configuration for debian package
if POSIX:
# If we're on linux, try to copy example from the place
# debian package puts it; get_default_config_path() creates
# the config directory for us so there's no need to check it
# again
example_path = '/usr/share/python-fpdb/' + file_name + '.example'
if not os.path.exists(example_path):
if os.path.exists(file_name + '.example'):
example_path = file_name + '.example'
else:
example_path = os.path.join(FPDB_ROOT_PATH, file_name + '.example')
if not config_found and fallback:
try:
shutil.copyfile(example_path, config_path)
example_copy = True
msg = _("Config file has been created at %s.") % (config_path)
log.info(msg)
except IOError:
try:
example_path = file_name + '.example'
shutil.copyfile(example_path, config_path)
example_copy = True
msg = _("Config file has been created at %s.") % (config_path)
log.info(msg)
except IOError:
pass
# OK, fall back to the .example file, should be in the start dir
elif os.path.exists(os.path.join(FPDB_ROOT_PATH, file_name + '.example')):
try:
#print ""
example_path = os.path.join(FPDB_ROOT_PATH, file_name + '.example')
if not config_found and fallback:
shutil.copyfile(example_path, config_path)
example_copy = True
log.info (_("No %r found in \"%r\" or \"%r\".") % (file_name, FPDB_ROOT_PATH, CONFIG_PATH) \
+ " " + _("Config file has been created at %r.") % (config_path+"\n") )
except:
print(_("Error copying .example config file, cannot fall back. Exiting."), "\n")
sys.stderr.write(_("Error copying .example config file, cannot fall back. Exiting.")+"\n")
sys.stderr.write( str(sys.exc_info()) )
sys.exit()
elif fallback:
sys.stderr.write((_("No %s found, cannot fall back. Exiting.") % file_name) + "\n")
sys.exit()
#print "get_config: returning "+str( (config_path,example_copy,example_path) )
return (config_path,example_copy,example_path)
def set_logfile(file_name):
(conf_file,copied,example_file) = get_config(u"logging.conf", fallback = False)
log_dir = os.path.join(CONFIG_PATH, u'log')
check_dir(log_dir)
log_file = os.path.join(log_dir, file_name)
if conf_file:
try:
log_file = log_file.replace('\\', '\\\\') # replace each \ with \\
logging.config.fileConfig(conf_file, {"logFile":log_file})
except:
sys.stderr.write(_("Could not setup log file %s") % file_name)
def check_dir(path, create = True):
"""Check if a dir exists, optionally creates if not."""
if os.path.exists(path):
if os.path.isdir(path):
return path
else:
return False
if create:
msg = _("Creating directory: '%s'") % (path)
print(msg)
log.info(msg)
os.mkdir(path)#, "utf-8"))
else:
return False
def normalizePath(path):
"Normalized existing pathes"
if os.path.exists(path):
return os.path.abspath(path)
return path
########################################################################
# application wide consts
APPLICATION_NAME_SHORT = 'fpdb'
APPLICATION_VERSION = 'xx.xx.xx'
DATABASE_TYPE_POSTGRESQL = 'postgresql'
DATABASE_TYPE_SQLITE = 'sqlite'
DATABASE_TYPE_MYSQL = 'mysql'
DATABASE_TYPES = (
DATABASE_TYPE_POSTGRESQL,
DATABASE_TYPE_SQLITE,
DATABASE_TYPE_MYSQL,
)
LOCALE_ENCODING = locale.getpreferredencoding()
if LOCALE_ENCODING in ("US-ASCII", "", None):
LOCALE_ENCODING = "cp1252"
if (os.uname()[0]!="Darwin"):
print(_("Default encoding set to US-ASCII, defaulting to CP1252 instead."), _("Please report this problem."))
# needs LOCALE_ENCODING (above), imported for sqlite setup in Config class below
import Charset
########################################################################
def string_to_bool(string, default=True):
"""converts a string representation of a boolean value to boolean True or False
@param string: (str) the string to convert
@param default: value to return if the string can not be converted to a boolean value
"""
string = string.lower()
if string in ('1', 'true', 't'):
return True
elif string in ('0', 'false', 'f'):
return False
return default
class Layout:
def __init__(self, node):
self.max = int( node.getAttribute('max') )
self.width = int( node.getAttribute('width') )
self.height = int( node.getAttribute('height') )
self.location = []
self.hh_seats = []
self.location = map(lambda x: None, range(self.max+1)) # fill array with max seats+1 empty entries
# hh_seats is used to map the seat numbers specified in hand history files (and stored in db) onto
# the contiguous integerss, 1 to self.max, used to index hud stat_windows (and aw seat_windows) for display
# For most sites these numbers are the same, but some sites (e.g. iPoker) omit seat numbers in hand histories
# for tables smaller than 10-max.
self.hh_seats= map(lambda x: None, range(self.max+1)) # fill array with max seats+1 empty entries
for location_node in node.getElementsByTagName('location'):
hud_seat = location_node.getAttribute('seat')
if hud_seat != "":
# if hist_seat for this seat number is specified in the layout, then store it in the hh_seats list
hist_seat = location_node.getAttribute('hist_seat') #XXX
if hist_seat:
self.hh_seats[int( hud_seat )] = int( hist_seat )
else:
# .. otherwise just store the original seat number in the hh_seats list
self.hh_seats[int( hud_seat )] = int( hud_seat )
self.location[int( hud_seat )] = (int( location_node.getAttribute('x') ), int( location_node.getAttribute('y')))
elif location_node.getAttribute('common') != "":
self.common = (int( location_node.getAttribute('x') ), int( location_node.getAttribute('y')))
def __str__(self):
if hasattr(self, 'name'):
name = str(self.name)
temp = " Layout = %d max, width= %d, height = %d" % (self.max, self.width, self.height)
if hasattr(self, 'fav_seat'): temp = temp + ", fav_seat = %d\n" % self.fav_seat
else: temp = temp + "\n"
if hasattr(self, "common"):
temp = temp + " Common = (%d, %d)\n" % (self.common[0], self.common[1])
temp = temp + " Locations = "
for i in range(1, len(self.location)):
temp = temp + "%s:(%d,%d) " % (self.hh_seats[i],self.location[i][0],self.location[i][1])
return temp + "\n"
class Email:
def __init__(self, node):
self.node = node
self.host= node.getAttribute("host")
self.username = node.getAttribute("username")
self.password = node.getAttribute("password")
self.useSsl = node.getAttribute("useSsl")
self.folder = node.getAttribute("folder")
self.fetchType = node.getAttribute("fetchType")
def __str__(self):
return " email\n fetchType = %s host = %s\n username = %s password = %s\n useSsl = %s folder = %s" \
% (self.fetchType, self.host, self.username, self.password, self.useSsl, self.folder)
class Site:
def __init__(self, node):
self.site_name = node.getAttribute("site_name")
self.screen_name = node.getAttribute("screen_name")
self.site_path = normalizePath(node.getAttribute("site_path"))
self.HH_path = normalizePath(node.getAttribute("HH_path"))
self.TS_path = normalizePath(node.getAttribute("TS_path"))
self.enabled = string_to_bool(node.getAttribute("enabled"), default=True)
self.aux_enabled = string_to_bool(node.getAttribute("aux_enabled"), default=True)
self.hud_menu_xshift = node.getAttribute("hud_menu_xshift")
self.hud_menu_xshift = 1 if self.hud_menu_xshift == "" else int(self.hud_menu_xshift)
self.hud_menu_yshift = node.getAttribute("hud_menu_yshift")
self.hud_menu_yshift = 1 if self.hud_menu_yshift == "" else int(self.hud_menu_yshift)
if node.hasAttribute("TS_path"):
self.TS_path = normalizePath(node.getAttribute("TS_path"))
else:
self.TS_path = ''
self.fav_seat = {}
for fav_node in node.getElementsByTagName('fav'):
max = int(fav_node.getAttribute("max"))
fav = int(fav_node.getAttribute("fav_seat"))
self.fav_seat[max] = fav
self.layout_set = {}
for site_layout_node in node.getElementsByTagName('layout_set'):
gt = site_layout_node.getAttribute("game_type")
ls = site_layout_node.getAttribute("ls")
self.layout_set[gt]=ls
self.emails = {}
for email_node in node.getElementsByTagName('email'):
email = Email(email_node)
self.emails[email.fetchType] = email
def __str__(self):
temp = "Site = " + self.site_name + "\n"
for key in dir(self):
if key.startswith('__'): continue
if key == 'layout_set': continue
if key == 'fav_seat': continue
if key == 'emails': continue
value = getattr(self, key)
if callable(value): continue
temp = temp + ' ' + key + " = " + str(value) + "\n"
for fetchtype in self.emails:
temp = temp + str(self.emails[fetchtype]) + "\n"
for game_type in self.layout_set:
temp = temp + " game_type = %s, layout_set = %s\n" % (game_type, self.layout_set[game_type])
for max in self.fav_seat:
temp = temp + " max = %s, fav_seat = %s\n" % (max, self.fav_seat[max])
return temp
class Stat:
def __init__(self, node):
rowcol = node.getAttribute("_rowcol") # human string "(r,c)" values >0)
self.rowcol = tuple(int(s)-1 for s in rowcol[1:-1].split(',')) # tuple (r-1,c-1)
self.stat_name = node.getAttribute("_stat_name")
self.tip = node.getAttribute("tip")
self.click = node.getAttribute("click")
self.popup = node.getAttribute("popup")
self.hudprefix = node.getAttribute("hudprefix")
self.hudsuffix = node.getAttribute("hudsuffix")
self.hudcolor = node.getAttribute("hudcolor")
self.stat_loth = node.getAttribute("stat_loth")
self.stat_hith = node.getAttribute("stat_hith")
self.stat_locolor = node.getAttribute("stat_locolor")
self.stat_hicolor = node.getAttribute("stat_hicolor")
def __str__(self):
temp = " _rowcol = %s, _stat_name = %s, \n" % (self.rowcol, self.stat_name)
for key in dir(self):
if key.startswith('__'): continue
if key == '_stat_name': continue
if key == '_rowcol': continue
value = getattr(self, key)
if callable(value): continue
temp = temp + ' ' + key + " = " + str(value) + "\n"
return temp
class Stat_sets:
def __init__(self, node):
self.name = node.getAttribute("name")
self.rows = int( node.getAttribute("rows") )
self.cols = int( node.getAttribute("cols") )
self.xpad = node.getAttribute("xpad")
self.xpad = 0 if self.xpad == "" else int(self.xpad)
self.ypad = node.getAttribute("ypad")
self.ypad = 0 if self.ypad == "" else int(self.ypad)
self.stats = {}
for stat_node in node.getElementsByTagName('stat'):
stat = Stat(stat_node)
self.stats[stat.rowcol] = stat # this is the key!
def __str__(self):
temp = "Name = " + self.name + "\n"
temp = temp + " rows = %d" % self.rows
temp = temp + " cols = %d" % self.cols
temp = temp + " xpad = %d" % self.xpad
temp = temp + " ypad = %d\n" % self.ypad
for stat in self.stats.keys():
temp = temp + "%s" % self.stats[stat]
return temp
class Database:
def __init__(self, node):
self.db_name = node.getAttribute("db_name")
self.db_desc = node.getAttribute("db_desc")
self.db_server = node.getAttribute("db_server").lower()
self.db_ip = node.getAttribute("db_ip")
self.db_user = node.getAttribute("db_user")
self.db_pass = node.getAttribute("db_pass")
self.db_selected = string_to_bool(node.getAttribute("default"), default=False)
log.debug("Database db_name:'%(name)s' db_server:'%(server)s' db_ip:'%(ip)s' db_user:'%(user)s' db_pass (not logged) selected:'%(sel)s'" \
% { 'name':self.db_name, 'server':self.db_server, 'ip':self.db_ip, 'user':self.db_user, 'sel':self.db_selected} )
def __str__(self):
temp = 'Database = ' + self.db_name + '\n'
for key in dir(self):
if key.startswith('__'): continue
value = getattr(self, key)
if callable(value): continue
temp = temp + ' ' + key + " = " + repr(value) + "\n"
return temp
class Aux_window:
def __init__(self, node):
for (name, value) in node.attributes.items():
setattr(self, name, value)
def __str__(self):
temp = 'Aux = ' + self.name + "\n"
for key in dir(self):
if key.startswith('__'): continue
value = getattr(self, key)
if callable(value): continue
temp = temp + ' ' + key + " = " + value + "\n"
return temp
class Supported_games:
def __init__(self, node):
for (name, value) in node.attributes.items():
setattr(self, name, value)
self.game_stat_set = {}
for game_stat_set_node in node.getElementsByTagName('game_stat_set'):
gss = Game_stat_set(game_stat_set_node)
self.game_stat_set[gss.game_type] = gss
def __str__(self):
temp = 'Supported_games = ' + self.game_name + "\n"
for key in dir(self):
if key.startswith('__'): continue
if key == 'game_stat_set': continue
if key == 'game_name': continue
value = getattr(self, key)
if callable(value): continue
temp = temp + ' ' + key + " = " + value + "\n"
for gs in self.game_stat_set:
temp = temp + "%s" % str(self.game_stat_set[gs])
return temp
class Layout_set:
def __init__(self, node):
for (name, value) in node.attributes.items():
setattr(self, name, value)
self.layout = {}
for layout_node in node.getElementsByTagName('layout'):
lo = Layout(layout_node)
self.layout[lo.max] = lo
def __str__(self):
temp = 'Layout set = ' + self.name + "\n"
for key in dir(self):
if key.startswith('__'): continue
if key == 'layout': continue
if key == 'name': continue
value = getattr(self, key)
if callable(value): continue
temp = temp + ' ' + key + " = " + value + "\n"
for layout in self.layout:
temp = temp + "%s" % self.layout[layout]
return temp
class Game_stat_set:
def __init__(self, node):
self.game_type = node.getAttribute("game_type")
self.stat_set = node.getAttribute("stat_set")
def __str__(self):
return " Game Type: '%s' Stat Set: '%s'\n" % (self.game_type, self.stat_set)
class HHC:
def __init__(self, node):
self.site = node.getAttribute("site")
self.converter = node.getAttribute("converter")
self.summaryImporter = node.getAttribute("summaryImporter")
def __str__(self):
return "%s:\tconverter: '%s' summaryImporter: '%s'" % (self.site, self.converter, self.summaryImporter)
class Popup:
def __init__(self, node):
self.name = node.getAttribute("pu_name")
self.pu_class = node.getAttribute("pu_class")
self.pu_stats = []
self.pu_stats_submenu = []
for stat_node in node.getElementsByTagName('pu_stat'):
self.pu_stats.append(stat_node.getAttribute("pu_stat_name"))
#if stat_node.getAttribute("pu_stat_submenu"):
self.pu_stats_submenu.append(
tuple(
(stat_node.getAttribute("pu_stat_name"),
stat_node.getAttribute("pu_stat_submenu"))))
def __str__(self):
temp = "Popup = " + self.name + " Class = " + self.pu_class + "\n"
for stat in self.pu_stats:
temp = temp + " " + stat
return temp + "\n"
class Import:
def __init__(self, node):
self.node = node
self.interval = node.getAttribute("interval")
self.sessionTimeout = string_to_bool(node.getAttribute("sessionTimeout") , default=30)
self.ResultsDirectory = node.getAttribute("ResultsDirectory")
self.hhBulkPath = node.getAttribute("hhBulkPath")
self.saveActions = string_to_bool(node.getAttribute("saveActions") , default=False)
self.cacheSessions = string_to_bool(node.getAttribute("cacheSessions") , default=False)
self.publicDB = string_to_bool(node.getAttribute("publicDB") , default=False)
self.callFpdbHud = string_to_bool(node.getAttribute("callFpdbHud") , default=False)
self.fastStoreHudCache = string_to_bool(node.getAttribute("fastStoreHudCache"), default=False)
self.saveStarsHH = string_to_bool(node.getAttribute("saveStarsHH") , default=False)
if node.getAttribute("importFilters"):
self.importFilters = node.getAttribute("importFilters").split(",")
else:
self.importFilters = []
if node.getAttribute("timezone"):
self.timezone = node.getAttribute("timezone")
else:
self.timezone = "America/New_York"
def __str__(self):
return " interval = %s\n callFpdbHud = %s\n saveActions = %s\n cacheSessions = %s\n publicDB = %s\n sessionTimeout = %s\n fastStoreHudCache = %s\n ResultsDirectory = %s" \
% (self.interval, self.callFpdbHud, self.saveActions, self.cacheSessions, self.publicDB, self.sessionTimeout, self.fastStoreHudCache, self.ResultsDirectory)
class HudUI:
def __init__(self, node):
self.node = node
self.label = node.getAttribute('label')
if node.hasAttribute('card_ht'): self.card_ht = node.getAttribute('card_ht')
if node.hasAttribute('card_wd'): self.card_wd = node.getAttribute('card_wd')
if node.hasAttribute('deck_type'): self.deck_type = node.getAttribute('deck_type')
if node.hasAttribute('card_back'): self.card_back = node.getAttribute('card_back')
#
if node.hasAttribute('stat_range'): self.stat_range = node.getAttribute('stat_range')
if node.hasAttribute('stat_days'): self.hud_days = node.getAttribute('stat_days')
if node.hasAttribute('aggregation_level_multiplier'): self.agg_bb_mult = node.getAttribute('aggregation_level_multiplier')
if node.hasAttribute('seats_style'): self.seats_style = node.getAttribute('seats_style')
if node.hasAttribute('seats_cust_nums_low'): self.seats_cust_nums_low = node.getAttribute('seats_cust_nums_low')
if node.hasAttribute('seats_cust_nums_high'): self.seats_cust_nums_high = node.getAttribute('seats_cust_nums_high')
#
if node.hasAttribute('hero_stat_range'): self.h_stat_range = node.getAttribute('hero_stat_range')
if node.hasAttribute('hero_stat_days'): self.h_hud_days = node.getAttribute('hero_stat_days')
if node.hasAttribute('hero_aggregation_level_multiplier'): self.h_agg_bb_mult = node.getAttribute('hero_aggregation_level_multiplier')
if node.hasAttribute('hero_seats_style'): self.h_seats_style = node.getAttribute('hero_seats_style')
if node.hasAttribute('hero_seats_cust_nums_low'): self.h_seats_cust_nums_low = node.getAttribute('hero_seats_cust_nums_low')
if node.hasAttribute('hero_seats_cust_nums_high'): self.h_seats_cust_nums_high = node.getAttribute('hero_seats_cust_nums_high')
def __str__(self):
return " label = %s\n" % self.label
class General(dict):
def __init__(self):
super(General, self).__init__()
def add_elements(self, node):
# day_start - number n where 0.0 <= n < 24.0 representing start of day for user
# e.g. user could set to 4.0 for day to start at 4am local time
# [ HH_bulk_path was here - now moved to import section ]
for (name, value) in node.attributes.items():
log.debug(unicode(_("config.general: adding %s = %s"), "utf8") % (name,value))
self[name] = value
try:
self["version"]=int(self["version"])
except KeyError:
self["version"]=0
self["ui_language"]="system"
self["config_difficulty"]="expert"
def get_defaults(self):
self["version"]=0
self["ui_language"]="system"
self["config_difficulty"]="expert"
self["config_wrap_len"]="-1"
self["day_start"]="5"
def __str__(self):
s = ""
for k in self:
s = s + " %s = %s\n" % (k, self[k])
return(s)
class GUICashStats(list):
"""<gui_cash_stats>
<col col_name="game" col_title="Game" disp_all="True" disp_posn="True" field_format="%s" field_type="str" xalignment="0.0" />
...
</gui_cash_stats>
"""
def __init__(self):
super(GUICashStats, self).__init__()
def add_elements(self, node):
# is this needed?
for child in node.childNodes:
if child.nodeType == child.ELEMENT_NODE:
col_name, col_title, disp_all, disp_posn, field_format, field_type, xalignment=None, None, True, True, "%s", "str", 0.0
if child.hasAttribute('col_name'): col_name = child.getAttribute('col_name')
if child.hasAttribute('col_title'): col_title = child.getAttribute('col_title')
if child.hasAttribute('disp_all'): disp_all = string_to_bool(child.getAttribute('disp_all'))
if child.hasAttribute('disp_posn'): disp_posn = string_to_bool(child.getAttribute('disp_posn'))
if child.hasAttribute('field_format'): field_format = child.getAttribute('field_format')
if child.hasAttribute('field_type'): field_type = child.getAttribute('field_type')
try:
if child.hasAttribute('xalignment'): xalignment = float(child.getAttribute('xalignment'))
except ValueError:
print(_("bad number in xalignment was ignored"))
log.info(_("bad number in xalignment was ignored"))
self.append( [col_name, col_title, disp_all, disp_posn, field_format, field_type, xalignment] )
def get_defaults(self):
"""A list of defaults to be called, should there be no entry in config"""
# SQL column name, display title, display all, display positional, format, type, alignment
defaults = [ [u'game', u'Game', True, True, u'%s', u'str', 0.0],
[u'hand', u'Hand', False, False, u'%s', u'str', 0.0],
[u'plposition', u'Posn', False, False, u'%s', u'str', 1.0],
[u'pname', u'Name', False, False, u'%s', u'str', 0.0],
[u'n', u'Hds', True, True, u'%1.0f', u'str', 1.0],
[u'avgseats', u'Seats', False, False, u'%3.1f', u'str', 1.0],
[u'vpip', u'VPIP', True, True, u'%3.1f', u'str', 1.0],
[u'pfr', u'PFR', True, True, u'%3.1f', u'str', 1.0],
[u'pf3', u'PF3', True, True, u'%3.1f', u'str', 1.0],
[u'aggfac', u'AggFac', True, True, u'%2.2f', u'str', 1.0],
[u'aggfrq', u'AggFreq', True, True, u'%3.1f', u'str', 1.0],
[u'conbet', u'ContBet', True, True, u'%3.1f', u'str', 1.0],
[u'rfi', u'RFI', True, True, u'%3.1f', u'str', 1.0],
[u'steals', u'Steals', True, True, u'%3.1f', u'str', 1.0],
[u'saw_f', u'Saw_F', True, True, u'%3.1f', u'str', 1.0],
[u'sawsd', u'SawSD', True, True, u'%3.1f', u'str', 1.0],
[u'wtsdwsf', u'WtSDwsF', True, True, u'%3.1f', u'str', 1.0],
[u'wmsd', u'W$SD', True, True, u'%3.1f', u'str', 1.0],
[u'flafq', u'FlAFq', True, True, u'%3.1f', u'str', 1.0],
[u'tuafq', u'TuAFq', True, True, u'%3.1f', u'str', 1.0],
[u'rvafq', u'RvAFq', True, True, u'%3.1f', u'str', 1.0],
[u'pofafq', u'PoFAFq', False, False, u'%3.1f', u'str', 1.0],
[u'net', u'Net($)', True, True, u'%6.2f', u'cash', 1.0],
[u'bbper100', u'bb/100', True, True, u'%4.2f', u'str', 1.0],
[u'rake', u'Rake($)', True, True, u'%6.2f', u'cash', 1.0],
[u'bb100xr', u'bbxr/100', True, True, u'%4.2f', u'str', 1.0],
[u'stddev', u'Standard Deviation', True, True, u'%5.2f', u'str', 1.0]
]
for col in defaults:
self.append (col)
# def __str__(self):
# s = ""
# for l in self:
# s = s + " %s = %s\n" % (k, self[k])
# return(s)
class RawHands:
def __init__(self, node=None):
if node==None:
self.save="error"
self.compression="none"
#print _("missing config section raw_hands")
else:
save=node.getAttribute("save")
if save in ("none", "error", "all"):
self.save=save
else:
print (_("Invalid config value for %s, defaulting to %s") % (raw_hands.save, "\"error\""))
self.save="error"
compression=node.getAttribute("compression")
if save in ("none", "gzip", "bzip2"):
self.compression=compression
else:
print (_("Invalid config value for %s, defaulting to %s") % (raw_hands.compression, "\"none\""))
self.compression="none"
#end def __init__
def __str__(self):
return " save= %s, compression= %s\n" % (self.save, self.compression)
#end class RawHands
class RawTourneys:
def __init__(self, node=None):
if node==None:
self.save="error"
self.compression="none"
#print _("missing config section raw_tourneys")
else:
save=node.getAttribute("save")
if save in ("none", "error", "all"):
self.save=save
else:
print (_("Invalid config value for %s, defaulting to %s") % (raw_tourneys.save, "\"error\""))
self.save="error"
compression=node.getAttribute("compression")
if save in ("none", "gzip", "bzip2"):
self.compression=compression
else:
print (_("Invalid config value for %s, defaulting to %s") % (raw_tourneys.compression, "\"none\""))
self.compression="none"
#end def __init__
def __str__(self):
return " save= %s, compression= %s\n" % (self.save, self.compression)
#end class RawTourneys
class Config:
def __init__(self, file = None, dbname = '', custom_log_dir='', lvl='INFO'):
self.install_method = INSTALL_METHOD
self.fpdb_root_path = FPDB_ROOT_PATH
self.appdata_path = APPDATA_PATH
self.config_path = CONFIG_PATH
self.FPDB_ROOT_PATH = FPDB_ROOT_PATH
self.graphics_path = GRAPHICS_PATH
self.os_family = OS_FAMILY
self.posix = POSIX
self.python_version = PYTHON_VERSION
if not os.path.exists(CONFIG_PATH):
os.mkdir(CONFIG_PATH)
if custom_log_dir and os.path.exists(custom_log_dir):
self.dir_log = unicode(custom_log_dir, "utf8")
else:
self.dir_log = os.path.join(CONFIG_PATH, u'log')
self.log_file = os.path.join(self.dir_log, u'fpdb-log.txt')
self.dir_database = os.path.join(CONFIG_PATH, u'database')
log = logging.getLogger("config")
# "file" is a path to an xml file with the fpdb/HUD configuration
# we check the existence of "file" and try to recover if it doesn't exist
# self.default_config_path = self.get_default_config_path()
self.example_copy = False
if file is not None: # config file path passed in
file = os.path.expanduser(file)
if not os.path.exists(file):
print(_("Configuration file %s not found. Using defaults.") % (file))
sys.stderr.write(_("Configuration file %s not found. Using defaults.") % (file))
file = None
self.example_copy,example_file = True,None
if file is None: (file,self.example_copy,example_file) = get_config(u"HUD_config.xml", True)
self.file = file
self.supported_sites = {}
self.supported_games = {}
self.supported_databases = {} # databaseName --> Database instance
self.aux_windows = {}
self.layout_sets = {}
self.stat_sets = {}
self.hhcs = {}
self.popup_windows = {}
self.db_selected = None # database the user would like to use
self.general = General()
self.emails = {}
self.gui_cash_stats = GUICashStats()
self.site_ids = {} # site ID list from the database
added,n = 1,0 # use n to prevent infinite loop if add_missing_elements() fails somehow
while added > 0 and n < 2:
n = n + 1
log.info(unicode(_("Reading configuration file %s"), "utf8") % file)
#print (("\n"+_("Reading configuration file %s")+"\n") % file)
try:
doc = xml.dom.minidom.parse(file)
self.doc = doc
self.file_error = None
except:
import traceback
log.error((_("Error parsing %s.") % (file)) + _("See error log file."))
traceback.print_exc(file=sys.stderr)
self.file_error = sys.exc_info()[1]
# we could add a parameter to decide whether to return or read a line and exit?
return
#print "press enter to continue"
#sys.stdin.readline()
#sys.exit()
if (not self.example_copy) and (example_file is not None):
# reads example file and adds missing elements into current config
added = self.add_missing_elements(doc, example_file)
if doc.getElementsByTagName("general") == []:
self.general.get_defaults()
for gen_node in doc.getElementsByTagName("general"):
self.general.add_elements(node=gen_node) # add/overwrite elements in self.general
if int(self.general["version"]) == CONFIG_VERSION:
self.wrongConfigVersion = False
else:
self.wrongConfigVersion = True
if doc.getElementsByTagName("gui_cash_stats") == []:
self.gui_cash_stats.get_defaults()
for gcs_node in doc.getElementsByTagName("gui_cash_stats"):
self.gui_cash_stats.add_elements(node=gcs_node) # add/overwrite elements in self.gui_cash_stats
# s_sites = doc.getElementsByTagName("supported_sites")
for site_node in doc.getElementsByTagName("site"):
site = Site(node = site_node)
self.supported_sites[site.site_name] = site
# s_games = doc.getElementsByTagName("supported_games")
for supported_game_node in doc.getElementsByTagName("game"):
supported_game = Supported_games(supported_game_node)
self.supported_games[supported_game.game_name] = supported_game
# parse databases defined by user in the <supported_databases> section
# the user may select the actual database to use via commandline or by setting the selected="bool"
# attribute of the tag. if no database is explicitely selected, we use the first one we come across
# s_dbs = doc.getElementsByTagName("supported_databases")
#TODO: do we want to take all <database> tags or all <database> tags contained in <supported_databases>
# ..this may break stuff for some users. so leave it unchanged for now untill there is a decission
for db_node in doc.getElementsByTagName("database"):
db = Database(node=db_node)
if db.db_name in self.supported_databases:
raise ValueError("Database names must be unique")
if self.db_selected is None or db.db_selected:
self.db_selected = db.db_name
db_node.setAttribute("default", "True")
self.supported_databases[db.db_name] = db
#TODO: if the user may passes '' (empty string) as database name via command line, his choice is ignored
# ..when we parse the xml we allow for ''. there has to be a decission if to allow '' or not
if dbname and dbname in self.supported_databases:
self.db_selected = dbname
#NOTE: fpdb can not handle the case when no database is defined in xml, so we throw an exception for now
if self.db_selected is None:
raise ValueError('There must be at least one database defined')
# s_dbs = doc.getElementsByTagName("mucked_windows")
for aw_node in doc.getElementsByTagName("aw"):
aw = Aux_window(node = aw_node)
self.aux_windows[aw.name] = aw
for ls_node in doc.getElementsByTagName("ls"):
ls = Layout_set(node = ls_node)
self.layout_sets[ls.name] = ls
for ss_node in doc.getElementsByTagName("ss"):
ss = Stat_sets(node = ss_node)
self.stat_sets[ss.name] = ss
# s_dbs = doc.getElementsByTagName("mucked_windows")
for hhc_node in doc.getElementsByTagName("hhc"):
hhc = HHC(node = hhc_node)
self.hhcs[hhc.site] = hhc
# s_dbs = doc.getElementsByTagName("popup_windows")
for pu_node in doc.getElementsByTagName("pu"):
pu = Popup(node = pu_node)
self.popup_windows[pu.name] = pu
for imp_node in doc.getElementsByTagName("import"):
imp = Import(node = imp_node)
self.imp = imp
for hui_node in doc.getElementsByTagName('hud_ui'):
hui = HudUI(node = hui_node)
self.ui = hui
db = self.get_db_parameters()
if db['db-password'] == 'YOUR MYSQL PASSWORD':
df_file = self.find_default_conf()
if df_file is None: # this is bad
pass
else:
df_parms = self.read_default_conf(df_file)
self.set_db_parameters(db_name = 'fpdb', db_ip = df_parms['db-host'],
db_user = df_parms['db-user'],
db_pass = df_parms['db-password'])
self.save(file=os.path.join(CONFIG_PATH, u"HUD_config.xml"))
if doc.getElementsByTagName("raw_hands") == []:
self.raw_hands = RawHands()
for raw_hands_node in doc.getElementsByTagName('raw_hands'):
self.raw_hands = RawHands(raw_hands_node)
if doc.getElementsByTagName("raw_tourneys") == []:
self.raw_tourneys = RawTourneys()
for raw_tourneys_node in doc.getElementsByTagName('raw_tourneys'):
self.raw_tourneys = RawTourneys(raw_tourneys_node)
#print ""
#end def __init__
def add_missing_elements(self, doc, example_file):
""" Look through example config file and add any elements that are not in the config
May need to add some 'enabled' attributes to turn things off - can't just delete a
config section now because this will add it back in"""
nodes_added = 0
try:
example_doc = xml.dom.minidom.parse(example_file)
except:
log.error((_("Error parsing example configuration file %s.") % (example_file)) + _("See error log file."))
return nodes_added
for cnode in doc.getElementsByTagName("FreePokerToolsConfig"):
for example_cnode in example_doc.childNodes:
if example_cnode.localName == "FreePokerToolsConfig":
for e in example_cnode.childNodes:
#print "nodetype", e.nodeType, "name", e.localName, "found", len(doc.getElementsByTagName(e.localName))
if e.nodeType == e.ELEMENT_NODE and doc.getElementsByTagName(e.localName) == []:
new = doc.importNode(e, True) # True means do deep copy
t_node = self.doc.createTextNode(" ")
cnode.appendChild(t_node)
cnode.appendChild(new)
t_node = self.doc.createTextNode("\r\n\r\n")
cnode.appendChild(t_node)