Source

trac-dvbcronrecording-plugin / src / dvbcronrecording / core.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
# -*- coding: utf-8 -*-
import pkg
import re
import os.path
import time
import datetime
import locale

from trac.core import Component, implements
# from trac.wiki import wiki_to_html, wiki_to_oneliner
from trac.web.chrome import add_stylesheet, add_script
from trac.util import Markup #, format_datetime

from trac.web import IRequestHandler
from trac.perm import IPermissionRequestor
from trac.web.chrome import INavigationContributor, ITemplateProvider
from trac.timeline.api import ITimelineEventProvider
from trac.config import Option, ListOption, PathOption, BoolOption

from translate import Translate #@UnresolvedImport
from computer import DvbCronRecordingPlanComputer, MMMtoHHMM
try:
    from channels import DvbCronRecordingChannelsPlugin
except:
    DvbCronRecordingChannelsPlugin = None

from quoting import quote4, unquote4
#### sudo mkdir /srv/dvbcronrecording
#### sudo chown wwwrun:www /srv/dvbcronrecording/

PACKAGE = 'dvbcronrecording'
NAV = 'recordings'
URL = 'recording'
INTODIR = "/srv/record"
VARDIR = "/srv/dvbcronrecording"
TITLE = ".recording."
CRONMINUTES = "9,19,29,39,49,59"
CRONUSER = "root"
RECORDINGUSER = "root"

LIST_VIEW = 'DVBREC_LIST_VIEW'
LIST_APPEND = 'DVBREC_LIST_APPEND'
LIST_DELETE = 'DVBREC_LIST_DELETE'

RECORDING_MK = "recording.mk"
RECORDING_CRON = "recording.cron"
RECORDING_UPDATE_CRON = "recording-update.cron"
RECORDING_UPDATE_CHANGE_CRON = "recording-update-change.cron"
RECORDING_CHANNELSCONF = "channels%(adapter)s.conf"

CHANNELSCONF = "~/.szap/{adapter}/channels.conf"

default_adapter = u"0"

from dvbcronrecording.db.session import db_cnx, commit
from dvbcronrecording.db.schema import RecordingList #@UnresolvedImport
from dvbcronrecording.db.schema import RecordingChanges #@UnresolvedImport

def _(text): return text

def intnull(value, default = None):
    if value is None: return default
    try: return int(value)
    except Exception: return default
def lookup(lists, entry, default = None):
    if entry is None: return default
    idx = intnull(entry)
    if idx is None or idx >= len(lists): return default
    return lists[idx]
def ustr(text):
    if type(text) is unicode: return text
    if type(text) is str: return unicode(text)
    return unicode(str(text))

class MakefileEntry: pass

class AdapterList:
    def __init__(self):
        self._adapters = []
    def number(self, adapter):
        n = len(self._adapters)
        if adapter not in self._adapters:
            self._adapters += [ adapter ]
        else:
            n = self._adapters.index(adapter)
        return n
    def name(self, adapter):
        return chr(ord('A') + self.number(adapter))
    def adaptername(self, item):
        return self.name(getattr(item, "adapter", default_adapter))

