Source

trac-dvbcronrecording-plugin / src / dvbcronrecording / computer.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
import time
import re
import datetime
import logging

from trac.core import Component #, implements
from trac.config import Option, ListOption, FloatOption, BoolOption

try:
    from channels import DvbCronRecordingChannelsPlugin
except:
    DvbCronRecordingChannelsPlugin = None

DEBUG = False
PACKAGE = 'dvbcronrecording'
NAV = 'recordings'
URL = 'recording'

default_adapter = u"0"

def intnull(value, default = None):
    if value is None: return default
    try: return int(value)
    except Exception: return default

class ChainEntry:
    def __init__(self):
        self.entry = None
        self.after = []
        self.message = ""

class RecorderItem:
    """ converting the database entry - which is similar to what
        the user entered in the input form fields - to an object
        with computable data attributes. Note that newtime/endtime
        are given as minutes-since-midnight. """
    def __init__(self):
        self.entry = None # the original entry
        self.weekday = None
        self.onlydate = None
        self.onlyday = None
        self.months = []
        self.newtimeMMM = 0
        self.endtimeMMM = 0
        self.extratimeM = 0
        self.channelname = None
        self.title = ""
        self.message = ""
        self.rank = 0.0
        self.cloned = None
        self.adapter = None
    def clone(self):
        item = RecorderItem()
        item.entry = self.entry
        item.weekday = self.weekday
        item.onlydate = self.onlydate
        item.onlyday = self.onlyday
        item.months = self.months
        item.newtimeMMM = self.newtimeMMM
        item.endtimeMMM = self.endtimeMMM
        item.extratimeM = self.extratimeM
        item.channelname = self.channelname
        item.title = self.title
        item.message = self.message
        item.rank = self.rank 
        item.cloned = self
        item.adapter = self.adapter
        return item
    def __unicode__(self):
        return u"(%s) '%s'" % (unicode(self.months), unicode(self.title))
    
class RecorderGroup:
    def __init__(self):
        self.items = [] # RecordingItem
        self.weekday = None
        self.newtimeMMM = None
        self.endtimeMMM = None
        self.extratimeM = None
        self.adapter = None
    def __unicode__(self):
        return u"["+unicode(",".join([unicode(item) for item in self.items]))+"]"

class RecorderGroupPlan:
    def __init__(self):
        self._groups = []
    def items(self):
        groupcount = 0
        for group in self._groups:
            if not group.items: continue
            for item in group.items:
                item.groupcount = groupcount
                yield item
            groupcount += 1
            yield None # group seperator
    def groups(self):
        for group in self._groups:
            yield group
    def addgroup(self, group):
        self._groups += [ group ]
    def sort(self):
        """ weekday, starttime, adapter """
        groups = sorted(self._groups, key = lambda x: (x.weekday, x.newtimeMMM, x.adapter))
        self._groups = groups

class RecorderFlatPlan:
    def __init__(self):
        self._items = []
    def items(self):
        return self._items
    def additem(self, item):
        self._items += [ item ]
    def deleted_items(self):
        for item in self._items:
            if item.newtimeMMM == item.endtimeMMM:
                yield item

class RecorderTime:
    def __init__(self, orig = None):
        self.item = orig
        self.message = ""
        self.datetimeX = None
        self.datetimeY = None
        self.deleted = False
        self.newtimeMMM = 0
        self.endtimeMMM = 0
        self.extratimeM = 0
        self.adapter = None
        self.adapters = [ default_adapter ]
        self.set(orig)
    def set(self, orig):
        if orig is not None:
            self.newtimeMMM = orig.newtimeMMM
            self.endtimeMMM = orig.endtimeMMM
            self.extratimeM = orig.extratimeM
        return self

months_ahead = 3
    
