Source

trac-dvbcronrecording-plugin / src / dvbcronrecording / channelsconf.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
# -*- coding: utf-8 -*-

import pkg #@UnresolvedImport
import re
from urllib import urlencode
from urllib2 import quote as quote2

import logging

from trac.core import Component, implements
# from trac.db import *
# 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 ITemplateProvider # INavigationContributor, 
from trac.util.presentation import Paginator

from translate import Translate
from tuning import tuning_adapter_list

PACKAGE = u'dvbcronrecording'
NAV = u'recordings'
URL = u'recording'
SUBURL = u'channelsconf'

CHANNELSCONF_VIEW = 'DVBREC_CHANNELSCONF_VIEW'
CHANNELSCONF_EDIT = 'DVBREC_CHANNELSCONF_EDIT'

DEBUG = False

from db import schema
def affinity(table_name, column_name):
    global tables
    for table in schema.tables:
        if table.name == table_name:
            for column in table.columns:
                if column.name == column_name:
                    return column.type
    return None
def aff(value, table_name, column_name):
    if value is None: return None
    typed = affinity(table_name, column_name)
    if typed in [ "int", "INT", "integer", "INTEGER"]:
        return intnull(value)
    return ustr(value)
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))
def q(text):
    return unicode(quote2(unicode(str(text)).encode("utf-8")))
    # return text
    # return unicode(quote_plus(unicode(str(text))))

logg = logging.getLogger("DvbCronRecordingChannelsConfPlugin")
if DEBUG:
    logg.addHandler(logging.FileHandler("/tmp/DvbCronRecordingChannelsConfPlugin.log"))
    logg.setLevel(logging.DEBUG)

