Commits

Guido Draheim committed 7bd548b

core with sql orm

Comments (0)

Files changed (3)

src/dvbcronrecording/computer.py

         past_days = self.get_past_days_this_month()
         logg.info("allowed_months %s" % (str(allowed_months)))    
         for entry in entries:
-            if entry["status"] == "no": 
-                logg.debug("status disabled for %s", entry["title"]) 
+            if entry.status == "no": 
+                logg.debug("status disabled for %s", entry.title) 
                 continue
             item = RecorderItem()
-            item.channelname = entry["channelname"]
-            item.title = entry["title"]
+            item.channelname = entry.channelname
+            item.title = entry.title
             if not item.title:
                 logg.debug("item had not title") 
                 continue            
             if not item.channelname: 
                 logg.debug("no channel name for '%s", item.title) 
                 continue            
-            m = re.match("(\d+)[.](\d+)[.]", entry["onlydate"])
+            m = re.match("(\d+)[.](\d+)[.]", entry.onlydate)
             if m:
-                logg.debug("onlydate %s for %s", entry["onlydate"], item.title)
+                logg.debug("onlydate %s for %s", entry.onlydate, item.title)
                 try:
                     onlyday = intnull(m.group(1))
                     onlymonth = intnull(m.group(2))
                     item.months = [ onlymonth ]
                     logg.info("onlyday %s onlymonths %s for %s", item.onlyday, item.months, item.title)
                 except Exception:
-                    logg.debug("conversion error %s '%s'", entry["onlydate"], item.title)
-                item.weekday = intnull(entry["weekday"])
+                    logg.debug("conversion error %s '%s'", entry.onlydate, item.title)
+                item.weekday = intnull(entry.weekday)
             else: 
-                item.weekday = intnull(entry["weekday"])
+                item.weekday = intnull(entry.weekday)
                 if item.weekday is None:
                     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"]))
+            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 rankup_channels:
                 item.rank += rankup_plus
-            logg.debug("originally %s-%s '%s'" % (entry["newtime"], entry["endtime"], item.title))
+            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))

src/dvbcronrecording/core.py

 
 CHANNELSCONF = "~/.szap/{adapter}/channels.conf"
 
+from db.session import db_cnx, commit #@UnresolvedImport
+from db.schema import RecordingList
+import sqlalchemy as _as
+
 def _(text): return text
 
 from db import schema
         req.perm.assert_permission(LIST_VIEW)
         translate = Translate("core", req.locale, req.languages )
 
-        # getting cursor
-        db = self.env.get_db_cnx()
-        cursor = db.cursor()
         page = req.args['page']
         if not page: page = "list"
         
         if page in [ 'makefile' ]:
             data = {}
             data['title'] = translate("Makefile Overview")
-            data['entries'] = self._makefile_entries(cursor, req)
+            data['entries'] = self._makefile_entries(req)
             data['_'] = translate
             add_stylesheet(req, PACKAGE+'/css/recordinglist.css')
             add_script(req, 'common/js/trac.js')
             data = {}
             data['title'] = translate("Cronfile Overview")
             data['messages'] = [ self.crontabreloadline() ]
-            data['cronlines'] = self._crontablines(cursor, req)
+            data['cronlines'] = self._crontablines(req)
             data['_'] = translate
             add_stylesheet(req, PACKAGE+'/css/recordinglist.css')
             add_script(req, 'common/js/trac.js')
             data['title'] = translate("Recording Plan")
             data['messages'] = [ ]
             data['weekdaynames'] = translate("**weekdaynames")
-            data['recordings'] = self._recording_plan(cursor, req)
+            data['recordings'] = self._recording_plan(req)
             data['_'] = translate
             add_stylesheet(req, PACKAGE+'/css/recordinglist.css')
             add_script(req, 'common/js/trac.js')
         if page in [ 'activate' ]:
             data = {}
             data['title'] = translate("Cron Activate")
-            makefile_entries = self._makefile_entries(cursor, req)
+            makefile_entries = self._makefile_entries(req)
             makefile_list = [ entry.rule for entry in makefile_entries  ]
-            makefile_entries = self._makefile_entries(cursor, req) # FIXME
+            makefile_entries = self._makefile_entries(req) # FIXME
             crontab_lines = self._to_crontablines(makefile_entries)
             crontab_reload = self.crontabreloadline()
             crontab_change = self.crontabchangeline()
             return ('recordingcronfile.html', data, None)
         if page in [ "save" ]:
             text = req.args["text"]