"""
  here we are.
"""
class DvbCronRecordingPlugin(Component):

    #
    # Public methods
    #

    implements(IPermissionRequestor, INavigationContributor, ITemplateProvider,
      IRequestHandler, ITimelineEventProvider)

    vardir = Option(PACKAGE, "vardir", VARDIR, 
     doc="Where to store the runtime data like the makefile and cronfile.")
    title = Option(PACKAGE, "title", TITLE,
     doc="The title to use on the navigation bar (subject to translation).")
    intodir = Option(PACKAGE, "intodir", INTODIR,
     doc="Where to put the recorder files (mostly videos of course).")
    cronminutes = ListOption(PACKAGE, "cronminutes", CRONMINUTES,
     doc="The clock minutes when to update crond with the recording plan.")
    cronuser = Option(PACKAGE, "cronuser", CRONUSER,
     doc="The system user that does update the /etc/cron.d/* files.")
    recordinguser = Option(PACKAGE, "recordinguser", RECORDINGUSER,
     doc="The system user to read /dev/dvb/* and to write recorder files.")
    crondirectly = BoolOption(PACKAGE, "crondirectly", False,
     doc="Write the recording plan directly to /etc/cron.d/*")
    channelsconf = Option(PACKAGE, "channelsconf", CHANNELSCONF,
     doc="File path pattern to the szap channels.conf to be used.") 
    
    # IPermissionRequestor methods

    """
      Returns list of permitions privided by this plugin.
    """
    def get_permission_actions(self):
        return [LIST_VIEW, LIST_APPEND, LIST_DELETE ]

    # ITemplateProvider methods

    """
      Returns additional path where stylesheets are placed.
    """
    def get_htdocs_dirs(self):
        return [(PACKAGE, pkg.resource_filename(__name__, 'htdocs'))]

    """
      Returns additional path where templates are placed.
    """
    def get_templates_dirs(self):
        return [pkg.resource_filename(__name__, 'templates')]

    # INavigationContributor methods

    """
      Returns name of active navigation item.
    """
    def get_active_navigation_item(self, req):
        return NAV

    """
      Returns navigation items provided by this plugin.
    """
    def get_navigation_items(self, req):
        if not req.perm.has_permission(LIST_VIEW):
            return
        translate = Translate(PACKAGE, req.locale)
        yield ('mainnav', NAV, Markup('<a href="%s">%s</a>' % 
          (req.href(URL), translate.get(self.title, TITLE))))

    # IRequestHandler methods

    """
      Determines if request should be handled by this plugin.
    """
    def match_request(self, req):
        m = re.match(r"/%s(?:/(.*))?$" % URL, req.path_info)
        if m:
            page = m.group(1)
            if page and page.startswith("channel"): return False
            if page and page.startswith("file"): return False
            if page and page.startswith("programguide"): return False
            req.args['page'] = page 
            return True
        return False

    """
      Handles display, append and delete requests on this plugin.
    """
    def process_request(self, req):
        req.perm.assert_permission(LIST_VIEW)
        translate = Translate(PACKAGE, req.locale, req.languages )

        page = req.args['page']
        if not page: page = "list"
        
        if page in [ 'makefile' ]:
            data = {}
            data['title'] = translate("Makefile Overview")
            data['entries'] = self._makefile_entries(req)
            data['_'] = translate
            add_stylesheet(req, PACKAGE+'/css/recordinglist.css')
            add_stylesheet(req, PACKAGE+'/css/dvbcronrecording.css')
            add_script(req, 'common/js/trac.js')
            return ('recordingmakefile.html', data, None)
        if page in [ 'cronfile' ]:
            data = {}
            data['title'] = translate("Cronfile Overview")
            data['messages'] = [ self.crontabreloadline() ]
            data['cronlines'] = self._crontablines(req)
            data['_'] = translate
            add_stylesheet(req, PACKAGE+'/css/recordinglist.css')
            add_stylesheet(req, PACKAGE+'/css/dvbcronrecording.css')
            add_script(req, 'common/js/trac.js')
            return ('recordingcronfile.html', data, None)
        if page in [ 'plan' ]:
            data = {}
            data['title'] = translate("Recording Plan")
            data['messages'] = [ ]
            data['weekdaynames'] = translate("**weekdaynames")
            data['recordings'] = self._recording_plan(req)
            data['_'] = translate
            add_stylesheet(req, PACKAGE+'/css/recordinglist.css')
            add_stylesheet(req, PACKAGE+'/css/dvbcronrecording.css')
            add_script(req, 'common/js/trac.js')
            return ('recordingplan.html', data, None)
        if page in [ 'activate' ]:
            return self._activate(req, page)
        if page in [ "save" ]:
            text = req.args["text"]
            result = self.savetext(req, text)
            commit()
            data = {}
            data['title'] = translate("Save")
            data['messages'] = ['(%s)' % text, result]
            data['text'] = self.loadtext(req)
            data['_'] = translate
            add_stylesheet(req, PACKAGE+'/css/recordinglist.css')
            add_stylesheet(req, PACKAGE+'/css/dvbcronrecording.css')
            add_script(req, 'common/js/trac.js')
            return ('recordingeditor.html', data, None)
        if page in [ "edit" ]:
            data = {}
            data['title'] = translate("Edit")
            data['messages'] = ['use the traditional syntax']
            data['text'] = self.loadtext(req)
            data['_'] = translate
            add_stylesheet(req, PACKAGE+'/css/recordinglist.css')
            add_stylesheet(req, PACKAGE+'/css/dvbcronrecording.css')
            add_script(req, 'common/js/trac.js')
            return ('recordingeditor.html', data, None)
            
        
        # ------------------------------------------------
        message = ""
        
        if page in [ None, '', 'list' ]:
            pass
        if page in [ 'newentry' ]:
            req.perm.assert_permission(LIST_APPEND)
            message = self._recordings_append(req)
        if page in [ 'update' ]:
            req.perm.assert_permission(LIST_APPEND)
            message = self._recordings_update(req)
        if page in [ 'delete' ]:
            req.perm.assert_permission(LIST_DELETE)
            message = self._recordings_delete(req)
        
        # database commit and return page content
        commit()
       
        if not message: message = translate("fully internationalized")
        # import locale
        # from trac.util.translation import get_negotiated_locale
        # message += u",".join([ str(item) for item in locale.getlocale()])
        message += u" %s" % (translate("?problem"))

        # message = str(req.locale.days)
        # passing variables to template
        data = {}
        data['message'] = message
        data['title'] = translate('Recording List')
        data['recordings'] = self._recordings_list(req)
        data['appends'] = req.perm.has_permission(LIST_APPEND);
        data['author'] = req.authname or ""
        data['defaults'] = list(self._newrecordings_list(req))
        data['weekdaynames'] = translate("**weekdaynames")
        data['statusnames'] = translate("**statusnames")
        data['prioritynames'] = translate("**prioritynames")
        data['channelnamelist'] = [ "" ] + self._channelname_list(req)
        data['_'] = translate

        add_stylesheet(req, 'common/css/wiki.css')
        add_stylesheet(req, PACKAGE+'/css/recordinglist.css')
        add_stylesheet(req, PACKAGE+'/css/dvbcronrecording.css')
        add_script(req, '%s/js/jquery.ui.datepicker.js' % (PACKAGE))
        if req.locale:
            add_script(req, '%s/js/jquery.ui.datepicker-%s.js' % (PACKAGE, req.locale))
        add_script(req, 'common/js/trac.js')
        add_script(req, 'common/js/wikitoolbar.js')
        return ('recordinglist.html', data, None)

    # ITimelineEventProvider methods

    def get_timeline_filters(self, req):
        filters = []
        if LIST_VIEW in req.perm:
            filters += [ ("recordinglist", _("Recording List"), False)]
        return filters

    def get_timeline_events(self, req, start, stop, filters):
        try:
            if "recordinglist" in filters:
                session = db_cnx(self.env)
                q = session.query(RecordingChanges)
                q = q.filter(RecordingChanges.modified >= start)
                q = q.filter(RecordingChanges.modified <= stop)
                for item in q.all():
                    yield (PACKAGE, item.modified.replace(tzinfo=req.tz), item.username,
                           (item.tablename, item.changed))
        except Exception, e:
                yield (PACKAGE, datetime.datetime.now(), req.authname,
                       "ERROR:%s" % str(e))
            
    def render_timeline_event(self, context, field, event):
        tablename, changed = event[3]
        if field == 'url':
            return context.href.recording('list')
        elif field == 'title':
            gettext = Translate(PACKAGE, context.req.locale)
            if changed.startswith("ACTIVATE"):
                title = gettext("the recording list was activated")
            else:
                title = gettext("a recording list entry was modified")
            return title
        elif field == 'description':
            translate = Translate(PACKAGE, context.req.locale)
            gettext = translate
            mapped = {"set next recording on" : gettext("set next recording on"),
                      "set some recording on" : gettext("set some recording on"),                      
                      "set no recording on" : gettext("set no recording on"),
                      "ACTIVATE: the modified recordinglist was activated":
                        gettext("ACTIVATE: the modified recordinglist was activated")
                      }
            for a,b in mapped.items():
                if changed.startswith(a):
                    changed = b + changed[len(a):]
            for i, name in translate("**weekdaynames").items():
                changed = changed.replace(("**%s]" % i), (name+"]"))
            return changed
        
            
    # ====================================================================
    
    # ====================================================================
    
    # ====================================================================        
    #
    # Private methods
    #
    """
      Returns list of the adapter settings
    """
    def _channelname_list(self, req):
        if DvbCronRecordingChannelsPlugin is None:
            return []
        channels = DvbCronRecordingChannelsPlugin(self.env)
        return channels.channelname_list(req)
    
    def _newrecordings_list(self, req):
        translate = Translate(PACKAGE, req.locale)
        channel = translate.get("prime-time-channel", "pro7")
        starts = translate.get("prime-time-start", "20:15")
        ends = translate.get("prime-time-ends", "22:10") 
        extra = translate.get("prime-time-extra", "8")
        movie = translate.get("prime-time-movie", "the-movie-today")
        now = time.localtime()
        onlydate = '%s.%s.' % (now[2],now[1])
        weekday = now[6] # monday is 0
        cols = ['id', 'channelname','newtime','endtime','extratime','weekday','onlydate','status','priority','title',]
        vals = [0, channel, starts, ends, extra, weekday, onlydate,'ok', 3, movie]
        yield dict(zip(cols,vals))

    """
      Returns list of recordings
    """
    def _recordings_list(self, req):
        session = db_cnx(self.env)
        q = session.query(RecordingList)
        q = q.order_by("weekday", "newtime", "endtime", "status")
        return q.all()

    """
      Appends a new entry into list
    """
    def _recordings_append(self, req):
        item = RecordingList()
        item.channelname = req.args.get("channelname")
        item.newtime = req.args.get("newtime")
        item.endtime = req.args.get("endtime")
        item.extratime = req.args.get("extratime")
        item.weekday = req.args.get("weekday")
        item.onlydate = req.args.get("onlydate")
        item.status = req.args.get("status")
        item.priority = req.args.get("priority")
        item.title = req.args.get("title")
        session = db_cnx(self.env)
        session.add(item)
        datespec = "[%s-%s%s]" % (item.newtime, 
                                item.endtime, 
                                item.onlydate and " "+item.onlydate or " **%s" % item.weekday 
                               ) 
        changed = "new recording on %s %s %s" % (item.channelname,
                                                 datespec,
                                                 item.title)
        session.add(RecordingChanges(tablename="RecordingList",
                                  username=req.authname,
                                  modified=datetime.datetime.now(),
                                  changed=changed))
        session.flush()
        return u"OK [rec:%s]" % item.id

    """
      Updates an entry in the list
    """
    def _recordings_update(self, req):
        session = db_cnx(self.env)
        item = session.query(RecordingList).get(req.args.get("id"))
        if not item:
            return "ERROR: no recordinglist item with id=%s" % req.args.get("id") 
        item.channelname = req.args.get("channelname")
        item.newtime = req.args.get("newtime")
        item.endtime = req.args.get("endtime")
        item.extratime = req.args.get("extratime")
        item.weekday = req.args.get("weekday")
        item.onlydate = req.args.get("onlydate")
        item.status = req.args.get("status")
        item.priority = req.args.get("priority")
        item.title = req.args.get("title")
        state = item.status
        if state == "ok": state = "next"
        if not state: state = "some"
        datespec = "[%s-%s%s]" % (item.newtime, 
                                item.endtime, 
                                item.onlydate and " "+item.onlydate or " **%s" % item.weekday 
                               ) 
        changed = "set %s recording on %s %s %s" % (state,
                                                         item.channelname,
                                                         datespec,
                                                         item.title)
        session.add(RecordingChanges(tablename="RecordingList",
                                  username=req.authname,
                                  modified=datetime.datetime.now(),
                                  changed=changed))
        session.flush()
        return u"OK [rec:%s]" % item.id

    """
      Deletes entry from recordings
    """
    def _recordings_delete(self, req):
        q = db_cnx(self.env).query(RecordingList)
        q = q.filter_by(id = req.args.get("id"))
        q.delete()


    # ---------------------------------------------------------------
    # old-style format
    # ---------------------------------------------------------------
    
    def savetext(self, req, text):
        translate = Translate(PACKAGE, req.locale)
        msgs = []
        for line in text.split("\n"):
            if line.startswith("+"):
                msgs += [ self.savetextline(req, line) ]
        n = len(msgs)
        msg = translate.nget("(%(n)s line)", "(%(n)s lines)", n) % locals()
        msg += "\n %s" % str(msgs)
        return msg
    def savetextline(self, req, line):
        m = re.match(r"[+](\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.*)[!]", line)
        if m:
            channel = m.group(1)
            newtime = m.group(2)
            endtime = m.group(3)
            weekday = m.group(4)
            title = m.group(5)
            req.args["channelname"] = channel
            req.args["newtime"] = newtime
            arg = endtime.split("+",1)
            req.args["endtime"] = arg[0]
            if len(arg) > 1: req.args["extratime"] = arg[1]
            else: req.args["extratime"] = "0"
            arg = weekday.split(",", 1)
            req.args["weekday"] = self.enumweekday(arg[0].strip())
            if len(arg) > 1: req.args["onlydate"] = arg[1]
            else: req.args["onlydate"] = ""
            req.args["title"] = title
            req.args["status"] = u"ok" 
            return self._recordings_append(req)
        else:
            return "NO."
    def enumweekday(self, name):
        for key, value in Translate.de_weekdaynames.items():
            if value == name: return key
        return name
    def loadtext(self, req):
        return "\n".join(list(self.loadtextlines(req)))
    def loadtextlines(self, req):
        entries = self._recordings_list(req)
        computer = DvbCronRecordingPlanComputer(self.env)
        plan = computer.plan(req, entries)
        for group in plan.groups():
            newtime = MMMtoHHMM(group.newtimeMMM).replace(":","")
            weekday = group.weekday
            weekdayname = lookup(Translate.de_weekdaynames, weekday)
            xx = "xx-%s%s.sh" % (weekdayname, newtime)
            for item in group.items:
                channel = item.channelname
                newtime = MMMtoHHMM(item.newtimeMMM)
                endtime = MMMtoHHMM(item.endtimeMMM)
                extratime = item.extratimeM
                weekday = item.weekday
                weekdayname = lookup(Translate.de_weekdaynames, weekday)
                onlydate = item.onlyday
                if onlydate:
                    only = "%s.%s." % (onlydate, item.months[0])
                    day = weekdayname+","+only
                else:
                    day = weekdayname
                if extratime:
                    end = endtime+"+"+str(extratime)
                else:
                    end = endtime
                filename = quote4(item.title)
                yield "+%(channel)s %(newtime)s %(end)s %(day)s %(filename)s!" % locals()
            yield "> %s" % xx
        
    def _loadtextlines(self, req):
        entries = self._recordings_list(req)
        startchain = self._entries_to_startchain(entries)
        for chain in startchain:
            entry = chain.entry
            check = entry
            newtime = check["newtime"].replace(":","")
            weekday = check["weekday"]
            weekdayname = lookup(Translate.de_weekdaynames, weekday)
            xx = "xx-%s%s.sh" % (weekdayname, newtime)
            for check in [ entry ] + chain.after:
                channel = check["channelname"]
                newtime = check["newtime"]
                endtime = check["endtime"]
                extratime = check["extratime"]
                weekday = check["weekday"]
                weekdayname = lookup(Translate.de_weekdaynames, weekday)
                onlydate = check["onlydate"]
                if onlydate:
                    day = weekdayname+","+onlydate
                else:
                    day = weekdayname
                if extratime:
                    end = endtime+"+"+extratime
                else:
                    end = endtime
                filename = quote4(check["title"])
                yield "+%(channel)s %(newtime)s %(end)s %(day)s %(filename)s!" % locals()
            yield "> %s" % xx

    # ---------------------------------------------------------------
    # chain up the entries
    # ---------------------------------------------------------------
    def _activate(self, req, page):
        req.perm.assert_permission(LIST_VIEW)
        translate = Translate(PACKAGE, req.locale, req.languages )
        data = {}
        data['title'] = translate("Cron Activate")
        makefile_entries = self._makefile_entries(req)
        makefile_list = [ entry.rule for entry in makefile_entries  ]
        makefile_entries = self._makefile_entries(req) # FIXME
        crontab_lines = self._to_crontablines(makefile_entries)
        crontab_reload = self.crontabreloadline()
        crontab_change = self.crontabchangeline()
        crontab_list = list(crontab_lines)
        written_messages = []
        for adapter in self.adapter_list(req):
            filename = self.cron_channelsconf_filename(adapter)
            conf = self.channelsconf_for_adapter(adapter)
            if conf:
                written = self.writefile(req, filename, conf)
                written_messages += [ written ]
        a = self.writefile(req, self.cronfilename(), list(crontab_list))
        b = self.writefile(req, self.makefilename(), list(makefile_list))
        c = self.writefile(req, self.cron_update_filename(), [ crontab_reload ])
        d = self.writefile(req, self.cron_update_change_filename(), [ crontab_change ])
        e = translate("cron.will.be.updated.every")+(" %s" % self.cronminutes_string())
        if self.crondirectly:
            e = self.writefile(req, self.cron_target_filename(), list(crontab_list))
        try:
            message = "ACTIVATE: the modified recordinglist was activated"
            session = db_cnx(self.env)
            session.add(RecordingChanges(tablename="RecordingList",
                                  username=req.authname,
                                  modified=datetime.datetime.now(),
                                  changed=message))
        except:
            pass
        data['messages'] = written_messages + [ a, b, c, d, e ]
        data['cronlines'] = crontab_list # + [ " ============= "] + makefile_list
        data['_'] = translate
        add_stylesheet(req, PACKAGE+'/css/recordinglist.css')
        add_stylesheet(req, PACKAGE+'/css/dvbcronrecording.css')
        add_script(req, 'common/js/trac.js')
        return ('recordingcronfile.html', data, None)
    
    def _recording_plan(self, req):
        entries = self._recordings_list(req)
        return list(self._recording_plan_from(req, entries))
    def _recording_plan_from(self, req, entries):
        computer = DvbCronRecordingPlanComputer(self.env)
        plan = computer.plan(req, entries)
        for item in plan.items():
            yield item
            
    def _channelname_to_channelconflist(self, req, channelname):
        if DvbCronRecordingChannelsPlugin is None:
            return []
        channels = DvbCronRecordingChannelsPlugin(self.env)
        return channels.channelname_to_channelconflist(req, channelname)
    def adapter_list(self, req):
        if DvbCronRecordingChannelsPlugin is None:
            return [ 0 ]
        channels = DvbCronRecordingChannelsPlugin(self.env)
        return channels.adapter_list(req)
    def channelsconf_for_adapter(self, adapter):
        if DvbCronRecordingChannelsPlugin is None:
            return [ 0 ]
        channels = DvbCronRecordingChannelsPlugin(self.env)
        return channels.channelsconf_for_adapter(adapter)
    def channels_list(self):
        if DvbCronRecordingChannelsPlugin is None:
            return [ 0 ]
        channels = DvbCronRecordingChannelsPlugin(self.env)
        return channels.channels_list()


    """ 
        This is doing the actual computations
    """
    def _makefile_entries(self, req):
        entries = self._recordings_list(req)
        computer = DvbCronRecordingPlanComputer(self.env)
        plan = computer.plan(req, entries)
        adapterlist = AdapterList()
        for group in plan.groups():
            if not group.items: continue
            item = group.items[0]
            HH = item.newtimeMMM / 60
            MM = item.newtimeMMM % 60
            AD = adapterlist.adaptername(item)
            if item.onlyday:
                DD = str(item.onlyday)
                EE = ",".join([str(month) for month in item.months ])
                startcron = "%02d %02d %2s %2s *" % (int(MM), int(HH), DD, EE)
                startname = "%02d.%02d.%02d.%s%s" % (int(HH), int(MM), item.onlyday, EE, AD)
            else:
                WW = ustr(int(item.weekday)+1)
                # WEEKDAY: tm_day Mo = 0 / -vs- / crontabs So = 0
                startcron = "%02d %02d  *  * %s" % (int(MM), int(HH), WW)
                startname = "%02d.%02d.%s%s" % (int(HH), int(MM), item.weekday, AD)
            lines = []
            for item in group.items:
                newtimeMMM = item.newtimeMMM
                endtimeMMM = item.endtimeMMM
                extratimeM = item.extratimeM
                if newtimeMMM >= endtimeMMM: continue
                runtimeseconds = (endtimeMMM + extratimeM - newtimeMMM) * 60
                filename = ustr("%s.mpg") % (quote4(item.title))
                channelname = item.channelname
                adapter = item.adapter or "0"
                channel = item.channelname
                frontend = 0
                if ":" in adapter:
                    adapter, frontend = adapter.split(":",1)
                channelsconf = self.cron_channelsconf_filename(adapter)
                format = "%Y%m%d-%a"+ustr(adapter)+"-%H%M"
                prefix = self.intodir+"/"
                cmd = [ u"gnutv -adapter %(adapter)s -frontend %(frontend)s" ]
                cmd += [ u" -channels %(channelsconf)s" ]
                cmd += [ u" -out file %(prefix)s`date +%(format)s`-%(filename)s" ]
                cmd += [ u" -timeout %(runtimeseconds)s '%(channel)s'" ]
                newtimeHHMM = MMMtoHHMM(item.newtimeMMM)
                endtimeHHMM = MMMtoHHMM(item.endtimeMMM)
                extratimePM = ""
                if extratimePM: extratime = "+%d" % extratimeM
                logged = ( newtimeHHMM, endtimeHHMM, extratimePM, item.title )
                lines += [ u"- logger -t recording -- 'NEXT %s %s%s %s'" % logged ]
                lines += [ (u" \\\n\t".join(cmd)) % locals() ]
                lines += [ u"- logger -t recording -- 'DONE %s %s%s %s'" % logged ]
            rule = u"%s : # %s" % (startname, startcron)
            for line in lines:
                rule += u"\n\t%s" % line
            # rule += u"\n\t: '%s'" % (item.message)
            make = MakefileEntry
            make.name = u"-"
            make.rule = rule
            make.cron = startcron
            make.start = startname 
            yield make
            
    def _crontablines(self, req):
        return self._to_crontablines(self._makefile_entries(req))
    def _to_crontablines(self, makefile_entries):
        for entry in makefile_entries:
            line = ("%s %s make -f %s %s" % (entry.cron, 
                self.recordinguser, self.makefilename(), entry.start))
            yield line
    def makefilename(self):
        return os.path.join(self.vardir, RECORDING_MK)
    def cronfilename(self):
        return os.path.join(self.vardir, RECORDING_CRON)
    def cron_update_filename(self):
        return os.path.join(self.vardir, RECORDING_UPDATE_CRON)
    def cron_update_change_filename(self):
        return os.path.join(self.vardir, RECORDING_UPDATE_CHANGE_CRON)
    def cron_channelsconf_filename(self, adapter):
        if not adapter or adapter == "0": adapter = ""
        return os.path.join(self.vardir, RECORDING_CHANNELSCONF % { "adapter" : str(adapter)})
    def cronminutes_string(self):
        cronminutes = ",".join([ item.strip() 
            for item in self.cronminutes if item.strip() ])
        if not cronminutes: 
            cronminutes = CRONMINUTES
        return cronminutes
    def crontabreloadline(self):
        crontime = "%s * * * *" % self.cronminutes_string()
        crontab = "/etc/crontab"
        cronfilename = self.cronfilename()
        cronfile = os.path.join("/etc/cron.d", os.path.basename(cronfilename))
        if cronfile == cronfilename:
            return ""
        cronaction = "cp %s %s; sleep 3; touch %s" % (cronfilename, cronfile, crontab)
        return "%s %s %s" % (crontime, self.cronuser, cronaction)
    def crontabchangeline(self):
        crontime = "%s * * * *" % self.cronminutes_string()
        crontab = "/etc/crontab"
        cron_update_filename = self.cron_update_filename()
        cron_target_filename = self.cron_target_filename()
        if cron_target_filename == cron_update_filename:
            return ""
        cronaction = "cp %s %s; sleep 3; touch %s" % (cron_update_filename, cron_target_filename, crontab)
        return "%s %s %s" % (crontime, self.cronuser, cronaction)
    def cron_target_filename(self):
        cron_update_filename = self.cron_update_filename()
        return os.path.join("/etc/cron.d", os.path.basename(cron_update_filename))
    def minutes(self, spec):
        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 zero(self, spec):
        if not spec: return 0
        return int(spec)
        
    def writefile(self, req, filename, lines):
        translate = Translate(PACKAGE, req.locale)
        directory = os.path.dirname(filename)
        try:
            if not os.path.isdir(directory):
                os.makedirs(directory)
        except Exception, e:
            msg = translate(u"ERROR:")
            msg += u" "+translate(u"create.directory '%(directory)s':") % locals()
            msg += u" "+str(e)
            return msg
        _, charset = locale.getdefaultlocale()
        if charset is None: charset = "UTF8"
        lastline = u"" 
        try:
            f = open(filename, "w")
            for line in lines:
                if not line.endswith("\n"): line += "\n"
                lastline = line
                f.write(ustr(line).encode(charset))
            f.close()
            n = len(lines)
            msg =  translate("done.save.to.file '%(filename)s'") % locals()
            msg += u" "+translate.nget(u"(%(n)s line)", u"(%(n)s lines)", n) % locals()
            return msg
        except IOError, e:
            msg = translate(u"ERROR:")
            msg += u" "+translate(u"save.to.file '%(filename)s':") % locals()
            msg += u" "+str(e)
            msg += u"\n %s" % lastline
            return msg
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.