class DvbCronRecordingPlanComputer(Component):
    """ it is a component but it does not have its own database tables - it 
        just helps to turn the recording list into a proper recording plan. """
        
    algorithm = Option(PACKAGE, "planning-algorithm", "plan3",
                       doc="Choose the planning type plan1,plan2,plan3,plan4")
    rankup_channels = ListOption(PACKAGE, "planning-rankup-channels","3sat,arte",
                       doc="Choose the channels to implicitly rank higher")
    rankup_value = FloatOption(PACKAGE, "planning-rankup-value", 0.3,
                        doc="Amount of rank increment for the rankup-channels") 
    onlydate_rankup = FloatOption(PACKAGE, "planning-onlydate-rankup", 0.5,
                        doc="Amount of rank increment for single date recordings") 
    
    def __init__(self):
        self._adapters = {}
        self._adapterlist = None
        self.logg = logging.getLogger(__name__)
    
    def adapters(self, channelname):
        if channelname in self._adapters:
            return self._adapters[channelname]
        return [ default_adapter ]
    def set_adapters_from_channels_list(self, channelslist):
        for entry in channelslist:
            channelname = entry.channelname
            adapter = entry.adapter
            if channelname not in self._adapters:
                self._adapters[channelname] = []
            if adapter not in self._adapters[channelname]:
                self._adapters[channelname] += [ adapter ]
        self.update_adapterlist()
    def update_adapterlist(self):
        """ for all channels create the union of their available adapters """
        adapterlist = []
        for adapters in self._adapters.values():
            for adapter in adapters:
                if adapter and adapter not in adapterlist:
                    adapterlist += [ adapter ]
        self._adapterlist = adapterlist
    def adapterlist(self):
        """ get the union of available adapters used in configured channels """
        if self._adapterlist is None:
            self.updated_adapterlist()
        adapterlist = self._adapterlist[:]
        if not adapterlist:
            return [ default_adapter ]
        if default_adapter not in adapterlist:
            adapterlist += [ default_adapter ]
        return adapterlist
            
    def channels_list(self):
        if DvbCronRecordingChannelsPlugin is None:
            return [ 0 ]
        channels = DvbCronRecordingChannelsPlugin(self.env)
        return channels.channels_list()
    
    # ======================================================================
    def zero(self, spec):
        if not spec: return 0
        return int(spec)
    
    """ 
        This is doing the actual computations
    """
    def _entries_to_startchain(self, entries):
        weekday1 = None
        endtime1 = None
        extratime1 = None
        start = []
        chain = None
        for entry in entries:
            if entry["status"] == "no": continue
            newtime2 = self.zero(self.minutes(entry["newtime"]))
            endtime2 = self.zero(self.minutes(entry["endtime"]))
            extratime2 = self.zero(self.minutes(entry["extratime"]))
            weekday2 = intnull(entry["weekday"])
            if endtime2 < newtime2: endtime2 += 24*60
            if endtime2 == endtime1: continue
            isafter = False
            if endtime1 is not None:
                if not weekday1 : weekday1 = 0
                if not weekday2 : weekday2 = 0
                daytime1 = weekday1 * 24 * 60
                daytime2 = weekday2 * 24 * 60
                message = " [%s < %s]" % (daytime1+endtime1+extratime1, daytime2+newtime2)
                if daytime1+endtime1+extratime1 >= daytime2+newtime2:
                    isafter = True
            else:
                message = " [FIRST] "
            if chain: chain.message += message
            if isafter:
                chain.after += [ entry ]
            else:
                if chain is not None:
                    start += [ chain ] 
                chain = ChainEntry()
                chain.entry = entry
                chain.after = []
            weekday1 = weekday2
            endtime1 = endtime2
            extratime1 = extratime2
        return start


    def minutes(self, spec):
        """ convert HH:MM spec into minutes (since midnight if not an interval) """
        m = re.match("(\d+):(\d+)", spec)
        if m: return int(m.group(1))*60 + int(m.group(2))
        m = re.match("(\d+)", spec)
        if m: return int(m.group(1))
        return None
    
    def get_allowed_months(self, ahead = months_ahead):
        this_month = time.localtime().tm_mon
        allowed = []
        for add_months in xrange(months_ahead):
            month = this_month + add_months
            if month > 12: month -= 12
            if month > 12: continue
            if month not in allowed:
                allowed += [ month ]
        return allowed
    
    def get_past_days_this_month(self):
        today = time.localtime()
        this_month = today.tm_mon
        this_day = today.tm_mday
        allowed = []
        for day in xrange(1, this_day):
            allowed += [ (day, this_month) ]
        return allowed
    
    """
       check this month and the next 3 months whether there are
       entries with 'onlydate' that would only run once.
    """
    def recordinglist_to_recorderitems(self, entries, ahead = months_ahead):
        allowed_months = self.get_allowed_months(ahead)
        past_days = self.get_past_days_this_month()
        self.logg.debug("allowed_months %s" % (str(allowed_months)))    
        for entry in entries:
            if entry.status == "no": 
                self.logg.debug("status disabled for %s", entry.title) 
                continue
            item = RecorderItem()
            item.channelname = entry.channelname
            item.title = entry.title
            if not item.title:
                self.logg.debug("item had not title") 
                continue            
            if not item.channelname: 
                self.logg.debug("no channel name for '%s", item.title) 
                continue            
            m = re.match("(\d+)[.](\d+)[.]", entry.onlydate)
            if m:
                self.logg.debug("onlydate %s for %s", entry.onlydate, item.title)
                try:
                    onlyday = intnull(m.group(1))
                    onlymonth = intnull(m.group(2))
                    if not onlyday: continue
                    if not onlymonth: continue
                    if onlymonth not in allowed_months:
                        self.logg.debug("onlymonth not in allowed_months '%s'", item.title) 
                        continue
                    if (onlyday, onlymonth) in past_days: 
                        self.logg.debug("(onlyday, onlymonth) in past_days '%s'", item.title) 
                        continue
                    item.onlyday = onlyday
                    item.months = [ onlymonth ]
                    self.logg.debug("onlyday %s onlymonths %s for %s", item.onlyday, item.months, item.title)
                except Exception:
                    self.logg.debug("conversion error %s '%s'", entry.onlydate, item.title)
                item.weekday = intnull(entry.weekday)
            else: 
                item.weekday = intnull(entry.weekday)
                if item.weekday is None:
                    self.logg.debug("item.weekday is None '%s'", item.title) 
                    continue
                if item.weekday >= 7: item.weekday = item.weekday % 7
            item.newtimeMMM = self.zero(self.minutes(entry.newtime))
            item.endtimeMMM = self.zero(self.minutes(entry.endtime))
            item.extratimeM = self.zero(self.minutes(entry.extratime))
            try: item.rank = float(int(entry.priority))
            except: pass
            if item.channelname in self.rankup_channels:
                item.rank += self.rankup_value
            self.logg.debug("originally %s-%s '%s'" % (entry.newtime, entry.endtime, item.title))
            yield item
    def recordinglist_to_recordergroups(self, entries, ahead = months_ahead):
        recorderitems = list(self.recordinglist_to_recorderitems(entries, ahead))
        onlymonths = []
        for item in recorderitems:
            for month in item.months: 
                if month not in onlymonths:
                    onlymonths.append(month)
        self.logg.debug("onlymonths %s", onlymonths)
        regularmonths = [ month for month in xrange(1,13) if month not in onlymonths ]
        self.logg.debug("regularmonths %s", regularmonths)
        localtime = time.localtime()
        this_month = localtime.tm_mon
        this_year = localtime.tm_year
        past_days = self.get_past_days_this_month()
        for month in sorted(onlymonths):
            year = this_year
            if month < this_month: year += 1
            for day in xrange(1,32):
                if (day, month) in past_days: continue
                try:
                    # ValueError if invalid day-of-month
                    date = datetime.date(year, month, day)
                    # no generate the recordings for that day
                    items = self.clone_filtered_for_date(recorderitems, date)
                    for group in self.recordergroups_from_filtered(items):
                        self.logg.debug("onlydate group %s", unicode(group))
                        yield group
                except ValueError:
                    pass # expected
        items = self.clone_filtered_for_regular(recorderitems, regularmonths)
        self.logg.debug("=======================================================")
        items = list(items)
        for item in items:
            self.logg.debug("regular item %s", unicode(item))
        for group in self.recordergroups_from_filtered(items):
            self.logg.debug("regular group %s", unicode(group))
            yield group
    def clone_filtered_for_date(self, recorderitems, date):
        for item in recorderitems:
            if item.onlyday: 
                if item.onlyday != date.day: continue
            elif item.months:
                if date.month not in item.months: continue
            else:
                if item.weekday != date.weekday(): continue
            newitem = item.clone()
            newitem.onlydate = date
            newitem.onlyday = date.day
            newitem.months = [ date.month ]
            newitem.weekday = date.weekday()
            if item.onlyday: 
                newitem.rank += self.onlydate_rankup
            yield newitem
    def clone_filtered_for_regular(self, recorderitems, regularmonths):
        for item in recorderitems:
            if item.onlyday: continue
            if item.months: continue
            newitem = item.clone()
            newitem.months = regularmonths
            yield newitem
    def recordergroups_from_filtered(self, recorderitems):
        """ group items into recordings with overlapping time intervals """    
        group = None
        previous = None
        nextday = 0
        for item in recorderitems:
            newtimeMMM = item.newtimeMMM
            endtimeMMM = item.endtimeMMM
            extratimeM = item.extratimeM 
            if group is None: # first run
                group = RecorderGroup()
                group.weekday = item.weekday
                group.newtimeMMM = newtimeMMM
            elif group.endtimeMMM + group.extratimeM < newtimeMMM + nextday:
                yield group # non-recording interval
                group = RecorderGroup()
                group.weekday = item.weekday
                group.newtimeMMM = newtimeMMM
            else: # overlapping?
                assert previous is not None # because of first run
                previous_ended_weekday = previous.weekday
                if previous.endtimeMMM < previous.newtimeMMM:
                    previous_ended_weekday += 1
                if item.weekday != previous_ended_weekday:
                    yield group # non-recording interval
                    group = RecorderGroup()
                    group.weekday = item.weekday
                    group.newtimeMMM = newtimeMMM
                pass 
            if endtimeMMM < newtimeMMM:
                nextday = 24*60
            group.endtimeMMM = endtimeMMM + nextday 
            group.extratimeM = extratimeM
            group.items += [ item ]
            previous = item
        if group is not None and group.endtimeMMM is not None:
            yield group
    def tuning_split_recordergroup(self, group, channels):
        """ this function is supposed to get a list of adapters and
            the channels that can be tuned on them. The recordings
            of the recordergroup can then be scheduled to different
            transponders and returned. Additionally, each item in the
            returned groups has its endtimeMMM set so that the difference
            of newtime-endtime is the recording time interval. """
        yield self.adjust_recordergroup(group) 
    def adjust_recordergroup(self, group):
        self.logg.debug("adjust group %s", unicode(group))
        nextday = 0
        previous = None
        for item in group.items:
            if previous is None:
                previous = item
                continue
            if item.endtimeMMM < item.newtimeMMM:
                nextday = 24 * 60
            if previous.rank > item.rank:
                item_newtime = item.newtimeMMM
                item.newtimeMMM = previous.endtimeMMM + previous.extratimeM
                if item_newtime != item.newtimeMMM:
                    item.message += " %s >>" % MMMtoHHMM(item_newtime) 
                    item.message += " %s;" % MMMtoHHMM(item.newtimeMMM)
            elif previous.rank < item.rank:
                previous_endtime = previous.endtimeMMM
                previous.endtimeMMM = item.newtimeMMM
                previous.extratimeM = 0
                if previous_endtime != previous.endtimeMMM:
                    previous.message += " %s << " % MMMtoHHMM(previous.endtimeMMM)
                    previous.message += " %s;" % MMMtoHHMM(previous_endtime)
            elif item.newtimeMMM < previous.endtimeMMM + previous.extratimeM:
                item_newtime = item.newtimeMMM
                item.newtimeMMM = previous.endtimeMMM + previous.extratimeM
                if item_newtime != item.newtimeMMM:
                    item.message += " %s ->" % MMMtoHHMM(item_newtime)
                    item.message += " %s;;" % MMMtoHHMM(item.newtimeMMM)
            if item.endtimeMMM + nextday <= item.newtimeMMM:
                item.endtimeMMM = item.newtimeMMM
                item.extratimeM = 0
                item.message += " [DEL]"
            elif previous.endtimeMMM == previous.newtimeMMM:
                previous.message += " [DEL]"
            previous = item
            nextday = 0
        return group
    def make_cronmonths(self, group):
        self.logg.debug("adjust group %s", unicode(group))
        for item in group.items:
            ranges = []
            months = item.months
            if len(months) > 1:
                start = None
                previous = None
                for month in months:
                    if start is None:
                        start = month
                        previous = month
                    elif month == previous + 1:
                        previous = month
                    else:
                        ranges += [ (start,previous) ]
                        start = month
                        previous = month
                ranges += [ (start,previous) ]
            else:
                ranges += [ (months[0],months[0])]
            item.cronmonths = ranges
        return group
    def plan1(self, entries):
        """ main entry point """
        plan = RecorderGroupPlan()
        for group in self.recordinglist_to_recordergroups(entries):
            group = self.adjust_recordergroup(group)
            group = self.make_cronmonths(group)
            plan.addgroup(group)
        return plan
    def recordinglist_to_flat_recorderitems(self, entries, ahead = months_ahead):
        recorderitems = list(self.recordinglist_to_recorderitems(entries, ahead))
        localtime = time.localtime()
        this_month = localtime.tm_mon
        this_year = localtime.tm_year
        past_days = self.get_past_days_this_month()
        for month in list(xrange(this_month,13)) + list(xrange(1, this_month)):
            year = this_year
            if month < this_month: year += 1
            for day in xrange(1,32):
                if (day, month) in past_days: continue
                try:
                    # ValueError if invalid day-of-month
                    date = datetime.date(year, month, day)
                    for item in self.clone_filtered_for_date(recorderitems, date):
                        yield item
                except:
                    pass
    def adjust_flat_recorderitems(self, itemlist):
        previous = None
        for item in itemlist:
            if item is None:
                continue # old group separator
            if item.endtimeMMM == item.newtimeMMM:
                continue # deleted element
            if previous is None:
                previous = item
                continue
            item_newtimeMMM = item.newtimeMMM
            if previous.onlydate == item.onlydate:
                pass
            elif previous.onlydate + datetime.timedelta(1) == item.onlydate:
                item_newtimeMMM += 24 * 60
            else:
                previous = None
                continue # items are separate by more than a day
            if previous.endtimeMMM + previous.extratimeM < item_newtimeMMM:
                previous = None
                continue # separate by at least a few minutes
            # -------------------------------------------------
            nextday = 0
            if item.endtimeMMM < item.newtimeMMM:
                nextday = 24 * 60
            if previous.rank > item.rank:
                item_newtime = item.newtimeMMM
                item.newtimeMMM = previous.endtimeMMM + previous.extratimeM
                if item_newtime != item.newtimeMMM:
                    item.message += " %s >>" % MMMtoHHMM(item_newtime) 
                    item.message += " %s;" % MMMtoHHMM(item.newtimeMMM)
            elif previous.rank < item.rank:
                previous_endtime = previous.endtimeMMM
                previous.endtimeMMM = item.newtimeMMM
                previous.extratimeM = 0
                if previous_endtime != previous.endtimeMMM:
                    previous.message += " %s << " % MMMtoHHMM(previous.endtimeMMM)
                    previous.message += " %s;" % MMMtoHHMM(previous_endtime)
            elif item.newtimeMMM < previous.endtimeMMM + previous.extratimeM:
                item_newtime = item.newtimeMMM
                item.newtimeMMM = previous.endtimeMMM + previous.extratimeM
                if item_newtime != item.newtimeMMM:
                    item.message += " %s ->" % MMMtoHHMM(item_newtime)
                    item.message += " %s;;" % MMMtoHHMM(item.newtimeMMM)
            if item.endtimeMMM + nextday <= item.newtimeMMM:
                item.endtimeMMM = item.newtimeMMM
                item.extratimeM = 0
                item.message += " [DEL]"
            elif previous.endtimeMMM == previous.newtimeMMM:
                previous.message += " [DEL]"
            previous = item
    def recorderitems_groups(self, itemlist):
        group = None
        for item in itemlist: 
            if not group:
                group = RecorderGroup()
                group.weekday = item.weekday
                group.firstdate = item.onlydate
                group.newtimeMMM = item.newtimeMMM
                group.endtimeMMM = item.endtimeMMM
                group.extratimeM = item.extratimeM
                group.items += [ item ]
                continue
            delta = item.onlydate - group.firstdate
            deltaMMM = delta.days * 24 * 60
            if group.endtimeMMM < item.newtimeMMM + deltaMMM:
                yield group
                group = RecorderGroup()
                group.weekday = item.weekday
                group.firstdate = item.onlydate
                group.newtimeMMM = item.newtimeMMM
                group.endtimeMMM = item.endtimeMMM
                group.extratimeM = item.extratimeM
                group.items += [ item ]
            else:
                group.endtimeMMM = item.endtimeMMM + deltaMMM
                group.extratimeM = item.extratimeM
                group.items += [ item ]
        if group is not None:
            yield group
    def deleted_items(self, itemlist):
        for item in itemlist:
            if item.newtimeMMM == item.endtimeMMM:
                yield item
    def plan2(self, entries):
        """ main entry point """
        itemlist = list(self.recordinglist_to_flat_recorderitems(entries))
        deleted = 0
        for round in xrange(10):
            self.adjust_flat_recorderitems(itemlist)
            newdeleted = len(list(self.deleted_items(itemlist)))
            if newdeleted > deleted:
                continue
        plan = RecorderGroupPlan()
        for group in self.recorderitems_groups(itemlist):
            plan.addgroup(group)
        group = RecorderGroup()
        item = RecorderItem()
        item.message = "itemlist length %s" % len(itemlist)
        group.items += [ item ]
        plan.addgroup(group)        
        return plan
    def recordinglist_to_recordertimelist(self, entries, ahead = months_ahead):
        recorderitems = list(self.recordinglist_to_recorderitems(entries, ahead))
        localtime = time.localtime()
        this_month = localtime.tm_mon
        this_year = localtime.tm_year
        past_days = self.get_past_days_this_month()
        for month in list(xrange(this_month,13)) + list(xrange(1, this_month)):
            year = this_year
            if month < this_month: year += 1
            for day in xrange(1,32):
                if (day, month) in past_days: continue
                try:
                    # ValueError if invalid day-of-month
                    date = datetime.datetime(year, month, day)
                    for item in recorderitems:
                        if item.onlyday: 
                            if item.onlyday != date.day: continue
                            if date.month not in item.months: continue
                        elif item.months:
                            if date.month not in item.months: continue
                        else:
                            if item.weekday != date.weekday(): continue
                        self.logg.debug("* %s => [%s.%s.] w%s '%s'", date, item.onlyday, item.months, item.weekday, item.title)
                        newtimeMMM = item.newtimeMMM
                        endtimeMMM = item.endtimeMMM
                        if endtimeMMM < newtimeMMM: endtimeMMM += 24 * 60
                        endtimeMMM += item.extratimeM
                        elem = RecorderTime(item)
                        elem.datetimeX = date + datetime.timedelta(minutes = newtimeMMM)
                        elem.datetimeY = date + datetime.timedelta(minutes = endtimeMMM)
                        elem.adapters = self.adapters(item.channelname)
                        # elem.message += " (([%s .. %s] from %s..%s))" % (elem.datetimeX, elem.datetimeY, newtimeMMM, endtimeMMM)
                        yield elem
                except:
                    pass
    def adjust_recordertimelist(self, recordertimelist, adapter = None):
        """ recordertimelist contains absolute X Y dates """
        minimum = datetime.timedelta(minutes = 2)
        previous = None
        for current in recordertimelist:
            if current.deleted:
                continue
            if adapter is not None and current.adapter is not None:
                if adapter != current.adapter:
                    continue
            if previous is None:
                previous = current
                continue
            if previous.datetimeY <= current.datetimeX:
                previous = current
                continue # nothing to do - there is a gap
            if previous.datetimeX > current.datetimeX:
                raise Exception("previous starts after current")
            overlapY = previous.datetimeY - current.datetimeX
            overlapM = deltaM(overlapY)
            assert overlapM > 0
            if previous.item.rank < current.item.rank:
                # move previous endtime down
                if overlapM <= previous.extratimeM:
                    previous.extratimeM -= overlapM
                    previous.datetimeY -= overlapY
                    if current.item.channelname != previous.item.channelname:
                        previous.message += " cut extratimeM %03d," % overlapM
                    else:
                        previous.message += " continues"
                    previous = current
                else: 
                    extraY = datetime.timedelta(minutes = previous.extratimeM)
                    previous.datetimeY -= extraY
                    previous.extratimeM = 0 
                    if current.datetimeX <= previous.datetimeX:
                        previous.deleted = True
                        previous.datetimeY = previous.datetimeX
                        previous.endtimeMMM = previous.newtimeMMM
                        previous.extratimeM = 0
                        previous.message += " deleted as next one starts %s," % MMMtoHHMM(current.newtimeMMM)
                    else:
                        if previous.datetimeY > current.datetimeX:
                            previous.datetimeY = current.datetimeX
                            previous.endtimeMMM = current.newtimeMMM
                            if current.item.channelname != previous.item.channelname:
                                previous.message += " end time set to next start %s," % MMMtoHHMM(current.newtimeMMM)
                            else:
                                previous.message += " continue"
                        if previous.datetimeY - previous.datetimeX < minimum:
                            previous.deleted = True
                            previous.datetimeY = previous.datetimeX
                            previous.endtimeMMM = previous.newtimeMMM
                            previous.extratimeM = 0
                            previous.message += " and deleted as it is too short now"
                        else:
                            previous = current
            else:
                # move current starttime up
                if current.datetimeY <= previous.datetimeY:
                    if previous.datetimeX > current.datetimeX:
                        current.message+= "previous starts after current"
                    current.deleted = True
                    current.datetimeX = current.datetimeY
                    current.newtimeMMM = current.endtimeMMM
                    current.extratimeM = 0
                    current.message += " deleted as previous one ends %s," % MMMtoHHMM(previous.endtimeMMM)
                else:
                    if current.datetimeX < previous.datetimeY:
                        current.datetimeX = previous.datetimeY
                        # current.item.weekday = current.datetimeX.weekday
                        # if current.item.onlyday: # might have crossed midnight 
                        #    current.item.onlyday = current.datetimeX.day
                        #    current.item.months = [ current.datetimeX.month ] 
                        current.newtimeMMM = previous.endtimeMMM + previous.extratimeM
                        if current.item.channelname != previous.item.channelname:
                            current.message += " set start time to previous end %s," % MMMtoHHMM(current.newtimeMMM)
                        else:
                            current.message += " continue"
                    if current.datetimeY - current.datetimeX < minimum:
                        current.deleted = True
                        current.datetimeX = current.datetimeY
                        current.newtimeMMM = current.endtimeMMM
                        current.extratimeM = 0
                        current.message += " and deleted as it is too short now"
                    else:
                        previous = current
    def assign_adapters_for_timelist(self, recordertimelist):
        """ initialized recording adapter - if recordings overlap
            and one of them has multiple adapter options than assign
            one of the secondary adapters available.  """
        previous = None
        for current in recordertimelist:
            if current.deleted:
                continue
            if current.adapters:
                current.adapter = current.adapters[0]
            if previous is None:
                previous = current
                continue
            if previous.datetimeY <= current.datetimeX:
                previous = current
                continue # nothing to do - there is a gap
            if previous.datetimeX > current.datetimeX:
                raise Exception("previous starts after current")
            overlapY = previous.datetimeY - current.datetimeX
            overlapM = deltaM(overlapY)
            assert overlapM > 0
            if previous.item.channelname == current.item.channelname:
                previous = current
                continue
            done = True
            while not done:
                if previous.item.rank < current.item.rank:
                    for adapter in previous.adapters:
                        if adapter != current.adapter:
                            previous.adapter = adapter
                            done = True; break
                    for adapter in current.adapters:
                        if adapter != previous.adapter:
                            current.adapter = adapter
                            done = True; break
                else:
                    for adapter in current.adapters:
                        if adapter != previous.adapter:
                            current.adapter = adapter
                            done = True; break
                    for adapter in previous.adapters:
                        if adapter != current.adapter:
                            previous.adapter = adapter
                            done = True; break
            if not done:
                # can not split overlapping recordings to different adapers
                pass
    def timelist_groups(self, timelist, adapter = None):
        group = None
        previous = None
        previousgroup = None
        predeletes = []
        seen = ""
        for elem in timelist:
            self.logg.debug("timelist_groups: adapter '%s' -vs- '%s'",
                      adapter, elem.adapter)            
            if adapter is not None and elem.adapter is not None:
                if adapter != elem.adapter:
                    continue
            item = elem.item.clone()
            item.newtimeMMM = elem.newtimeMMM
            item.endtimeMMM = elem.endtimeMMM
            item.extratimeM = elem.extratimeM
            item.weekday = elem.datetimeX.weekday()
            item.onlyday = elem.datetimeX.day
            item.months = [ elem.datetimeX.month ]
            item.adapter = elem.adapter
            if item.newtimeMMM != elem.item.newtimeMMM:
                item.message += " [%s]>>[%s]" % (MMMtoHHMM(elem.item.newtimeMMM), MMMtoHHMM(item.newtimeMMM))
            if item.endtimeMMM != elem.item.endtimeMMM:
                item.message += " [%s]<<[%s]" % (MMMtoHHMM(item.endtimeMMM), MMMtoHHMM(elem.item.endtimeMMM))
            # ==>
            if not group or elem.datetimeX > previous.datetimeY:
                # START or TIME GAP
                if group:
                    yield group ; previousgroup = group; group = None
                item.message = " ."+item.message
                if elem.deleted: 
                    item.message += " [DEL]"
                    predeletes += [ item ]
                else:
                    previous = elem
                    group = RecorderGroup()
                    group.weekday = item.weekday
                    group.newtimeMMM = item.newtimeMMM
                    group.endtimeMMM = item.endtimeMMM
                    group.extratimeM = item.extratimeM
                    group.adapter = item.adapter
                    group.items = predeletes + [ item ]
                    predeletes = []
            else:
                # HANDOVER
                item.message = " :"+item.message
                if elem.deleted: 
                    item.message += " [DEL]"
                    group.items += [ item ]
                else:
                    previous = elem
                    group.endtimeMMM = item.endtimeMMM
                    group.extratimeM = item.extratimeM
                    group.items += [ item ]
            item.message += elem.message + seen
        if predeletes:
            if group:
                group.items += predeletes
            elif previousgroup:
                previousgroup.items += predeletes
        if group:
            # END
            yield group ; group = None
    def reduce_regular_groups(self, plan):
        class BlockGroup:
            def __init__(self):
                self.groups = []
        blocks = {}
        for group in plan.groups():
            group.deleted = False
            group.weekday = group.items[0].weekday
            group.hasonlydays = 0
            for item in group.items:
                if item.cloned and item.cloned.onlyday:
                    group.hasonlydays += 1
            key = (group.weekday, group.newtimeMMM, group.endtimeMMM, group.extratimeM)
            if key not in blocks:
                blocks[key] = BlockGroup()
            blocks[key].groups += [ group ]
        for key, block in blocks.items():
            block.master = None
            months_with_onlydays = []
            for group in block.groups:
                month = group.items[0].months[0]
                if group.hasonlydays:
                    if month not in months_with_onlydays:
                        months_with_onlydays += [ month ]
            # now we have a candidate of groups that we want to collapse
            block.months = [ month for month in xrange(1,13) 
                            if month not in months_with_onlydays ]
            for group in block.groups:
                month = group.items[0].months[0]
                if month not in block.months: # month in months_with_onlydays
                    continue
                if block.master is None:
                    block.master = group
                    for item in group.items:
                        item.onlyday = None
                        item.months = block.months
                    self.make_cronmonths(group)
                else:
                    group.deleted = True
                    for item in group.items:
                        item.onlyday = None
                        item.months = []
        newplan = RecorderGroupPlan()
        for group in plan.groups():
            if group.deleted: continue
            newplan.addgroup(group)
        return newplan           
    def plan3(self, entries):
        """ main entry point """
        self.logg.info("plan3")
        timelist = list(self.recordinglist_to_recordertimelist(entries))
        old_deleted = 0
        for round in xrange(2):
            timelist = sorted(timelist, key = lambda x: x.datetimeX )
            self.adjust_recordertimelist(timelist)
            deleted = [ elem for elem in timelist if elem.deleted ]
            new_deleted = len(deleted)
            if old_deleted < new_deleted:
                old_deleted = new_deleted
                continue
        timelist = sorted(timelist, key = lambda x: x.datetimeX )
        plan = RecorderGroupPlan()
        for group in self.timelist_groups(timelist):
            plan.addgroup(group)
        if True:
            return self.reduce_regular_groups(plan)
        return plan
    def plan4(self, entries):
        """ main entry point """
        self.logg.info("plan4")
        timelist = list(self.recordinglist_to_recordertimelist(entries))
        self.assign_adapters_for_timelist(timelist)
        old_deleted = 0
        for round in xrange(2):
            timelist = sorted(timelist, key = lambda x: x.datetimeX )
            for adapter in self.adapterlist():
                self.adjust_recordertimelist(timelist, adapter)
            deleted = [ elem for elem in timelist if elem.deleted ]
            new_deleted = len(deleted)
            if old_deleted < new_deleted:
                old_deleted = new_deleted
                continue
        timelist = sorted(timelist, key = lambda x: x.datetimeX )
        plan = RecorderGroupPlan()
        for adapter in self.adapterlist():
            for group in self.timelist_groups(timelist, adapter):
                plan.addgroup(group)
        self.logg.info("adapterlist = %s", self.adapterlist())
        if True:
            plan.sort()
            return self.reduce_regular_groups(plan)
        else:
            plan.sort()
            return plan
            
    def plan(self, entries):
        if self.algorithm == "plan1":
            return self.plan1(entries)
        if self.algorithm == "plan2":
            return self.plan2(entries)
        self.set_adapters_from_channels_list(self.channels_list())
        if self.algorithm == "plan3":
            return self.plan3(entries)
        if self.algorithm == "plan4":
            return self.plan4(entries)
        #else:
        return self.plan3(entries)

def deltaM(td):
    return td.seconds / 60 + (td.days * 24 * 60)

def MMMtoHHMM(mmm):
    if mmm is None: return ""
    return "%02i:%02i" % (mmm / 60, mmm % 60)