forked from NobahdiAtoll/CRDataManager
-
Notifications
You must be signed in to change notification settings - Fork 1
/
dmClasses.py
1554 lines (1237 loc) · 72.1 KB
/
dmClasses.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
import clr
import System
import System.IO
import dmGlobals
from __builtin__ import isinstance
from System import StringSplitOptions
from System import Array
clr.AddReference('System.Text.RegularExpressions')
clr.AddReference('System.Xml.Linq')
import System.Text.RegularExpressions
import System.Xml
from dmGlobals import dmConversionError
from System.Text.RegularExpressions import Regex, RegexOptions, Match
from System.Collections.Generic import List
from System.Xml.Linq import *
from System.Collections.Generic import Dictionary, List
from dmGlobals import *
from System.IO import File, Directory
class dmNode:
"""Base of all classes used in a dmCollection"""
def getName(self): return self.__Name
def setName(self, strName): self.__Name = strName
Name = property(getName, setName)
def getComment(self): return self.__Comment
def setComment(self, strComment): self.__Comment = strComment
Comment = property(getComment, setComment)
def getParent(self): return self.__Parent
def setParent(self, dmcContainer): return self.__Parent
Parent = property(getParent, setParent)
def __init__(self, dmnparent, strParameters):
if dmGlobals.TraceFunctionMessages:
print 'dmNode constructor: dmNode(dmNodeParent, strParameters)'
self.Parent = dmnparent #this is not necessary for processing dmNodes while running but will come in handy for the editor
self.Name = '' #all inheriting nodes are capable of having a name
self.Comment = '' #all inheriting nodes are capabale of having a comment
pass
def ToXML(self, elementName):
if dmGlobals.TraceFunctionMessages:
print 'Method dmNode:ToXML(elementName)'
baseElement = XElement(XName.Get(elementName))
if self.Name != '' and self.Name != None:
baseElement.Add(Xattribute(XName.Get('name'), self.Name))
if self.Comment != '' and self.Comment != None:
baseElement.Add(XAttribute(XName.Get('comment'), self.Comment))
return baseElement
def FromXML(self, element):
if dmGlobals.TraceFunctionMessages:
print 'Method dmNode:ToXML(element)'
if element.Attribute(XName.Get('name')) != None:
self.Name = element.Attribute(XName.Get('name')).Value
if element.Attribute(XName.Get('comment')) != None:
self.Comment = element.Attribute(('comment')).Value
pass
def ProcessBook(self, book, bgWorker):
if dmGlobals.TraceFunctionMessages:
print 'Method: dmNode:ProcessBook(book, backgroundWorker)'
strReport = ''
return strReport
class dmContainer(dmNode):
"""a container that contains groups and rulesets [base for dmCollection and dmGroup]"""
def getGroups(self): return self.__Groups
def setGroups(self, groups): self.__Groups = List[dmGroup](groups)
Groups = property(getGroups, setGroups)
def getRulesets(self): return self.__Rulesets
def setRulesets(self, rulesets): self.__Rulesets = List[dmRuleset](rulesets)
Rulesets = property(getRulesets, setRulesets)
def __init__(self, dmnparent, strParameters):
"""Initializes a dmContainer object"""
if dmGlobals.TraceFunctionMessages:
print 'dmContainer constructor: dmContainer(dmNodeParent, objParameters)'
dmNode.__init__(self, dmnparent, strParameters) #initialize all properties inheirited from dmNode
self.Groups = [] #create Group List
self.Rulesets = [] #create Ruleset List
pass
def ParseGroup(self, arrParameters, nStartLine, dmcParent):
if dmGlobals.TraceFunctionMessages:
print 'Method dmConainer:ParseGroup(stingarrayParameters, intStartLine, dmContainerToAddTo)'
nReturn = nStartLine #integer value that will send back the line number of the final line parsed
newGroup = dmGroup(dmcParent, None) #create a new group that will hold the new group info
#Parse Group Info from line
if arrParameters[nReturn].startswith(GROUPHEADER): #if the current line starts with the defined GROUP HEADER in dmGlobals
GroupInfo = self.ParseNodeInfo(arrParameters[nReturn]) #Parse info for new Group into a dict Item
newGroup.Name = GroupInfo['GROUP'].strip() #set Group name from group info
if GroupInfo.has_key('COMMENT'): #if Comment is provided in GroupInfo
newGroup.Comment = GroupInfo['COMMENT'].strip() #set Comment from GroupInfo
if GroupInfo.has_key('FILTERSANDDEFAULTS'): #if FILTERSANDDEFAULTS exixts in Group Info
newGroup.FiltersAndDefaults = dmRuleset(None, GroupInfo['FILTERSANDDEFAULTS'].strip()) #set the FiltersAndDefaults Ruleset
nReturn = nReturn + 1 #increment current line number
while not arrParameters[nReturn].startswith(dmGlobals.GROUPENDER): #if the line does not equal the "GROUPENDER" defined in dmGlobals
if arrParameters[nReturn].startswith(dmGlobals.GROUPHEADER): #If CURRENT line is a group header
nReturn = self.ParseGroup(arrParameters, nReturn, newGroup) #create and a new Group with this group as parent
elif arrParameters[nReturn].startswith(dmGlobals.RULESETHEADER) or not arrParameters[nReturn].startswith('#'): #else if the current line is a RULESETHEADER or uncommented line
nReturn = self.ParseRuleset(arrParameters, nReturn, newGroup) #Parse and add new Ruleset to this group
else: #otherwise
nReturn = nReturn + 1 #increment line number
dmcParent.Groups.Add(newGroup) #finally add the created group to the dmContainer node defined as dmcParent
nReturn = nReturn + 1 #increment line number
return nReturn #return next
def ParseRuleset(self, arrParameters, nStartLine, dmcParent):
"""Parses Ruleset as a child Ruleset of the dmContainer: dmcParent"""
if dmGlobals.TraceFunctionMessages:
print 'Method: dmContainer:ParseRuleset(stringarrayParameters, intStartLine, dmContainerToMakeParent)'
nReturn = nStartLine #assign current defined start line as the line number to return
newRuleset = dmRuleset(dmcParent, None) #create a new Ruleset to house parsed info
if arrParameters[nReturn].startswith(dmGlobals.RULESETHEADER): #if the current line is a RulesetHeader
RulesetInfo = self.ParseNodeInfo(arrParameters[nReturn]) #Parse Ruleset Info from line
if RulesetInfo.has_key('NAME'): #if Ruleset Info Contains a Name key
newRuleset.Name = RulesetInfo['NAME'] #set new Ruleset Name
if RulesetInfo.has_key('COMMENT'): #if Ruleset Info Contains a Comment Key
newRuleset.Comment = RulesetInfo['COMMENT'] #set new Ruleset Comment
nReturn = nReturn + 1 #after parsing Ruleset Info move to next line
newRuleset.ParseParameters(arrParameters[nReturn]) #actually parse ruleset if line is ruleset
nReturn = nReturn + 1 #set Next Line as the return value
dmcParent.Rulesets.Add(newRuleset) # add new Ruleset to dmContainer dmcParent
return nReturn #return next line value
def ParseNodeInfo(self, strInfo):
"""Retrieves info values from headers"""
if dmGlobals.TraceFunctionMessages: print 'Method: dmContainer:ParseNodeInfo(stringInfo)'
NodeInfo = dict() #setup a dictionary to hold values
parseInfo = strInfo.strip('#') #strip Comment item
parseInfo = parseInfo.lstrip('@ ')
listInfo = parseInfo.split('@ ') #use @ to split Values
for item in listInfo:
if item != None and item.strip() != '':
dicItem = item.strip().split(' ',1)
if len(dicItem) > 1:
NodeInfo[dicItem[0]] = dicItem[1]
elif len(dicItem) > 0:
NodeInfo[dicItem[0]] = ''
return NodeInfo
def ParseParameters(self, strParameters):
"""does nothing, define this in inherited dmContainers"""
if dmGlobals.TraceFunctionMessages: print 'Method: dmContainer:ParseParameters(objParameters)'
pass
def ProcessBook(self, book, bgWorker):
if dmGlobals.TraceFunctionMessages: print 'Method: dmContainer:ProcessBook(book, backgroundWorker)'
strReport = ''
if not bgWorker.CancellationPending:
if dmGlobals.TraceGeneralMessages: print "Processing child groups..."
for group in self.Groups:
if dmGlobals.TraceGeneralMessages: print 'verifying user has not cancelled process...'
if not bgWorker.CancellationPending:
strGroupReport = group.ProcessBook(book, bgWorker)
if strGroupReport != None and strGroupReport != '':
strReport = dmGlobals.AppendReport(strReport, strGroupReport)
else:
strReport = strReport + System.Environment.NewLine + 'Process cancelled by user'
if dmGlobals.TraceGeneralMessages:
print 'Process cancelled by user'
print 'backing out of process...'
break
if dmGlobals.TraceGeneralMessages: print "Processing child rulesets..."
for ruleset in self.Rulesets:
if dmGlobals.TraceGeneralMessages: print 'verifying user has not cancelled process...'
if not bgWorker.CancellationPending:
if dmGlobals.TraceGeneralMessages: print 'Processing book...'
strRulesetReport = ruleset.ProcessBook(book, bgWorker)
if strRulesetReport != None and strRulesetReport != '':
strReport = dmGlobals.AppendReport(strReport, strRulesetReport)
else:
if dmGlobals.TraceGeneralMessages:
print 'Process cancelled by user'
print 'backing out of process...'
break
else:
strReport = dmGlobals.AppendReport(strReport, System.Environment.NewLine + 'Process cancelled by user')
if dmGlobals.TraceGeneralMessages:
print 'Process cancelled by user'
print 'backing out of process...'
if dmGlobals.TraceFunctionMessages: print 'Exiting process dmContainer:ProcessBook(book, bgWorker)'
return strReport
def ToXML(self, elementName):
if dmGlobals.TraceFunctionMessages: print 'Method: dmContainer:ToXML(stringElementName)'
baseElement = dmNode.ToXML(self, elementName)
for item in self.Groups:
baseElement.append(item.XMLSerialize('group'))
for item in self.Rulesets:
baseElement.append(item.XMLSerialize('ruleset'))
return baseElement
def FromXML(self, element):
if dmGlobals.TraceFunctionMessages: print 'Method: dmContainer:FromXML(xmlElement)'
dmNode.FromXML(self, element)
for group in element.Elements(XName.Get('group')):
self.Groups.append(dmGroup(self, group))
for ruleset in element.Elements(XName.Get('ruleset')):
self.Rulesets.append(dmRuleset(self, ruleset))
pass
class dmCollection(dmContainer):
"""The base object for groups and rulesets"""
def getDisabled(self): return self.__Disabled
def setDisabled(self, dmgGroup): self.__Disabled = dmgGroup
Disabled = property(getDisabled, setDisabled)
def getVersion(self): return self.__Version
def setVersion(self, version): self.__setversion__(version)
Version = property(getVersion, setVersion)
def __init__(self, strParameters):
if dmGlobals.TraceFunctionMessages: print 'dmCollection constructor: dmCollection(objParameters)'
if dmGlobals.TraceGeneralMessages: print 'Compiling Ruleset Collection'
dmContainer.__init__(self, None, strParameters)
self.Disabled = dmGroup(self)
self.Version = System.Version(1,1,9,9)
if strParameters != None:
if isinstance(strParameters, XElement):
self.FromXML(strParameters)
else:
self.ParseParameters(strParameters)
pass
def __setversion__(self, vItem):
if dmGlobals.TraceFunctionMessages: print 'Method: dmCollection:__setversion__(objVersion)'
if isinstance(vItem, System.Version):
self.Version = vItem
elif isinstance(vItem, str):
self.Version = System.Version.Parse(vItem)
def ParseParameters(self, strParameters):
"""Parses the file to a collection"""
if dmGlobals.TraceFunctionMessages: print 'Method: dmCollection:ParseParameters(objParameters)'
if File.Exists(strParameters):
try:
self.FromXML(System.Xml.Linq.XDocument.Load(strParameters).Root)
except:
self.Parse(File.ReadAllLines(strParameters))
pass
def Parse(self, arrParameters):
"""Parses the array of strings to a ruleset collection"""
if dmGlobals.TraceFunctionMessages: print 'Method: dmCollection:Parse(stringarrayParameters)'
nReturn = 0
while nReturn < arrParameters.Length and not arrParameters[nReturn].startswith(dmGlobals.ENDER):
if arrParameters[nReturn].startswith(dmGlobals.AUTHORHEADER):
self.Name = arrParameters[nReturn].replace(dmGlobals.AUTHORHEADER,'')
nReturn = nReturn + 1
elif arrParameters[nReturn].startswith(dmGlobals.NOTESHEADER):
nReturn = self.RetrieveNotes(arrParameters, nReturn)
elif arrParameters[nReturn].startswith(dmGlobals.RULESETHEADER) or not arrParameters[nReturn].startswith('#'):
nReturn = self.ParseRuleset(arrParameters, nReturn, self)
elif arrParameters[nReturn].startswith(dmGlobals.GROUPHEADER):
nReturn = self.ParseGroup(arrParameters, nReturn, self)
else: nReturn = nReturn + 1
pass
def RetrieveNotes(self, arrParameters, nStartLine):
if dmGlobals.TraceFunctionMessages: print 'Method: dmCollection:RetrieveNotes(stringarrayParameters, intStartLine)'
nReturn = nStartLine
self.Comment = ''
while not arrParameters[nReturn].startswith(NOTESENDER):
self.Comment += arrParameters[nReturn].lstrip('# ') + System.Environment.NewLine
nReturn = nReturn + 1
pass
def ProcessBook(self, book, bgWorker):
if dmGlobals.TraceFunctionMessages:
print 'Method: dmCollection:ProcessBook(book, backgroundWorker)'
strReport = ''
if not bgWorker.CancellationPending:
strReport = dmContainer.ProcessBook(self, book, bgWorker)
if dmGlobals.TraceFunctionMessages:
print 'Exiting Method: dmCollection:ProcessBook(book, backgroundWorker)'
return strReport
def ToXML(self, elementName):
if dmGlobals.TraceFunctionMessages:
print 'Method: dmCollection:ToXML(stringElementName)'
baseElement = dmContainer.ToXML(self, elementName)
baseElement.Add(self.Disabled.XMLSerialize('disabled'))
return baseElement
def FromXML(self, element):
if dmGlobals.TraceFunctionMessages: print 'Method: dmCollection:FromXML(xmlElement)'
dmContainer.FromXML(self, element)
self.Disabled = dmGroup(self, element.Element(XName.Get('Disabled')))
self.__setversion__(element.Attribute(XName.Get('version')).Value)
pass
class dmGroup(dmContainer):
"""a named group of groups and rulesets (derived from dmContainer)"""
def getFiltersAndDefaults(self): return self.__FiltersAndDefaults
def setFiltersAndDefaults(self, dmrRuleset): self.__FiltersAndDefaults = dmrRuleset
FiltersAndDefaults = property(getFiltersAndDefaults, setFiltersAndDefaults)
def __init__(self, dmcparent, strParameters=None):
if dmGlobals.TraceFunctionMessages: print 'dmGroup constructor: dmGroup(dmContainerParent, objParameters)'
dmContainer.__init__(self, dmcparent, strParameters)
self.FiltersAndDefaults = dmRuleset(self, None)
if strParameters != None:
if isinstance(strParameters, XElement):
self.FromXML(strParameters)
else:
self.ParseParameters(strParameters)
pass
def ParseParameters(self, strParameters):
"""Parses Parameters of Group from a string or list of parameters"""
if dmGlobals.TraceFunctionMessages: print 'Method: dmGroup:ParseParameters(objParameters)'
if isinstance(strParameters, str) or isinstance(strParameters, list):
arrParameters = list()
if isinstance(strParameters, str):
arrParameters = strParameters.splitlines() #split string into lines
elif isinstance(strParameters, list):
arrParameters = strParameters
nReturn = 0
#Parse Group Info from line
if arrParameters[nReturn].startswith(GROUPHEADER):
GroupInfo = self.ParseNodeInfo(arrParameters[nReturn])
self.Name = GroupInfo['GROUP'].strip()
if GroupInfo.haskey('COMMENT'):
self.Comment = GroupInfo['COMMENT'].strip()
if GroupInfo.haskey('FILTERSANDDEFAULTS'):
self.FiltersAndDefaults = dmRuleset(self,GroupInfo['FILTERSANDDEFAULTS'].strip())
#increment nReturn
nReturn = nReturn + 1
while nReturn < len(arrParameters) and not arrParameters[nReturn].startswith(GROUPENDER):
if arrParameters[nReturn].startswith(GROUPHEADER):
nReturn = self.ParseGroup(arrParameters, nReturn, self)
elif arrParameters[nReturn].startswith(RULESETHEADER) or not arrParameters[nReturn].startswith('#'):
nReturn = ParseRuleset(arrParameters, nReturn, self)
elif isinstance(strParameters, XElement):
self.FromXML(strParameters)
pass
def MeetsConditions(self, book):
"""Determines if the book matches all Rules in FiltersAndDefaults Ruleset"""
if dmGlobals.TraceFunctionMessages: print 'Method: dmGroup:MeetsConditions(book)'
return self.FiltersAndDefaults.MeetsConditions(book)
def ProcessBook(self, book, bgWorker):
if dmGlobals.TraceFunctionMessages:
print 'Method: dmGroup:ProcessBook(book, backgroundWorker)'
strReport = ''
if self.MeetsConditions(book):
if dmGlobals.TraceGeneralMessages: print 'Book: \'' + book.CaptionWithoutTitle + '\' Meets conditions, Processing.'
strReport = dmContainer.ProcessBook(self, book, bgWorker)
#groupReport
CompiledReport = ''
if dmGlobals.TraceGeneralMessages: print 'Applying Default actions of group \'' + self.Name
strTempReport = ''
for action in self.FiltersAndDefaults.Actions:
strTempReport = action.Apply(book) + System.Environment.NewLine
if strTempReport != None and strTempReport != '':
CompiledReport = CompiledReport + strTempReport
if CompiledReport != '':
CompiledReport = 'Group: \'' + self.Name + '\' touched book: ' + book.CaptionWithoutTitle + System.Environment.NewLine + CompiledReport
strReport = strReport + System.Environment.NewLine + CompiledReport
else:
if dmGlobals.TraceGeneralMessages: print 'Conditions set forth by filters of group\'' + self.Name + '\' not met, skiping group.'
if dmGlobals.TraceFunctionMessages: print 'Exiting Method: dmGroup:ProcessBook(book, backgroundWorker)'
return strReport
def ToXML(self, elementName):
if dmGlobals.TraceFunctionMessages: print 'Method: dmGroup:ToXML(stringElementName)'
baseElement = dmContainer.ToXML(self, elementName)
baseElement.Add(self.FiltersAndDefaults.ToXML('filtersanddefaults'))
return baseElement
def FromXML(self, element):
if dmGlobals.TraceFunctionMessages: print 'Method: dmGroup:FromXML(xmlElement)'
dmContainer.FromXML(self, element)
self.FiltersAndDefaults = dmRuleset(self, element.Element(XName.Get('filtersanddefaults')))
pass
def ToString(self):
if dmGlobals.TraceFunctionMessages: print 'Method: dmGroup:ToString()'
strReturn = 'Group: ' + self.Name + ' ' + self.FiltersAndDefaults.HumanizeRules()
return strReturn
class dmRuleset(dmNode):
"""Container for rules and actions"""
def getRulesetMode(self): return self.__RulesetMode
def setRulesetMode(self, strANDorOR):
if strANDorOR.lower() == 'and': self.__RulesetMode = 'AND'
elif strANDorOR.lower() == 'or': self.__RulesetMode = 'OR'
else: self.__RulesetMode = 'AND'
RulesetMode = property(getRulesetMode, setRulesetMode)
def getRules(self): return self.__Rules
def setRules(self, lstRules): self.__Rules = List[dmRule](lstRules)
Rules = property(getRules, setRules)
def getActions(self): return self.__Actions
def setActions(self, lstActions): self.__Actions = List[dmAction](lstActions)
Actions = property(getActions, setActions)
def __init__(self, dmcparent, strParameters=None):
"""initializes ruleset instance"""
if dmGlobals.TraceFunctionMessages: print 'dmRuleset constructor: dmRuleset(objParameters)'
dmNode.__init__(self, dmcparent, strParameters) #calls base initialize which adds base fields
self.RulesetMode = 'AND' #sets ruleset mode by default to AND ParseParameters call (from dmNode) later corrrects if and is used
self.Rules = [] #initializes list of rules
self.Actions = [] #initializes list of actions
if strParameters != None:
if isinstance(strParameters, XElement):
self.FromXML(strParameters)
else:
self.ParseParameters(strParameters)
pass
def ParseParameters(self, strParameters):
if dmGlobals.TraceFunctionMessages: print 'Method: dmRuleset:ParseParameters(objParameters)'
if isinstance(strParameters, str):
strParsed = strParameters
"""parses ruleset""" #note: this function is called from dmNode initialization
if strParsed.startswith('#@ Invalid Ruleset'):
strParsed = strParsed.split('.', 1)[1]
if strParsed.strip() != '': #if we aren't dealing with an empty string
if strParsed.startswith('|'): #if the ruleset mode is set as OR
self.RulesetMode = 'OR' #specify OR as ruleset mode
rulesAndActions = strParsed.lstrip('|').split('=>',1) #split Rules and Actions
self.ParseItemParameters(rulesAndActions[0], 'Rule') #Parse Rules
self.ParseItemParameters(rulesAndActions[1], 'Action') #Parse Actions
elif isinstance(strParameters, XElement):
self.FromXML(strParameters)
pass
def ParseItemParameters(self, strRules, strRuleOrAction):
"""Parses strRules(string) to Rules Or Actions as specified by strRuleOrAction and adds it to this ruleset accordingly"""
if dmGlobals.TraceFunctionMessages: print 'Method: dmRuleset:ParseItemParameters(stringParameters, stringRuleOrAction)'
parameters = strRules.split('> <') #split into individual rules or actions
for parameter in parameters: #for each item in the created list
if parameter.strip() != '': #if the item is not an empty string
if strRuleOrAction == 'Rule': #if indicated as a Rule
self.Rules.Add(dmRule(self, parameter)) #create and add a dmRule instance to this Ruleset's Rules
elif strRuleOrAction == 'Action': #if indicated as an Action
self.Actions.Add(dmAction(self, parameter)) #create and add a dmAction instance to this Ruleset's Actions
pass
def MeetsConditions(self, book):
if dmGlobals.TraceFunctionMessages: print 'Method: dmRuleset:MeetsConditions(book)'
bReturn = True
if self.Rules.Count < 1:
if dmGlobals.TraceGeneralMessages: print 'There are no rules defined.'
return True
if self.RulesetMode == 'OR': #if we are using OR mode
if dmGlobals.TraceGeneralMessages: print 'Checking rules in OR Mode'
if len(self.Rules) > 0:
bReturn = False #we need False to be default if we are in OR mode but only if there are rules present.
for rule in self.Rules: #iterate over rules
if rule.Match(book): #we only need one match to decide if conditions are met in OR mode
bReturn = True #set return True as soon as a match found
break #and then exit iteration
else: #if we are using AND mode
if dmGlobals.TraceGeneralMessages: print 'Checking rules in AND Mode'
for rule in self.Rules: #iterate through Rules
if not rule.Match(book): # we only need one non-match to determine conditions are not met
bReturn = False #set return to False as soon as non-match found
break #and then exit iteration
return bReturn #return True or False
def ApplyActions(self, book):
if dmGlobals.TraceFunctionMessages: print 'Method: dmRuleset:ApplyActions(book)'
strReport = ''
for action in self.Actions:
if dmGlobals.TraceGeneralMessages: print 'Applying Actions...'
strTemp = action.Apply(book)
if strTemp != '':
if strReport != '': strReport = strReport + System.Environment.NewLine
if dmGlobals.TraceGeneralMessages: print 'Value was modified, adding info to report'
strReport = strReport + strTemp
if dmGlobals.TraceFunctionMessages: print 'Exiting Method: dmRuleset:ApplyActions(book)'
return strReport
def ProcessBook(self, book, bgwProcess):
"""Begins Processing of Book with this Ruleset"""
if dmGlobals.TraceFunctionMessages: print 'Method: dmRuleset:ProcessBook(book, backgroundWorker)'
strReport = ''
if dmGlobals.TraceGeneralMessages: print 'Checking rules...'
if self.MeetsConditions(book): #if Rules meet conditions
if dmGlobals.TraceGeneralMessages:
print 'Book met all conditional rules'
print 'Processing Ruleset: ' + self.Name
#create a dictionary of values
strTemp = self.ApplyActions(book)
if strTemp != '':
strReport = System.Environment.NewLine + 'Book: ' + book.CaptionWithoutTitle + ' was touched. ' + self.ToString() + System.Environment.NewLine + strTemp
return strReport
def ToString(self):
if dmGlobals.TraceFunctionMessages: print 'Method dmRuleset:ToString()'
strReturn = 'Ruleset: ' + self.Name + ' ' + self.HumanizeRules()
return strReturn
def HumanizeRules(self):
if dmGlobals.TraceFunctionMessages: print 'Method: dmRuleset:HumanizeRules()'
strReturn = '('
ruleCount = 0
while ruleCount < len(self.Rules):
strReturn = strReturn + self.Rules[ruleCount].ToString()
ruleCount = ruleCount + 1
if ruleCount < len(self.Rules): strReturn = strReturn + ' ' + self.RulesetMode + ' '
strReturn = strReturn + ' => '
actionCount = 0
while actionCount < len(self.Actions):
strReturn = strReturn + self.Actions[actionCount].ToString()
actionCount = actionCount + 1
strReturn = strReturn + ')'
return strReturn
def ToXML(self, elementName):
if dmGlobals.TraceFunctionMessages: print 'Method: dmRuleset:ToXML(stringElementName)'
baseElement = dmNode.ToXML(self, elementName)
baseElement.Attribute['rulesetmode'] = self.RulesetMode
for rule in self.Rules:
baseElement.append(rule.XMLSerialize('rule'))
for action in self.Actions:
baseElement.append(action.XMLSerialize('action'))
pass
def FromXML(self, element):
if dmGlobals.TraceFunctionMessages: print 'Method: dmRuleset:FromXML(xmlElement)'
dmNode.FromXML(self, element)
self.RulesetMode = element.Attribute(XName.Get('rulesetmode')).Value
for rule in element.Elements(XName.Get('rule')):
self.Rules.append(dmRule(self, rule))
for action in element.Elements(XName.Get('action')):
self.Actions.append(dmAction(self, action))
pass
class dmParameters(dmNode):
def getField(self):
return self._Field
def setField(self, strCompleteField):
self.ParseField(strCompleteField)
Field = property(getField, setField)
def getModifier(self):
return self._Modifier
def setModifier(self, strModifier):
self._Modifier = strModifier
Modifier = property(getModifier, setModifier)
def getValue(self):
return self._Value
def setValue(self, strValue):
self._Value = strValue
Value = property(getValue, setValue)
@property
def IsCustomField(self):
return self.Field in dmGlobals.READONLYKEYS or not self.Field in dmGlobals.ALLOWEDVALS
@property
def IsValid(self):
if dmGlobals.TraceFunctionMessages: print 'Property: dmParameters:IsValid'
bReturn = True
#validation for Actions
if isinstance(self, dmAction):
if (not self.Field in dmGlobals.ALLOWEDVALS):
bReturn = False
if not self.Modifier in dmGlobals.ValidValModifiers(self.Field):
bReturn = False
#validation for Rules
elif isinstance(self, dmRule):
if (not self.Field in dmGlobals.ALLOWEDVALS):
bReturn = False
if not self.Modifier in dmGlobals.ValidValModifiers(self.Field):
bReturn = False
#TODO: Determine if the value is valid
if not ValueValid():
bReturn = false
return bReturn
"""base object for dmRule & dmAction instances"""
def __init__(self, dmnparent, strParameters):
"""initializes a dmParameter instance"""
dmNode.__init__(self, dmnparent, strParameters) #calls the base dmNode initializer to initialize further fields
self.Field = '' #initializes the field
self.Modifier = '' #initializes the modifier value
self.Value = '' #initializes the value value
if strParameters != None:
if isinstance(strParameters, XElement):
self.FromXML(strParameters)
else:
self.ParseParameters(strParameters)
pass
def ValueValid(self):
if dmGlobals.TraceFunctionMessages: print 'Method: dmParameters:ValueValid()'
bReturn = True
if self.Field in dmGlobals.FIELDSNUMERIC:
#check that string can be converted to this type
try:
dmGlobals.StringToFloat(self.Value)
except:
bReturn = False
if self.Field in dmGlobals.FIELDSDATETIME:
#check that string can be converted to this type
try:
dmGlobals.StringToDate(self.Value)
except:
bReturn = False
if self.Field in dmGlobals.FIELDSLANGUAGEISO:
#TODO: ReadLanguages and ISO abbreviations
#check that string can be converted to this type
try:
pass
except:
pass
if self.Field in dmGlobals.FIELDSBOOL:
#check that string can be converted to this type
try:
dmGlobals.StringToBool(self.Value)
except:
bReturn = False
if self.Field in dmGlobals.FIELDSMANGAYESNO:
#check that string can be converted to this type
try:
dmGlobals.StringToMangaYesNo(self.Value)
except:
bReturn = False
if self.Field in dmGlobals.FIELDSYESNO:
#check that string can be converted to this type
try:
dmGlobals.StringToYesNo(self.Value)
except:
bReturn = False
if self.Field in dmGlobals.FIELDSSTRING or self.Field in dmGlobals.FIELD or self.Field in dmGlobals.FIELDSCUSTOM:
if not self.Field in dmGlobals.FIELDSMULTILINE:
#checks for carriage return info in string values that do not support new lines
if '{newline}' in self.Value:
bReturn = False
return bReturn;
def ParseParameters(self, strParameters):
"""Parses the string containing info for the parameters"""
if dmGlobals.TraceFunctionMessages: print 'Method: dmParameters:ParseParameters(objParameters)'
if isinstance(strParameters, str):
item = strParameters.strip() #strip whitespace from front of string
item = item.lstrip('<') #remove all instances '<' from front of string
item = item.rstrip('>') #remove all instances '>' from back of string
tmpParameters = item.split('.',1) #results in [field, modifier&value]
self.ParseField(tmpParameters[0]) #sets complete field from field value in created list
modfierAndValue = tmpParameters[1].split(':',1) #results in [modifier, value]
self.Modifier = modfierAndValue[0] #set the modifier
if len(modfierAndValue) > 1: #if a value is present
self.Value = modfierAndValue[1] #set the value accordingly
else:
self.Value = '' #otherwise set Value to empty string for safety purposes
elif isinstance(strParameters, XElement):
self.FromXML(strParameters)
else:
print 'could not parse Parameter Info' + strParameter
pass
def FieldConvert(self, strValue, strField=None):
if dmGlobals.TraceFunctionMessages: print 'Method: dmParameters:FieldConvert(stringValue, stringFieldName)'
FieldValue = self.Field
if strField != None:
FieldValue = strField
theVal = strValue
try:
if FieldValue in dmGlobals.ALLOWEDVALS:
if FieldValue in dmGlobals.FIELDSLIST and not dmGlobals.IsList(strValue):
theVal = strValue.Split(Array[str](dmGlobals.CRLISTDELIMITER), StringSplitOptions.RemoveEmptyEntries)
elif FieldValue in dmGlobals.FIELDSBOOL and not dmGlobals.IsBool(strValue):
theVal = dmGlobals.StringToBool(strValue)
elif FieldValue in dmGlobals.FIELDSDATETIME and not dmGlobals.IsDateTime(strValue):
theVal = dmGlobals.StringToDate(strValue)
elif FieldValue in dmGlobals.FIELDSNUMERIC and not dmGlobals.IsFloat(strValue):
theVal = dmGlobals.StringToFloat(strValue)
elif FieldValue in dmGlobals.FIELDSMANGAYESNO and not dmGlobals.IsMangaYesNo(strValue):
theVal = dmGlobals.StringToMangaYesNo(strValue)
elif FieldValue in dmGlobals.FIELDSYESNO and not dmGlobals.IsYesNo(strValue):
theVal = dmGlobals.StringToYesNo(strValue)
elif FieldValue in dmGlobals.FIELDSPSUEDONUMERIC and not isinstance(strValue,str):
try:
theVal = strValue.ToString()
except:
pass
#otherwise just return the value
except Exception as ex:
pass
return theVal
def GetFieldValue(self, book, strFieldName=None):
if dmGlobals.TraceFunctionMessages: print 'Method: dmParameters:GetFieldValue(book, strFieldName)'
objReturn = None
FieldValue = self.Field
if strFieldName != None:
FieldValue = strFieldName
if dmGlobals.TraceGeneralMessages: print 'Retrieving value for ' + FieldValue + ' field in comic: ' + book.CaptionWithoutTitle #debug Info
if FieldValue in dmGlobals.FIELDSLIST:
objReturn = self.GetList(book, FieldValue)
elif not FieldValue in dmGlobals.ALLOWEDVALS and not FieldValue in dmGlobals.ALLOWEDKEYS:
objReturn = self.GetCustomField(book, FieldValue)
else:
objReturn = getattr(book, FieldValue)
if dmGlobals.TraceGeneralMessages:
print dmGlobals.ToString(objReturn)
print
return objReturn
def GetList(self, book, strFieldName):
if dmGlobals.TraceFunctionMessages: print 'Method: dmParameters:GetList(book, strFieldName)'
strList = getattr(book, strFieldName)
if strList == None or strList == '':
strList = []
else:
strList = strList.split(dmGlobals.CRLISTDELIMITER)
return strList
def GetCustomField(self, book, strFieldName):
print 'Method: dmParameters:GetCustomField(book, strCustomFieldName)'
strTemp = book.GetCustomValue(strFieldName)
if strTemp == None:
strTemp = ''
return strTemp
def ParseField(self, strCompleteField=''):
"""Sets Field & CustomField values properly"""
if dmGlobals.TraceFunctionMessages: print 'Method: dmParameters:ParseField()'
if strCompleteField.startswith('Custom'): # if CustomField begins with 'Custom'
tmpRegex = Regex("Custom\((.*?)\)")
self._Field = tmpRegex.Match(strCompleteField).Groups[1].Value #set the Field Value
else: #otherwise
self._Field = strCompleteField #Field value == CompleteField value
pass
def ToXML(self, elementName):
if dmGlobals.TraceFunctionMessages: print 'Method: dmParameters:ToXML(stringElementName)'
baseElement = XElement(elementName)
baseElement.Add(XAttribute(XName.Get('field'), self.Field))
baseElement.Add((XName.Get('modifier'), self.Modifier))
baseElement.Add(XAttribute(XName.Get('value'), self.Value))
return baseElement
def FromXML(self, element):
if dmGlobals.TraceFunctionMessages: print 'Method: dmParameters:FromXML(xmlElement)'
self.Field = element.Attribute(XName.Get('field')).Value
self.Modifier = element.Attribute(XName.Get('modifier')).Value
self.Value = element.Attribute(XName.Get('value')).Value
def ReplaceReferenceStrings(self, strValue, book):
"""Replaces references to other fields and newline and tab references"""
if dmGlobals.TraceFunctionMessages: print 'dmAction:ReplaceReferenceStrings(self, strValue, book)'
strNewValue = strValue
strNewValue = strNewValue.replace('{newline}', System.Environment.NewLine)
strNewValue = strNewValue.replace('{tab}', ' ')
#find field (including custom) references and replace
for x in Regex.Matches(strNewValue, "\\{([^}]+?)}"):
strNewValue = strNewValue.replace(x.Groups[0].Value, self.GetFieldValue(book, x.Groups[1].Value))
return strNewValue
def ToString(self):
if dmGlobals.TraceFunctionMessages: print 'Method: dmParameters:ToString()'
strReturn = self.Field + ' ' + self.Modifier.upper() + ' \'' + self.Value + '\''
return strReturn
class dmRule(dmParameters):
"""defines a restriction on whether or not defined actions should be applied"""
def __init__(self, dmnparent, strParameters):
"""initializes a dmRule instance"""
if dmGlobals.TraceFunctionMessages: print 'dmRule constructor: dmRule(dmNodeParent, objParameters)'
dmParameters.__init__(self, dmnparent, strParameters) #call initialization done in the dmParameters base instance
pass
def Match(self, book):
"""Determines if the rule matches the book file (returns True or False)"""
if dmGlobals.TraceFunctionMessages: print 'Method: dmRule:Match(book)'
return getattr(self, self.Modifier)(book) #sends the book to the designated (by self.Modifier) function to determine if the rule matches
def Is(self, book):
if dmGlobals.TraceFunctionMessages: print 'Method: dmRule:Is(book)'
getValue = self.GetFieldValue(book, self.Field) #get Value from book
compareValue = self.FieldConvert(self.ReplaceReferenceStrings(self.Value, book) ,self.Field) #value to compare
if self.Field in dmGlobals.FIELDSLIST: #deal with list items as individual items
if len(compareValue) == len(getValue): #only continue if lists are same legnth
count = 0
for item in compareValue: #iterate through compare list items
for val in getValue: #iterate through book list items
if val.lower() == item.lower(): #compare lowercase list items from book (val) to compare list items (item)
count = count + 1 #if match increment count
if count == len(getValue): #if count ends up equal between book list items and compare list items
return True #set true
else:
if isinstance(getValue, str):
if getValue.lower() == compareValue.lower():
return True
else:
if getValue == compareValue: #if values match
return True #set true
return False #if everything else fails set false
def Not(self, book):
if dmGlobals.TraceFunctionMessages: print 'Method: dmRule:Not(book)'
return not self.Is(book) #return inverse of 'Is(book)'
def IsAnyOf(self, book):
"""Available for string languageISO, psuedonumeric, and numeric"""
if dmGlobals.TraceFunctionMessages: print 'Method: dmRule:IsAnyOf(book)'
getValue = self.GetFieldValue(book, self.Field) #get Value from book
compareValue = self.ReplaceReferenceStrings(self.Value, book).split(dmGlobals.DMLISTDELIMITER) #value to compare as list
for word in compareValue:
if isinstance(getValue, str): #if dealing with string
if getValue.lower() == word.lower(): #compare lowercase
return True
if getValue == self.FieldConvert(word, self.Field):
return True
return False
def NotIsAnyOf(self, book):
if dmGlobals.TraceFunctionMessages: print 'Method: dmRule:NotIsAny(book)'
return not self.IsAnyOf(book)
def Contains(self, book):
"""Only applicable with string and list"""
if dmGlobals.TraceFunctionMessages: print 'Method: dmRule:Contains(book)'
getValue = self.GetFieldValue(book, self.Field) #get Value from book
compareValue = self.ReplaceReferenceStrings(self.Value, book) #value to compare
if self.Field in dmGlobals.FIELDSLIST: #search as string list
for check in getValue:
if check.lower().Contains(compareValue.lower()):
return True
else: #search as string
if getValue.lower().Contains(compareValue.lower()):
return True
return False
def NotContains(self, book):
"""Only applicable with string and list"""
if dmGlobals.TraceFunctionMessages: print 'Method: dmRule:NotContains(book)'
return not self.Contains(book)
def ContainsAnyOf(self, book):
"""Only applicable with string and list"""
if dmGlobals.TraceFunctionMessages: print 'Method: dmRule:ContainsAnyOf(book)'
getValue = self.GetFieldValue(book, self.Field) #get Value from book
compareValue = self.ReplaceReferenceStrings(self.Value, book).split(dmGlobals.DMLISTDELIMITER) #value to compare
for compareItem in compareValue:
if self.Field in dmGlobals.FIELDSLIST: #compare list against list
for getItem in getValue: #compare list items as lowercase
if getItem.lower().Contains(compareItem.lower()):
return True #return true at first instance of match
else: #compare list against string
if getValue.lower().Contains(compareItem.lower()): #compare string item against list item
return True #return true at first instance of match
return False #all else failing return false
def NotContainsAnyOf(self, book):
"""Only applicable with string and list"""
if dmGlobals.TraceFunctionMessages: print 'Method: dmRule:NotContainsAnyOf(book)'
return not self.ContainsAnyOf(book)
def ListContains(self, book):
"""Only applicable with string and list"""
if dmGlobals.TraceFunctionMessages: print 'Method: dmRule:Contains(book)'
for check in getValue:
if check.lower() == compareValue.lower():
return True
def NotListContains(self, book):
return not self.ListContains(book)
def ListContainsAnyOf(self, book):
"""Only applicable with string and list"""
if dmGlobals.TraceFunctionMessages: print 'Method: dmRule:ContainsAnyOf(book)'
getValue = self.GetFieldValue(book, self.Field) #get Value from book
compareValue = self.ReplaceReferenceStrings(self.Value, book).split(dmGlobals.DMLISTDELIMITER) #value to compare
for compareItem in compareValue:
if self.Field in dmGlobals.FIELDSLIST: #compare list against list
for getItem in getValue: #compare list items as lowercase
if getItem.lower().Contains(compareItem.lower()):
return True #return true at first instance of match
else: #compare list against string
if getValue.lower().Contains(compareItem.lower()): #compare string item against list item
return True #return true at first instance of match
def NotListContainsAnyOf(self, book):
return not self.ListContainsAnyOf(book)
def ListContainsAllOf(self, book):
pass