-
Notifications
You must be signed in to change notification settings - Fork 22
/
event_lib.py
6577 lines (5670 loc) · 155 KB
/
event_lib.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
#
# Copyright (C) Saeed Rasooli <saeed.gnu@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation; either version 3 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/agpl.txt>.
from scal3 import logger
log = logger.get()
from typing import TYPE_CHECKING
if TYPE_CHECKING:
import io
from collections.abc import Callable, Iterator
from datetime import datetime
from typing import Any
import json
import os
import os.path
from collections import OrderedDict
from contextlib import suppress
from os.path import isabs, join, split, splitext
from time import localtime
from time import time as now
from typing import NamedTuple
from cachetools import LRUCache
import mytz
from scal3 import core, ics, locale_man
from scal3.cal_types import (
GREGORIAN,
calTypes,
convert,
getSysDate,
jd_to,
to_jd,
)
from scal3.core import (
getAbsWeekNumberFromJd,
jd_to_primary,
log,
)
from scal3.date_utils import checkDate, dateDecode, dateEncode, jwday
from scal3.interval_utils import (
intersectionOfTwoIntervalList,
simplifyNumList,
)
from scal3.json_utils import jsonToData
from scal3.locale_man import getMonthName, textNumEncode
from scal3.locale_man import tr as _
from scal3.path import confDir, pixDir, svgDir
# from scal3.interval_utils import
from scal3.s_object import (
BsonHistObj,
FileSystem,
JsonSObj,
SObj,
iterObjectFiles,
loadBsonObject,
makeOrderedData,
objectDirName,
updateBasicDataFromBson,
)
from scal3.time_utils import (
HMS,
durationDecode,
durationEncode,
getEpochFromJd,
getEpochFromJhms,
getFloatJdFromEpoch,
getJdFromEpoch,
getJdListFromEpochRange,
getJhmsFromEpoch,
getSecondsFromHms,
hmDecode,
hmEncode,
jsonTimeFromEpoch,
roundEpochToDay,
simpleTimeEncode,
timeDecode,
timeEncode,
timeToFloatHour,
)
from scal3.utils import (
findNearestIndex,
iceil,
ifloor,
numRangesEncode,
s_join,
toStr,
)
# --------------------------
(
IMPORT_MODE_APPEND,
IMPORT_MODE_SKIP_MODIFIED,
IMPORT_MODE_OVERRIDE_MODIFIED,
) = range(3)
# --------------------------
dayLen = 24 * 3600
icsMinStartYear = 1970
# icsMaxEndYear = 2050
eventsDir = join("event", "events")
groupsDir = join("event", "groups")
accountsDir = join("event", "accounts")
hms_zero = HMS()
hms_24 = HMS(24)
# --------------------------
lockPath = join(confDir, "event", "lock.json")
allReadOnly = False
# ---------------------------------------------------
def init(fs: FileSystem) -> None:
global allReadOnly, info, lastIds
fs.makeDir(objectDirName)
fs.makeDir(eventsDir)
fs.makeDir(groupsDir)
fs.makeDir(accountsDir)
from scal3.lockfile import checkAndSaveJsonLockFile
allReadOnly = checkAndSaveJsonLockFile(lockPath)
if allReadOnly:
log.info(f"Event lock file {lockPath} exists, EVENT DATA IS READ-ONLY")
info = InfoWrapper.load(fs)
lastIds = LastIdsWrapper.load(fs)
lastIds.scan()
class JsonEventObj(JsonSObj):
def save(self) -> None:
if allReadOnly:
log.info(f"events are read-only, ignored file {self.file}")
return
JsonSObj.save(self)
class Smallest:
def __eq__(self, other: "Any") -> bool:
if isinstance(other, Smallest):
return True
return False
def __lt__(self, other: "Any") -> bool:
if isinstance(other, Smallest):
return False
return True
def __gt__(self, other: "Any") -> bool:
return False
def __hash__(self):
return hash(Smallest)
smallest = Smallest()
class BsonHistEventObj(BsonHistObj):
def set_uuid(self) -> None:
from uuid import uuid4
self.uuid = uuid4().hex
def save(self, *args) -> None:
if allReadOnly:
log.info(f"events are read-only, ignored file {self.file}")
return
if hasattr(self, "uuid") and self.uuid is None:
self.set_uuid()
return BsonHistObj.save(self, *args)
class InfoWrapper(JsonEventObj):
file = join("event", "info.json")
skipLoadNoFile = True
params = (
"version",
"last_run",
)
paramsOrder = (
"version",
"last_run",
)
def __init__(self) -> None:
self.version = ""
self.last_run = 0
def update(self) -> None:
self.version = core.VERSION
self.last_run = int(now())
def updateAndSave(self) -> None:
self.update()
self.save()
info = None # type: InfoWrapper
# ---------------------------------------------------
class LastIdsWrapper(JsonEventObj):
skipLoadNoFile = True
file = join("event", "last_ids.json")
params = (
"event",
"group",
"account",
)
paramsOrder = (
"event",
"group",
"account",
)
def __init__(self) -> None:
self.event = 0
self.group = 0
self.account = 0
def __str__(self) -> str:
return (
"LastIds("
f"event={self.event}, "
f"group={self.group}, "
f"account={self.account}"
")"
)
def scanDir(self, dpath: str) -> int:
lastId = 0
for fname in self.fs.listdir(dpath):
idStr, ext = splitext(fname)
if ext != ".json":
continue
try:
_id = int(idStr)
except ValueError:
log.error(f"invalid file name: {dpath}")
continue
if _id > lastId:
lastId = _id
return lastId
def scan(self) -> None:
t0 = now()
self.event = self.scanDir("event/events")
self.group = self.scanDir("event/groups")
self.account = self.scanDir("event/accounts")
self.save()
log.info(f"Scanning last_ids took {now() - t0:.3f} seconds, {self}")
lastIds = None # type: LastIdsWrapper
# ---------------------------------------------------------------------------
def removeUnusedObjects(fs: FileSystem):
global allReadOnly
if allReadOnly:
raise RuntimeError("removeUnusedObjects: EVENTS ARE READ-ONLY")
def do_removeUnusedObjects():
hashSet = set()
for cls in (Account, EventTrash, EventGroup, Event):
for fpath in cls.iterFiles(fs):
with fs.open(fpath) as fp:
jsonStr = fp.read()
data = jsonToData(jsonStr)
history = data.get("history")
if not history:
log.error(f"No history in file: {fpath}")
continue
for _revTime, revHash in history:
hashSet.add(revHash)
log.info(f"Found {len(hashSet)} used objects")
removedCount = 0
for _hash, fpath in iterObjectFiles(fs):
if _hash not in hashSet:
log.debug(f"Removing file: {fpath}")
removedCount += 1
fs.removeFile(fpath)
log.info(f"Removed {removedCount} objects")
allReadOnly = True
try:
tm0 = now()
do_removeUnusedObjects()
log.info(f"removeUnusedObjects: took {now() - tm0}")
finally:
allReadOnly = False
# ---------------------------------------------------------------------------
class ClassGroup(list):
def __init__(self, tname: str) -> None:
list.__init__(self)
self.tname = tname
self.names = []
self.byName = {}
self.byDesc = {}
self.main = None
def register(self, cls: "type[ClassGroup]") -> "type[ClassGroup]":
assert cls.name
cls.tname = self.tname
self.append(cls)
self.names.append(cls.name)
self.byName[cls.name] = cls
self.byDesc[cls.desc] = cls
if hasattr(cls, "nameAlias"):
self.byName[cls.nameAlias] = cls
return cls
def setMain(self, cls: "type[ClassGroup]") -> "type[ClassGroup]":
self.main = cls
return cls
class classes:
rule = ClassGroup("rule")
notifier = ClassGroup("notifier")
event = ClassGroup("event")
group = ClassGroup("group")
account = ClassGroup("account")
defaultGroupTypeIndex = 0 # FIXME
__plugin_api_get__ = [
"classes",
"defaultGroupTypeIndex",
"EventRule",
"EventNotifier",
"Event",
"EventGroup",
"Account",
]
# ---------------------------------------------------------------------------
# FIXME move this o Event class
def getEventUID(event: "Event") -> str:
import socket
event_st = core.compressLongInt(hash(str(event.getData())))
time_st = core.getCompactTime()
host = socket.gethostname()
return event_st + "_" + time_st + "@" + host
class BadEventFile(Exception): # FIXME
pass
class OccurSet(SObj):
def __init__(self) -> None:
self.event = None
def intersection(self) -> None:
raise NotImplementedError
def getDaysJdList(self) -> list[int]: # noqa: PLR6301
return [] # make generator FIXME
def getTimeRangeList(self) -> list[tuple[int, int]]: # noqa: PLR6301
return [] # make generator FIXME
def getFloatJdRangeList(self) -> list[tuple[float, float]]:
return [
(getFloatJdFromEpoch(ep0), getFloatJdFromEpoch(ep1))
for ep0, ep1 in self.getTimeRangeList()
]
def getStartJd(self) -> int:
raise NotImplementedError
def getEndJd(self) -> int:
raise NotImplementedError
# def __iter__(self) -> Iterator:
# return iter(self.getTimeRangeList())
class JdOccurSet(OccurSet):
name = "jdSet"
def __init__(self, jdSet: "set[int] | None" = None) -> None:
OccurSet.__init__(self)
if not jdSet:
jdSet = []
self.jdSet = set(jdSet)
def __repr__(self) -> str:
return f"JdOccurSet({list(self.jdSet)})"
def __bool__(self) -> bool:
return bool(self.jdSet)
def __len__(self) -> int:
return len(self.jdSet)
def getStartJd(self) -> int:
if not self.jdSet:
return
return min(self.jdSet)
def getEndJd(self) -> int:
if not self.jdSet:
return
return max(self.jdSet) + 1
def intersection(self, occur: OccurSet) -> OccurSet:
if isinstance(occur, JdOccurSet):
return JdOccurSet(
self.jdSet.intersection(occur.jdSet),
)
if isinstance(occur, IntervalOccurSet):
return IntervalOccurSet(
intersectionOfTwoIntervalList(
self.getTimeRangeList(),
occur.getTimeRangeList(),
),
)
if isinstance(occur, TimeListOccurSet):
return occur.intersection(self)
raise TypeError
def getDaysJdList(self) -> list[int]:
return sorted(self.jdSet)
def getTimeRangeList(self) -> list[tuple[int, int]]:
return [
(
getEpochFromJd(jd),
getEpochFromJd(jd + 1),
)
for jd in self.jdSet
]
def calcJdRanges(self) -> list[tuple[int, int]]:
jdList = sorted(self.jdSet) # jdList is sorted
if not jdList:
return []
startJd = jdList[0]
endJd = startJd + 1
jdRanges = []
for jd in jdList[1:]:
if jd == endJd:
endJd += 1
else:
jdRanges.append((startJd, endJd))
startJd = jd
endJd = startJd + 1
jdRanges.append((startJd, endJd))
return jdRanges
class IntervalOccurSet(OccurSet):
name = "timeRange"
def __init__(self, rangeList: "list[tuple[int, int]] | None" = None) -> str:
OccurSet.__init__(self)
if not rangeList:
rangeList = []
self.rangeList = rangeList
def __repr__(self) -> str:
return f"IntervalOccurSet({self.rangeList!r})"
def __bool__(self) -> bool:
return bool(self.rangeList)
def __len__(self) -> int:
return len(self.rangeList)
# def __getitem__(i):
# self.rangeList.__getitem__(i) # FIXME
def getStartJd(self) -> int:
if not self.rangeList:
return
return getJdFromEpoch(min(r[0] for r in self.rangeList))
def getEndJd(self) -> int:
if not self.rangeList:
return
return getJdFromEpoch(max(r[1] for r in self.rangeList))
def intersection(self, occur: OccurSet) -> OccurSet:
if isinstance(occur, JdOccurSet | IntervalOccurSet):
return IntervalOccurSet(
intersectionOfTwoIntervalList(
self.getTimeRangeList(),
occur.getTimeRangeList(),
),
)
if isinstance(occur, TimeListOccurSet):
return occur.intersection(self)
raise TypeError(
f"bad type {occur.__class__.__name__} ({occur!r})",
)
def getDaysJdList(self) -> list[int]:
return sorted(
{
jd
for startEpoch, endEpoch in self.rangeList
for jd in getJdListFromEpochRange(startEpoch, endEpoch)
},
)
def getTimeRangeList(self) -> list[tuple[int, int]]:
return self.rangeList
@staticmethod
def newFromStartEnd(startEpoch: int, endEpoch: int) -> OccurSet:
if startEpoch > endEpoch:
return IntervalOccurSet([])
return IntervalOccurSet([(startEpoch, endEpoch)])
class TimeListOccurSet(OccurSet):
name = "repeativeTime"
def __init__(self, *args) -> None:
OccurSet.__init__(self)
if not args:
self.startEpoch = 0
self.endEpoch = 0
self.stepSeconds = -1
self.epochList = set()
elif len(args) == 1:
self.epochList = set(args[0])
elif len(args) == 3:
self.setRange(*args)
else:
raise ValueError
def __repr__(self) -> str:
return r"TimeListOccurSet({self.epochList!r})"
# def __bool__(self) -> bool:
# return self.startEpoch == self.endEpoch
def __bool__(self) -> bool:
return bool(self.epochList)
def getStartJd(self) -> int:
if not self.epochList:
return
return getJdFromEpoch(min(self.epochList))
def getEndJd(self) -> int:
if not self.epochList:
return
return getJdFromEpoch(max(self.epochList) + 1)
def setRange(self, startEpoch: int, endEpoch: int, stepSeconds: int) -> None:
try:
from numpy.core.multiarray import arange
except ImportError:
from scal3.utils import arange
# ------
self.startEpoch = startEpoch
self.endEpoch = endEpoch
self.stepSeconds = stepSeconds
self.epochList = set(arange(startEpoch, endEpoch, stepSeconds))
def intersection(self, occur: OccurSet) -> OccurSet:
if isinstance(occur, JdOccurSet | IntervalOccurSet):
epochBetween = []
for epoch in self.epochList:
for startEpoch, endEpoch in occur.getTimeRangeList():
if startEpoch <= epoch < endEpoch:
epochBetween.append(epoch)
break
return TimeListOccurSet(epochBetween)
if isinstance(occur, TimeListOccurSet):
return TimeListOccurSet(
self.epochList.intersection(occur.epochList),
)
raise TypeError
# FIXME: improve performance
def getDaysJdList(self) -> list[int]:
return sorted({getJdFromEpoch(epoch) for epoch in self.epochList})
def getTimeRangeList(self) -> list[tuple[int, int]]:
return [(epoch, epoch) for epoch in self.epochList] # or end=None, FIXME
# Should not be registered, or instantiate directly
@classes.rule.setMain
class EventRule(SObj):
name = ""
desc = ""
provide = ()
need = ()
conflict = ()
sgroup = -1
expand = False
params = ()
def getServerString(self) -> str:
raise NotImplementedError
def __bool__(self) -> bool:
return True
def __init__(self, parent: "Event"):
"""Parent can be an event for now (maybe later a group too)."""
self.parent = parent
def copy(self) -> "EventRule":
newObj = self.__class__(self.parent)
newObj.fs = getattr(self, "fs", None)
newObj.copyFrom(self)
return newObj
def getCalType(self) -> int:
return self.parent.calType
def changeCalType(self, calType: int) -> bool: # noqa: ARG002, PLR6301
return True
def calcOccurrence(
self,
startJd: int,
endJd: int,
event: "Event",
) -> OccurSet:
raise NotImplementedError
def getInfo(self) -> str:
return self.desc + f": {self}"
def getEpochFromJd(self, jd: int) -> int:
return getEpochFromJd(
jd,
tz=self.parent.getTimeZoneObj(),
)
class AllDayEventRule(EventRule):
def jdMatches(self, jd: int) -> bool: # noqa: ARG002, PLR6301
return True
def calcOccurrence(
self,
startJd: int,
endJd: int,
event: "Event", # noqa: ARG002
) -> OccurSet:
# improve performance FIXME
jds = set()
for jd in range(startJd, endJd):
if self.jdMatches(jd):
jds.add(jd) # benchmark FIXME
return JdOccurSet(jds)
# Should not be registered, or instantiate directly
class MultiValueAllDayEventRule(AllDayEventRule):
conflict = ("date",)
params = ("values",)
expand = True # FIXME
def __init__(self, parent: "Event") -> None:
EventRule.__init__(self, parent)
self.values = []
def getData(self) -> "list[Any]":
return self.values
def setData(self, data: "Any"):
if not isinstance(data, tuple | list):
data = [data]
self.values = data
def __str__(self) -> str:
return textNumEncode(numRangesEncode(self.values, ", "))
def hasValue(self, value: "Any") -> bool:
for item in self.values:
if isinstance(item, tuple | list):
if item[0] <= value <= item[1]:
return True
elif item == value:
return True
return False
def getValuesPlain(self) -> "list[int | tuple[int, int]]":
ls = []
for item in self.values:
if isinstance(item, tuple | list):
ls += list(range(item[0], item[1] + 1))
else:
ls.append(item)
return ls
def setValuesPlain(self, values: "list[int | tuple[int, int]]") -> None:
self.values = simplifyNumList(values)
def changeCalType(self, _calType: int) -> bool: # noqa: PLR6301
return False
@classes.rule.register
class YearEventRule(MultiValueAllDayEventRule):
name = "year"
desc = _("Year")
params = ("values",)
def getServerString(self) -> str:
return numRangesEncode(self.values, " ") # no comma
def __init__(self, parent: "Event") -> None:
MultiValueAllDayEventRule.__init__(self, parent)
self.values = [getSysDate(self.getCalType())[0]]
def jdMatches(self, jd: int) -> bool:
return self.hasValue(jd_to(jd, self.getCalType())[0])
def newCalTypeValues(
self,
newCalType: int,
) -> "list[int | tuple[int, int]]":
def yearConv(year):
return convert(year, 7, 1, curCalType, newCalType)[0]
curCalType = self.getCalType()
values2 = []
for item in self.values:
if isinstance(item, tuple | list):
values2.append(
(
yearConv(item[0]),
yearConv(item[1]),
),
)
else:
values2.append(yearConv(item))
return values2
def changeCalType(self, calType: int) -> bool:
self.values = self.newCalTypeValues(calType)
return True
@classes.rule.register
class MonthEventRule(MultiValueAllDayEventRule):
name = "month"
desc = _("Month")
conflict = (
"date",
"weekMonth",
)
params = ("values",)
def getServerString(self) -> str:
return numRangesEncode(self.values, " ") # no comma
def __init__(self, parent: "Event") -> None:
MultiValueAllDayEventRule.__init__(self, parent)
self.values = [1]
def jdMatches(self, jd: int) -> bool:
return self.hasValue(jd_to(jd, self.getCalType())[1])
@classes.rule.register
class DayOfMonthEventRule(MultiValueAllDayEventRule):
name = "day"
desc = _("Day of Month")
params = ("values",)
def getServerString(self) -> str:
return numRangesEncode(self.values, " ") # no comma
def __init__(self, parent: "Event") -> None:
MultiValueAllDayEventRule.__init__(self, parent)
self.values = [1]
def jdMatches(self, jd: int) -> bool:
return self.hasValue(jd_to(jd, self.getCalType())[2])
@classes.rule.register
class WeekNumberModeEventRule(EventRule):
name = "weekNumMode"
desc = _("Week Number")
need = ("start",) # FIXME
conflict = (
"date",
"weekMonth",
)
params = ("weekNumMode",)
EVERY_WEEK, ODD_WEEKS, EVEN_WEEKS = list(range(3))
# remove EVERY_WEEK? FIXME
weekNumModeNames = ("any", "odd", "even")
def getServerString(self) -> str:
return self.weekNumMode
def __init__(self, parent: "Event") -> None:
EventRule.__init__(self, parent)
self.weekNumMode = self.EVERY_WEEK
def getData(self) -> str:
return self.weekNumModeNames[self.weekNumMode]
def setData(self, wnModeName: str) -> None:
if wnModeName not in self.weekNumModeNames:
raise BadEventFile(
f"bad rule value {wnModeName=}, "
"the value for weekNumMode must be "
f"one of {self.weekNumModeNames!r}",
)
self.weekNumMode = self.weekNumModeNames.index(wnModeName)
def calcOccurrence(
self,
startJd: int,
endJd: int,
event: "Event",
) -> OccurSet:
# improve performance FIXME
startAbsWeekNum = getAbsWeekNumberFromJd(event.getStartJd()) - 1
# 1st week # FIXME
if self.weekNumMode == self.EVERY_WEEK:
return JdOccurSet(
range(startJd, endJd),
)
if self.weekNumMode == self.ODD_WEEKS:
return JdOccurSet(
{
jd
for jd in range(startJd, endJd)
if (getAbsWeekNumberFromJd(jd) - startAbsWeekNum) % 2 == 1
},
)
if self.weekNumMode == self.EVEN_WEEKS:
return JdOccurSet(
{
jd
for jd in range(startJd, endJd)
if (getAbsWeekNumberFromJd(jd) - startAbsWeekNum) % 2 == 0
},
)
return None
def __str__(self) -> str:
return self.weekNumModeNames[self.weekNumMode]
def getInfo(self) -> None:
if self.weekNumMode == self.EVERY_WEEK:
return ""
if self.weekNumMode == self.ODD_WEEKS:
return _("Odd Weeks")
if self.weekNumMode == self.EVEN_WEEKS:
return _("Even Weeks")
return None
@classes.rule.register
class WeekDayEventRule(AllDayEventRule):
name = "weekDay"
desc = _("Day of Week")
conflict = (
"date",
"weekMonth",
)
params = ("weekDayList",)
def getServerString(self) -> str:
return s_join(self.weekDayList)
def __init__(self, parent: "Event") -> None:
EventRule.__init__(self, parent)
self.weekDayList = list(range(7)) # or [] FIXME
def getData(self) -> list[int]:
return self.weekDayList
def setData(self, data: "int | list[int]") -> None:
if isinstance(data, int):
self.weekDayList = [data]
elif isinstance(data, tuple | list):
self.weekDayList = data
else:
raise BadEventFile(
f"bad rule weekDayList={data}, "
"value for weekDayList must be a list of integers"
" (0 for sunday)",
)
def jdMatches(self, jd: int) -> None:
return jwday(jd) in self.weekDayList
def __str__(self) -> str:
if self.weekDayList == list(range(7)):
return ""
return ", ".join([core.weekDayNameEnglish[wd] for wd in self.weekDayList])
def getInfo(self) -> str:
if self.weekDayList == list(range(7)):
return ""
sep = _(",") + " "
sep2 = " " + _("or") + " "
return (
_("Day of Week")
+ ": "
+ sep.join([core.weekDayName[wd] for wd in self.weekDayList[:-1]])
+ sep2
+ core.weekDayName[self.weekDayList[-1]]
)
@classes.rule.register
class WeekMonthEventRule(EventRule):
name = "weekMonth"
desc = _("Week-Month")
conflict = (
"date",
"month",
"ex_month",
"weekNumMode",
"weekday",
"cycleDays",
"cycleWeeks",
"cycleLen",
)
params = (
"month", # 0..12 0 means every month
"wmIndex", # 0..4
"weekDay", # 0..6
)
"""
paramsValidators = {
"month": lambda m: 0 <= m <= 12,
"wmIndex": lambda m: 0 <= m <= 4,
"weekDay": lambda m: 0 <= m <= 6,
}
"""
wmIndexNamesEn = (
"First", # 0
"Second", # 1
"Third", # 2
"Fourth", # 3
"Last", # 4
)
wmIndexNames = (
_("First"), # 0
_("Second"), # 1
_("Third"), # 2
_("Fourth"), # 3
_("Last"), # 4
)