-            result = self.savetext(cursor, req, text)
-            db.commit()
+            result = self.savetext(req, text)
+            commit()
             data = {}
             data['title'] = translate("Save")
             data['messages'] = ['(%s)' % text, result]
-            data['text'] = self.loadtext(cursor, req)
+            data['text'] = self.loadtext(req)
             data['_'] = translate
             add_stylesheet(req, PACKAGE+'/css/recordinglist.css')
             add_script(req, 'common/js/trac.js')
             data = {}
             data['title'] = translate("Edit")
             data['messages'] = ['use the traditional syntax']
-            data['text'] = self.loadtext(cursor, req)
+            data['text'] = self.loadtext(req)
             data['_'] = translate
             add_stylesheet(req, PACKAGE+'/css/recordinglist.css')
             add_script(req, 'common/js/trac.js')
             pass
         if page in [ 'newentry' ]:
             req.perm.assert_permission(LIST_APPEND)
-            message = self._recordings_append(cursor, req)
+            message = self._recordings_append(req)
         if page in [ 'update' ]:
             req.perm.assert_permission(LIST_APPEND)
-            message = self._recordings_update(cursor, req)
+            message = self._recordings_update(req)
         if page in [ 'delete' ]:
             req.perm.assert_permission(LIST_DELETE)
-            message = self._recordings_delete(cursor, req)
+            message = self._recordings_delete(req)
         
         # database commit and return page content
-        db.commit()
+        commit()
 
         add_stylesheet(req, 'common/css/wiki.css')
         add_stylesheet(req, PACKAGE+'/css/recordinglist.css')
         data = {}
         data['message'] = message
         data['title'] = translate('Recordings List')
-        data['recordings'] = self._recordings_list(cursor, req)
+        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(cursor, req))
+        data['defaults'] = list(self._newrecordings_list(req))
         data['weekdaynames'] = translate("**weekdaynames")
         data['statusnames'] = translate("**statusnames")
         data['prioritynames'] = translate("**prioritynames")
-        data['channelnamelist'] = [ "" ] + self._channelname_list(cursor, req)
+        data['channelnamelist'] = [ "" ] + self._channelname_list(req)
         data['_'] = translate
 
         return ('recordinglist.html', data, None)
     """
       Returns list of the adapter settings
     """
-    def _channelname_list(self, cursor, req):
-        return channelname_list(cursor, req)
+    def _channelname_list(self, req):
+        return channelname_list(self.env, req)
     
-    def _newrecordings_list(self, cursor, req):
+    def _newrecordings_list(self, req):
         translate = Translate("core", req.locale)
         channel = translate.get("prime-time-channel", "pro7")
         starts = translate.get("prime-time-start", "20:15")
     """
       Returns list of recordings
     """
-    def _recordings_list(self, cursor, req):
-        cols = ['id', 'channelname','newtime','endtime','extratime','weekday','onlydate','status','priority','title']
-        sql = "SELECT %s FROM recording_list" % (",".join(cols))
-        sql += " ORDER BY weekday, newtime, endtime, status"
-        cursor.execute(sql)
-        entries = []
-        for entry in cursor:
-            entry = dict(zip(cols, entry))
-            entries.append(entry)
-        return entries
+    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, cursor, req):
-        cols = ['id', 'channelname','newtime','endtime','extratime','weekday','onlydate','status','priority','title']
-        vals = [] # { "author" : req.authname or 'anonymous' }
-        for col in cols:
-            if req.args.has_key(col):
-                vals += [ aff(req.args[col], "recording_list", col) ]
-            else:
-                vals += [ None ]
-        sql = "INSERT INTO recording_list (%s)" % ",".join(cols)
-        sql += " VALUES (%s)" % (",".join(["%s"] * len(cols)))
-        cursor.execute(sql, vals)
-        return u"OK"
+    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)
+        session.flush()
+        return u"OK [rec:%s]" % item.id
 
     """
       Updates an entry in the list
     """
-    def _recordings_update(self, cursor, req):
-        cols = ['channelname','newtime','endtime','extratime','weekday','onlydate','status','priority','title']
-        vals = [] # { "author" : req.authname or 'anonymous' }
-        for col in cols:
-            if req.args.has_key(col):
-                vals += [ aff(req.args[col], "recording_list", col) ]
-            else:
-                vals += [ None ] 
-        sqlX = ""
-        try:
-            id = int(req.args["id"])
-            if not id: return "ERROR: no id given"
-            sql = "UPDATE recording_list " 
-            sql += " SET "+(",".join([" %s = %%s" % col for col in cols]))
-            sql += " WHERE id = %s"
-            sqlX = sql + " | " + str( vals + [ id ] )
-            cursor.execute(sql, vals + [ id ])
-        except Exception, e:
-            return u"ERROR: %s\n%s" % (str(e), sqlX)
-        return u"OK"
+    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")
+        session.flush()
+        return u"OK [rec:%s]" % item.id
 
     """
       Deletes entry from recordings
     """