polaritylist = { "H" : "H", "V" : "V", "lr" : "LR", "hr" : "HR" }

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

    #
    # Public methods
    #

    implements(IPermissionRequestor, ITemplateProvider,  IRequestHandler)

    # IPermissionRequestor methods

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

    # 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')]

    # IRequestHandler methods

    """
      Determines if request should be handled by this plugin.
    """
    def match_request(self, req):
        m = re.match(r"/%s/%s(?:/(.*))?$" % (URL, SUBURL), req.path_info)
        if m:
            page = m.group(1)
            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(CHANNELSCONF_VIEW)
        translate = Translate("channelsconf", req.locale)

        # getting cursor
        db = self.env.get_db_cnx()
        cursor = db.cursor()
        page = req.args['page']
        if not page: page = "show"
        if page in [ "save" ]:
            text = req.args["text"]
            result = self.savetext(cursor, req, text)
            db.commit()
            data = {}
            data['title'] = translate("Saved")
            data['messages'] = ['(%s)' % text, result]
            data['adapterlist'] = self._adapter_list(cursor, req)
            data['text'] = self.loadtext(cursor, req)
            data['_'] = translate
            add_stylesheet(req, PACKAGE+'/css/recordingchannelsconf.css')
            add_script(req, 'common/js/trac.js')
            return ('channelsconf_editor.html', data, None)
        if page in [ "edit" ]:
            data = {}
            data['title'] = translate("Edit")
            data['messages'] = [ translate('use the traditional dvbscan/zap syntax') ]
            data['adapterlist'] = self._adapter_list(cursor, req)
            data['text'] = self.loadtext(cursor, req)
            data['_'] = translate
            add_stylesheet(req, PACKAGE+'/css/recordingchannelsconf.css')
            add_script(req, 'common/js/trac.js')
            return ('channelsconf_editor.html', data, None)
        if page in [ "take", "takeover" ]:
            channels = self._channelsconf_selectby(cursor, req, ['adapter', 'title'])
            data = {}
            data['title'] = translate("Takeover")
            data['messages'] = [ "" ]
            data['adapterlist'] = self._adapter_list(cursor, req)
            data["_pagenum"] = req.args.get("_pagenum", "0")
            data["_pagesize"] = req.args.get("_pagesize", "10")
            data['datalist'] = Paginator(channels, int(data["_pagenum"]), int(data["_pagesize"]))
            data['_'] = translate
            data['urlencode'] = urlencode
            data['q'] = q
            add_stylesheet(req, PACKAGE+'/css/recordingchannelsconf.css')
            add_script(req, 'common/js/trac.js')
            return ('channelsconf_take.html', data, None)
        
        channeltype = ""
        if page in [ 'show']:
            channeltype = "video channels"
        if page in [ "list/video" ]:
            channeltype = "video channels"
        if page in [ "list/radio" ]:
            channeltype = "radio channels"
        if req.args.has_key("channeltype"):
            channeltype = req.args["channeltype"]
        if not channeltype:
            channeltype = "all channel types"
        
        # ------------------------------------------------
        message = ""
        
        if page in [ 'newentry', 'append' ]:
            message = self._channelsconf_append(cursor, req)
        if page in [ 'update' ]:
            message = self._channelsconf_update(cursor, req)
        if page in [ 'delete' ]:
            message = self._channelsconf_delete(cursor, req)
        
        # database commit and return page content
        db.commit()

        add_stylesheet(req, 'common/css/wiki.css')
        add_stylesheet(req, PACKAGE+'/css/recordingchannelsconf.css')
        add_script(req, 'common/js/trac.js')
        add_script(req, 'common/js/wikitoolbar.js')
        
        if not message: message = translate("please do not use umlauts")
        # message += translate("?problem")
        message += "[%s]" % channeltype
        message += "{%s}" % page
        
        newchannels_list = self._newchannels_list(cursor, req)
        channels_list = self._channelsconf_list(cursor, req, channeltype)
        channeltypelist = ["all channel types",
                           "data channels", 
                           "radio channels", 
                           "video channels"]

        # passing variables to template
        data = {}
        data['message'] = message
        data['title'] = translate('Channel List')
        data['polaritylist'] = polaritylist
        data['adapterlist'] = self._adapter_list(cursor, req)
        data["channeltype"] = channeltype
        data["channeltypelist"] = channeltypelist
        data['new_datalist'] = newchannels_list
        data['_selection'] = "channeltype="+quote2(channeltype)
        data["_pagenum"] = req.args.get("_pagenum", "0")
        data["_pagesize"] = req.args.get("_pagesize", "10")
        data['datalist'] = Paginator(channels_list, int(data["_pagenum"]), int(data["_pagesize"]))
        data['appends'] = req.perm.has_permission(CHANNELSCONF_VIEW);
        data['author'] = req.authname or ""
        data['_'] = translate
        data['urlencode'] = urlencode
        data['q'] = q

        return ('channelsconf_list.html', data, None)

    # ====================================================================
    
    # ====================================================================
    
    # ====================================================================
        
    #
    # Private methods
    #

    """
      Returns list of the adapter settings
    """
    def _adapter_list(self, cursor, req, defaults = [ 0 ]):
        return tuning_adapter_list(cursor, defaults)
    
    """
      Returns list of the channels.conf
    """
    def _channelsconf_selectby(self, cursor, req, selectby = ['adapter', 'title']):
        view = selectby
        cols = ['adapter', 'title','frequency','polarity','source','symbolrate','vpid', 'apid', 'tpid']
        sql = "SELECT %s FROM recording_channelsconf" % (",".join(cols))
        order_sql = " ORDER BY title, adapter, source LIMIT 11"
        view_vals = []
        view_cols = []
        for col in view:
            if req.args.has_key(col):
                view_vals += [ aff(req.args[col], "recording_channelsconf", col) ]
                view_cols += [ col ]
        if view_cols:
            view_sql = " WHERE " + (" AND ".join([" %s = %%s" % col for col in view_cols ]))
            logg.info("sql = %s", sql + view_sql)
            cursor.execute(sql + view_sql + order_sql, view_vals)
        else:
            logg.info("sql = %s;", sql + order_sql)
            cursor.execute(sql)
        entries = []
        for entry in cursor:
            entry = dict(zip(cols, entry))
            entries.append(entry)
        return entries
    
    def _newchannels_list(self, cursor, req):
        _ = ['adapter', 'title','frequency','polarity','source','symbolrate','vpid', 'apid', 'tpid']
        translate = Translate("channelsconf", req.locale)
        defs = {}
        defs["adapter"] = "0"
        defs["title"] = translate.get("-new-channel", "NEW CHANNEL")
        defs["frequency"] = translate.get("-new-frequency", "12000")
        defs["polarity"] = translate.get("-new-polarity", "H")
        defs["source"] = translate.get("-new-source", "0")
        defs["symbolrate"] = translate.get("-new-symbolrate", "27500")
        defs["vpid"] = translate.get("-new-vpid", "100")
        defs["apid"] = translate.get("-new-apid", "101")
        defs["tpid"] = translate.get("-new-tpid", "100")
        return [ defs ]

    """
      Returns list of the channels.conf
    """
    def _channelsconf_list(self, cursor, req, channeltype = None):
        view = ['adapter']
        cols = ['adapter', 'title','frequency','polarity','source','symbolrate','vpid', 'apid', 'tpid']
        sql = "SELECT %s FROM recording_channelsconf" % (",".join(cols))
        order_sql = " ORDER BY title, adapter, source"
        view_vals = []
        view_cols = []
        type_cols = []
        for col in view:
            if req.args.has_key(col):
                view_vals += [ aff(req.args[col], "recording_channelsconf", col) ]
                view_cols += [ col ]
        if channeltype in [ "audio", "video", "radio channels", "video channels" ]:
            type_cols += ["apid > 0"]
        elif channeltype in [ "data", "data channels"]:
            type_cols += ["apid = 0"]
        if channeltype in [ "video", "video channels" ]:
            type_cols += ["vpid > 0"]
        elif channeltype in [ "audio", "radio channels"]:
            type_cols += ["vpid = 0"]
        if view_cols:
            view_sql = " WHERE " + (" AND ".join([" %s = %%s" % col for col in view_cols ]))
            if type_cols:
                view_sql += " AND " + " AND ".join(type_cols)
            logg.info("sql = %s", sql + view_sql)
            cursor.execute(sql + view_sql + order_sql, view_vals)
        else:
            view_sql = ""
            if type_cols:
                view_sql += " WHERE " + " AND ".join(type_cols)
            logg.info("sql = %s;", sql + order_sql)
            cursor.execute(sql + view_sql + order_sql)
        entries = []
        for entry in cursor:
            entry = dict(zip(cols, entry))
            entries.append(entry)
        return entries

    """
      Appends a new entry into channels.conf list
    """
    def _channelsconf_append(self, cursor, req):
        cols = ['adapter', 'title','frequency','polarity','source','symbolrate','vpid', 'apid', 'tpid']
        vals = [] # { "author" : req.authname or 'anonymous' }
        for col in cols:
            if req.args.has_key(col):
                vals += [ aff(req.args[col], "recording_channel", col) ]
            else:
                vals += [ None ]
        sql = "INSERT INTO recording_channelsconf (%s)" % ",".join(cols)
        sql += " VALUES (%s)" % (",".join(["%s"] * len(cols)))
        cursor.execute(sql, vals)
        return "OK"

    """
      Updates an entry in the channels.conf list
    """
    def _channelsconf_update(self, cursor, req):
        keys = ['adapter', 'title']
        cols = ['frequency','polarity','source','symbolrate','vpid', 'apid', 'tpid']
        rename = { "newtitle" : "title" }
        vals = [] # { "author" : req.authname or 'anonymous' }
        for col in cols:
            if req.args.has_key(col):
                vals += [ aff(req.args[col], "recording_channelsconf", col) ]
            else:
                vals += [ None ] 
        where = []
        for col in keys:
            if req.args.has_key(col):
                where += [ aff(req.args[col], "recording_channelsconf", col) ]
            else:
                where += [ None ]
        for col in rename:
            if req.args.has_key(col):
                col2 = rename[col]
                vals += [ aff(req.args[col2], "recording_channelsconf", col) ]
                cols += col2
        sqlX = ""
        try:
            sql = "UPDATE recording_channelsconf " 
            sql += " SET "+(",".join([" %s = %%s" % col for col in cols]))
            sql += " WHERE " + (" AND ".join([" %s = %%s" % col for col in keys ]))
            sqlX = sql + " | " + str( vals + where )
            cursor.execute(sql, vals + where)
        except Exception, e:
            return "ERROR: %s\n%s" % (str(e), sqlX)
        return "OK"

    """
      Deletes entry from recordings
    """
    def _channelsconf_delete(self, cursor, req):
        keys = ['adapter', 'title']
        key_vals = []
        for col in keys:
            if req.args.has_key(col):
                key_vals += [ aff(req.args[col], "recording_channelsconf", col) ]
            else:
                key_vals += [ None ]
        key_sql = " WHERE " + (" AND ".join([" %s = %%s" % col for col in keys ]))
        cursor.execute("DELETE FROM recording_channelsconf "+key_sql, key_vals)


    # ---------------------------------------------------------------
    def savetext(self, cursor, req, text):
        if not req.args.has_key("adapter"):
            return "no adapter given in update"
        adapter = req.args["adapter"]
        sql = "DELETE FROM recording_channelsconf WHERE adapter = %s"
        cursor.execute(sql, adapter)
        msg = []
        for line in text.split("\n"):
            msg += [ self.savetextline(cursor, req, unicode(line)) ]
        return "(%s lines = %s)" % (len(msg), str(msg))
    def savetextline(self, cursor, req, line):
        cols = ["title", "frequency", "polarity", "source", "symbolrate", "vpid","apid","tpid"]
        # VIVA PLUS:12551:v:0:22000:171:172:12120
        m = re.match(r"([^:]+):([^:]+):([^:]+):([^:]+):([^:]+):([^:]+):([^:]+):([^:]+)", line)
        if m:
            vals = m.groups()
            for n in xrange(len(cols)):
                if n < len(vals):
                    val = vals[n]
                    if val: val = val.strip()
                    req.args[ cols[n] ] = val
            return self._channelsconf_append(cursor, req)
        else:
            return "NO."
    def loadtext(self, cursor, req):
        return "\n".join(list(self.loadtextlines(cursor, req)))
    def loadtextlines(self, cursor, req):
        cols = ["title", "frequency", "polarity", "source", "symbolrate", "vpid","apid","tpid"]
        entries = self._channelsconf_list(cursor, req)
        for entry in entries:
            vals = []
            for col in cols:
                if col in entry:
                    vals += [ ustr(entry[col]) ]
                else:
                    vals += ""
            yield (":".join(vals))
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.