-    def _recordings_delete(self, cursor, req):
-        id = int(req.args["id"])
-        cursor.execute("DELETE FROM recording_list WHERE id = %s", [ id ])
+    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, cursor, req, text):
+    def savetext(self, req, text):
         translate = Translate("core", req.locale)
         msgs = []
         for line in text.split("\n"):
             if line.startswith("+"):
-                msgs += [ self.savetextline(cursor, req, line) ]
+                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, cursor, req, line):
+    def savetextline(self, req, line):
         m = re.match(r"[+](\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.*)[!]", line)
         if m:
             channel = m.group(1)
             else: req.args["onlydate"] = ""
             req.args["title"] = title
             req.args["status"] = u"ok" 
-            return self._recordings_append(cursor, req)
+            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, cursor, req):
-        return "\n".join(list(self.loadtextlines(cursor, req)))
-    def loadtextlines(self, cursor, req):
-        entries = self._recordings_list(cursor, req)
+    def loadtext(self, req):
+        return "\n".join(list(self.loadtextlines(req)))
+    def loadtextlines(self, req):
+        entries = self._recordings_list(req)
         computer = TracSimpleRecorderComputer()
         plan = computer.plan(entries)
         for group in plan.groups():
                 yield "+%(channel)s %(newtime)s %(end)s %(day)s %(filename)s!" % locals()
             yield "> %s" % xx
         
-    def _loadtextlines(self, cursor, req):
-        entries = self._recordings_list(cursor, req)
+    def _loadtextlines(self, req):
+        entries = self._recordings_list(req)
         startchain = self._entries_to_startchain(entries)
         for chain in startchain:
             entry = chain.entry
     # ---------------------------------------------------------------
     # chain up the entries
     # ---------------------------------------------------------------
-    def _recording_plan(self, cursor, req):
-        entries = self._recordings_list(cursor, req)
+    def _recording_plan(self, req):
+        entries = self._recordings_list(req)
         return list(self._recording_plan_from(entries))
     def _recording_plan_from(self, entries):
         computer = TracSimpleRecorderComputer()
     """ 
         This is doing the actual computations
     """
-    def _makefile_entries(self, cursor, req):
-        entries = self._recordings_list(cursor, req)
+    def _makefile_entries(self, req):
+        entries = self._recordings_list(req)
         computer = TracSimpleRecorderComputer()
         plan = computer.plan(entries)
         for group in plan.groups():
                 adapter = item.tuning_adapter
                 channel = item.tuning_channel
                 if not adapter: adapter = "0"
-                for tuning in channelname_to_channelconflist(cursor, req, channelname):
+                for tuning in channelname_to_channelconflist(req, channelname):
                     # TODO: allow to change the adapter
                     if tuning.adapter != adapter: continue
                     if tuning.channel: channel = tuning.channel                
                 if ":" in adapter:
                     adapter, frontend = adapter.split(":",1)
                 if not channel: channel = item.channelname
-                channelsconf = self.channelsconf_filename(cursor, adapter)
+                channelsconf = self.channelsconf_filename(adapter)
                 format = "%Y%m%d-"+ustr(adapter)+"%a-%H%M"
                 prefix = self.intodir+"/"
                 cmd = [ u"gnutv -adapter %(adapter)s -frontend %(frontend)s" ]
             make.start = startname 
             yield make
             
-    def _crontablines(self, cursor, req):
-        return self._to_crontablines(self._makefile_entries(cursor, req))
+    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, 
     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 channelsconf_filename(self, cursor, adapter):
+    def channelsconf_filename(self, adapter):
         channelsconf = self.channelsconf
         if DvbCronRecordingTuningPlugin is not None:
             tuning = DvbCronRecordingTuningPlugin(self.compmgr)
-            found = tuning.channelsconf_from_adapter(cursor, adapter)
+            found = tuning.channelsconf_from_adapter(adapter)
             if found: channelsconf = found
         user = self.recordinguser
         channelsconf = channelsconf.replace("~/", "~{user}/")

src/dvbcronrecording/db/schema.py

 RecordingTuning = db4.RecordingTuning
 RecordingChannels = db4.RecordingChannels
 RecordingChannelsConf = db4.RecordingChannelsConf
+RecordingList = db4.RecordingList
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.