def keyOK(self): if self.modus == "list": if self.loading: return check = self['menu_list'].getCurrent() if check is None: return (serien_name, serien_id) = self.getSeriesNameID() if config.plugins.serienRec.activateNewOnThisSTBOnly.value: boxID = None else: boxID = config.plugins.serienRec.BoxID.value if self.database.addMarker(str(serien_id), serien_name, '', boxID, 0): SRLogger.writeLog("\nSerien Marker für ' %s ' wurde angelegt" % serien_name, True) self['title'].setText("Serie '- %s -' zum Serien Marker hinzugefügt." % serien_name) self['title'].instance.setForegroundColor(parseColor("green")) if config.plugins.serienRec.tvplaner_full_check.value: config.plugins.serienRec.tvplaner_last_full_check.value = int(0) config.plugins.serienRec.tvplaner_last_full_check.save() SerienRecorder.configfile.save() if config.plugins.serienRec.openMarkerScreen.value: from SerienRecorderMarkerScreen import serienRecMarker self.session.open(serienRecMarker, serien_name) else: self['title'].setText("Serie '- %s -' existiert bereits im Serien Marker." % serien_name) self['title'].instance.setForegroundColor(parseColor("red"))
def createDirectory(cls, serien_name, dirname, dirname_serie, cover_only=False): from SerienRecorderLogWriter import SRLogger serien_name = doReplaces(serien_name) # dirname = doReplaces(dirname) # dirname_serie = doReplaces(dirname_serie) if not fileExists(dirname) and not cover_only: print "[SerienRecorder] Erstelle Verzeichnis %s" % dirname SRLogger.writeLog("Erstelle Verzeichnis: ' %s '" % dirname) try: os.makedirs(dirname) except OSError as e: SRLogger.writeLog("Fehler beim Erstellen des Verzeichnisses: %s" % e.strerror) # if e.errno != 17: # raise # Copy cover only if path exists and series sub dir is activated if fileExists(dirname) and config.plugins.serienRec.seriensubdir.value and config.plugins.serienRec.copyCoverToFolder.value: if fileExists("%s%s.jpg" % (config.plugins.serienRec.coverPath.value, serien_name)) and not fileExists("%sfolder.jpg" % dirname_serie): shutil.copyfile("%s%s.jpg" % (config.plugins.serienRec.coverPath.value, serien_name), "%sfolder.jpg" % dirname_serie) if config.plugins.serienRec.seasonsubdir.value: covername = "series" if config.plugins.serienRec.copyCoverToFolder.value is "1": covername = "folder" if fileExists("%s%s.jpg" % (config.plugins.serienRec.coverPath.value, serien_name)) and not fileExists("%s%s.jpg" % (dirname, covername)): shutil.copyfile("%s%s.jpg" % (config.plugins.serienRec.coverPath.value, serien_name), "%s%s.jpg" % (dirname, covername))
def createDirectory(cls, serien_name, dirname, dirname_serie, cover_only=False): from SerienRecorderLogWriter import SRLogger serien_name = doReplaces(serien_name) # dirname = doReplaces(dirname) # dirname_serie = doReplaces(dirname_serie) if not fileExists(dirname) and not cover_only: print "[SerienRecorder] Erstelle Verzeichnis %s" % dirname SRLogger.writeLog("Erstelle Verzeichnis: ' %s '" % dirname) try: os.makedirs(dirname) except OSError as e: SRLogger.writeLog("Fehler beim Erstellen des Verzeichnisses: %s" % e.strerror) # if e.errno != 17: # raise # Copy cover only if path exists and series sub dir is activated if fileExists(dirname) and config.plugins.serienRec.seriensubdir.value and config.plugins.serienRec.copyCoverToFolder.value: if fileExists("%s%s.jpg" % (config.plugins.serienRec.coverPath.value, serien_name)) and not fileExists("%sfolder.jpg" % dirname_serie): shutil.copyfile("%s%s.jpg" % (config.plugins.serienRec.coverPath.value, serien_name), "%sfolder.jpg" % dirname_serie) if config.plugins.serienRec.seasonsubdir.value: covername = "series" if config.plugins.serienRec.copyCoverToFolder.value is "1": covername = "folder" if fileExists("%s%s.jpg" % (config.plugins.serienRec.coverPath.value, serien_name)) and not fileExists("%s%s.jpg" % (dirname, covername)): shutil.copyfile("%s%s.jpg" % (config.plugins.serienRec.coverPath.value, serien_name), "%s%s.jpg" % (dirname, covername))
def checkChannels(self): channels = self.database.getChannels(True) if config.plugins.serienRec.selectBouquets.value: stbChannelList = STBHelpers.buildSTBChannelList(config.plugins.serienRec.MainBouquet.value) else: stbChannelList = STBHelpers.buildSTBChannelList() stbServiceRefs = [x[1] for x in stbChannelList] serviceRefs = [x[2] for x in channels] missingServiceRefs = [] missingServices = [] for serviceRef in serviceRefs: if serviceRef not in stbServiceRefs: missingServiceRefs.append(serviceRef) for missingServiceRef in missingServiceRefs: for channel in channels: (webSender, servicename, serviceref, altservicename, altserviceref, status) = channel if serviceref is missingServiceRef and servicename and int(status) != 0: missingServices.append(servicename) SRLogger.writeLog("%s => %s" % (missingServiceRef, servicename), True) break if missingServices: self.session.open(MessageBox, "Für folgende Sender existiert die ServiceRef nicht mehr,\nbitte die Sender neu zuweisen:\n\n" + "\n".join(missingServices), MessageBox.TYPE_INFO, timeout=0) else: self.session.open(MessageBox, "Alle zugewiesenen Sender sind noch vorhanden.", MessageBox.TYPE_INFO, timeout=7)
def run(self): try: from SerienRecorderSeriesServer import SeriesServer self.planerData = SeriesServer().doGetPlanerData( self.daypage, self.webChannels) except: SRLogger.writeLog( "Fehler beim Abrufen und Verarbeiten der SerienPlaner-Daten [%s]\n" % str(self.daypage), True)
def setEPGRefreshCallback(self, configentry = None): try: if self.epgrefresh_instance: if config.plugins.serienRec.autochecktype.value == "2": self.epgrefresh_instance.addFinishNotifier(self.startCheck) else: self.epgrefresh_instance.removeFinishNotifier(self.startCheck) except Exception as e: try: from Tools.HardwareInfoVu import HardwareInfoVu pass except: SRLogger.writeLog("Um die EPGRefresh Optionen nutzen zu können, muss mindestens die EPGRefresh Version 2.1.1 installiert sein. " + str(e), True)
def getCover(self, serien_name, serien_id, auto_check = False, forceReload = False): if not config.plugins.serienRec.downloadCover.value: return serien_name = doReplaces(serien_name.encode('utf-8')) serien_nameCover = "%s%s.jpg" % (config.plugins.serienRec.coverPath.value, serien_name) png_serien_nameCover = "%s%s.png" % (config.plugins.serienRec.coverPath.value, serien_name) try: if self and config.plugins.serienRec.showCover.value: self['cover'].hide() global coverToShow coverToShow = serien_nameCover if not fileExists(config.plugins.serienRec.coverPath.value): try: os.mkdir(config.plugins.serienRec.coverPath.value) except: Notifications.AddPopup("Cover Pfad (%s) kann nicht angelegt werden.\n\nÜberprüfen Sie den Pfad und die Rechte!" % config.plugins.serienRec.coverPath.value, MessageBox.TYPE_INFO, timeout=10, id="checkFileAccess") # Change PNG cover file extension to correct file extension JPG if fileExists(png_serien_nameCover): os.rename(png_serien_nameCover, serien_nameCover) if forceReload: os.remove(serien_nameCover) if config.plugins.serienRec.refreshPlaceholderCover.value and fileExists(serien_nameCover) and os.path.getsize(serien_nameCover) == 0: statinfo = os.stat(serien_nameCover) if (statinfo.st_ctime + 5184000) <= time.time(): # Older than 60 days os.remove(serien_nameCover) if fileExists(serien_nameCover): if self and config.plugins.serienRec.showCover.value: showCover(serien_nameCover, self, serien_nameCover) elif serien_id and (config.plugins.serienRec.showCover.value or (config.plugins.serienRec.downloadCover.value and auto_check)): try: posterURL = SeriesServer().doGetCoverURL(int(serien_id), serien_name) #writeLog("Cover URL [%s] => %s" % (serien_name, posterURL), True) if posterURL: from twisted.web.client import downloadPage downloadPage(posterURL, serien_nameCover).addCallback(showCover, self, serien_nameCover, False).addErrback(getCoverDataError, self, serien_nameCover) else: if config.plugins.serienRec.createPlaceholderCover.value: open(serien_nameCover, "a").close() except: if config.plugins.serienRec.createPlaceholderCover.value: open(serien_nameCover, "a").close() getCoverDataError("failed", self, serien_nameCover) except: SRLogger.writeLog("Fehler bei Laden des Covers: %s " % serien_nameCover, True)
def createBackup(): import SerienRecorder from SerienRecorderLogWriter import SRLogger from SerienRecorderTVPlaner import SERIENRECORDER_TVPLANER_HTML_FILENAME lt = time.localtime() # Remove old backups if config.plugins.serienRec.deleteBackupFilesOlderThan.value > 0: SRLogger.writeLog( "\nEntferne alte Backup-Dateien und erzeuge neues Backup.", True) now = time.time() logFolderPattern = re.compile('\d{4}\d{2}\d{2}\d{2}\d{2}') for root, dirs, files in os.walk( config.plugins.serienRec.BackupPath.value, topdown=False): for name in dirs: if logFolderPattern.match(name) and os.stat( os.path.join(root, name)).st_ctime < ( now - config.plugins.serienRec. deleteBackupFilesOlderThan.value * 24 * 60 * 60): shutil.rmtree(os.path.join(root, name), True) SRLogger.writeLog( "Lösche Ordner: %s" % os.path.join(root, name), True) else: SRLogger.writeLog("Erzeuge neues Backup", True) BackupPath = "%s%s%s%s%s%s/" % ( config.plugins.serienRec.BackupPath.value, lt.tm_year, str( lt.tm_mon).zfill(2), str(lt.tm_mday).zfill(2), str( lt.tm_hour).zfill(2), str(lt.tm_min).zfill(2)) if not os.path.exists(BackupPath): try: os.makedirs(BackupPath) except: pass if os.path.isdir(BackupPath): try: if fileExists(SerienRecorder.serienRecDataBaseFilePath): from SerienRecorderDatabase import SRDatabase database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) database.backup(BackupPath) if fileExists(SRLogger.getLogFilePath()): shutil.copy(SRLogger.getLogFilePath(), BackupPath) if fileExists("/etc/enigma2/timers.xml"): shutil.copy("/etc/enigma2/timers.xml", BackupPath) if fileExists("%sConfig.backup" % SerienRecorder.serienRecMainPath): shutil.copy( "%sConfig.backup" % SerienRecorder.serienRecMainPath, BackupPath) STBHelpers.saveEnigmaSettingsToFile(BackupPath) for filename in os.listdir(BackupPath): os.chmod(os.path.join(BackupPath, filename), 0o777) if fileExists(SERIENRECORDER_TVPLANER_HTML_FILENAME % config.plugins.serienRec.LogFilePath.value): shutil.copy( SERIENRECORDER_TVPLANER_HTML_FILENAME % config.plugins.serienRec.LogFilePath.value, BackupPath) except Exception, e: SRLogger.writeLog("Backup konnte nicht erstellt werden: " + str(e), True)
def readPlanerData(self, answer=True): print "[SerienRecorder] readPlanerData" if not showMainScreen: self.keyCancel() self.close() return self.loading = True cache = serienRecSeriesPlanner.loadPlanerData( config.plugins.serienRec.screenplaner.value) if answer: cache.clear() self.setHeadline() self['title'].instance.setForegroundColor(parseColor("foreground")) lt = datetime.datetime.now() if config.plugins.serienRec.screenplaner.value == 1: lt += datetime.timedelta(days=self.page) key = time.strftime('%d.%m.%Y', lt.timetuple()) if key in cache: try: self['title'].setText("Lade Infos vom Speicher...") if config.plugins.serienRec.screenplaner.value == 1: self.processPlanerData(cache[key], True) else: self.processTopThirty(cache[key], True) except: SRLogger.writeLog( "Fehler beim Abrufen und Verarbeiten der Daten\n", True) else: self['title'].setText("Lade Infos vom Web...") webChannels = self.database.getActiveChannels() try: if config.plugins.serienRec.screenplaner.value == 1: planerData = SeriesServer().doGetPlanerData( int(self.page), webChannels) self.processPlanerData(planerData, False) else: topThirtyData = SeriesServer().doGetTopThirty() self.processTopThirty(topThirtyData, False) except: SRLogger.writeLog( "Fehler beim Abrufen und Verarbeiten der Daten\n", True)
def resetTVPlanerHTMLBackup(): if config.plugins.serienRec.tvplaner.value and config.plugins.serienRec.tvplaner_backupHTML.value: logFile = SERIENRECORDER_TVPLANER_HTML_FILENAME % config.plugins.serienRec.LogFilePath.value if not config.plugins.serienRec.longLogFileName.value: # logFile leeren (renamed to .old) if fileExists(logFile): shutil.move(logFile, "%s.old" % logFile) else: lt = datetime.datetime.now() - datetime.timedelta(days=config.plugins.serienRec.deleteLogFilesOlderThan.value) for filename in os.listdir(config.plugins.serienRec.LogFilePath.value): if (filename.find('TV-Planer_') == 0) and (int(os.path.getmtime(os.path.join(config.plugins.serienRec.LogFilePath.value, filename))) < int(lt.strftime("%s"))): try: os.remove('%s%s' % (config.plugins.serienRec.LogFilePath.value, filename)) except: SRLogger.writeLog("TV-Planer HTML Backup konnte nicht gelöscht werden: %s" % os.path.join(config.plugins.serienRec.LogFilePath.value, filename), True) open(logFile, 'w').close()
def channelReset(self, execute): if execute: print "[SerienRecorder] channel-list reset..." SRLogger.writeLog("Senderliste wird aktualisiert...") if config.plugins.serienRec.selectBouquets.value: self.stbChannelList = STBHelpers.buildSTBChannelList(config.plugins.serienRec.MainBouquet.value) else: self.stbChannelList = STBHelpers.buildSTBChannelList() self['title'].setText("Lade Wunschliste-Sender...") try: self.createWebChannels(SeriesServer().doGetWebChannels(), False) self.database.setChannelListLastUpdate() except: self['title'].setText("Fehler beim Laden der Wunschliste-Sender") SRLogger.writeLog("Fehler beim Laden der Senderliste vom SerienServer.", True) else: print "[SerienRecorder] channel-list ok."
def readPlanerData(self, answer=True): print "[SerienRecorder] readPlanerData" if not showMainScreen: self.keyCancel() self.close() return self.loading = True cache = serienRecSeriesPlanner.loadPlanerData(config.plugins.serienRec.screenplaner.value) if answer: cache.clear() self.setHeadline() self['title'].instance.setForegroundColor(parseColor("foreground")) lt = datetime.datetime.now() if config.plugins.serienRec.screenplaner.value == 1: lt += datetime.timedelta(days=self.page) key = time.strftime('%d.%m.%Y', lt.timetuple()) if key in cache: try: self['title'].setText("Lade Infos vom Speicher...") if config.plugins.serienRec.screenplaner.value == 1: self.processPlanerData(cache[key], True) else: self.processTopThirty(cache[key], True) except: SRLogger.writeLog("Fehler beim Abrufen und Verarbeiten der Daten\n", True) else: self['title'].setText("Lade Infos vom Web...") webChannels = self.database.getActiveChannels() try: if config.plugins.serienRec.screenplaner.value == 1: planerData = SeriesServer().doGetPlanerData(int(self.page), webChannels) self.processPlanerData(planerData, False) else: topThirtyData = SeriesServer().doGetTopThirty() self.processTopThirty(topThirtyData, False) except: SRLogger.writeLog("Fehler beim Abrufen und Verarbeiten der Daten\n", True)
def addTimerToDB(self, serien_name, staffel, episode, title, start_time, stbRef, webChannel, eit, addToDatabase, TimerAktiviert=True): seasonEpisodeString = "S%sE%s" % (str(staffel).zfill(2), str(episode).zfill(2)) if not addToDatabase: print "[SerienRecorder] Timer angelegt: %s %s - %s" % (serien_name, seasonEpisodeString, title) SRLogger.writeLogFilter("timerDebug", " Timer angelegt: %s %s - %s" % (serien_name, seasonEpisodeString, title)) else: (margin_before, margin_after) = self.database.getMargins(serien_name, webChannel, config.plugins.serienRec.margin_before.value, config.plugins.serienRec.margin_after.value) timerStartTime = int(start_time) + (int(margin_before) * 60) - (int(STBHelpers.getEPGTimeSpan()) * 60) if self.database.timerExistsByServiceRef(serien_name, stbRef, timerStartTime, timerStartTime): self.database.updateTimerEIT(serien_name, stbRef, eit, timerStartTime, timerStartTime, TimerAktiviert) print "[SerienRecorder] Timer bereits vorhanden: %s %s - %s" % (serien_name, seasonEpisodeString, title) SRLogger.writeLog(" Timer bereits vorhanden: %s %s - %s" % (serien_name, seasonEpisodeString, title)) else: self.database.addToTimerList(serien_name, episode, episode, staffel, title, start_time, stbRef, webChannel, eit, TimerAktiviert) print "[SerienRecorder] Timer angelegt: %s %s - %s" % (serien_name, seasonEpisodeString, title) SRLogger.writeLogFilter("timerDebug", " Timer angelegt: %s %s - %s" % (serien_name, seasonEpisodeString, title))
def updatePlanerData(self): webChannels = self.database.getActiveChannels() SRLogger.writeLog("\nLaden der SerienPlaner-Daten gestartet ...", True) markers = self.database.getAllMarkers( config.plugins.serienRec.BoxID.value) downloadPlanerDataResults = [] for daypage in range( int(config.plugins.serienRec.planerCacheSize.value)): planerData = downloadPlanerData(int(daypage), webChannels) downloadPlanerDataResults.append(planerData) planerData.start() try: for planerDataThread in downloadPlanerDataResults: planerDataThread.join() if not planerDataThread.getData(): continue (daypage, planerData) = planerDataThread.getData() self.processPlanerData(planerData, markers, daypage) self.postProcessPlanerData() except: SRLogger.writeLog( "Fehler beim Abrufen oder Verarbeiten der SerienPlaner-Daten") SRLogger.writeLog("... Laden der SerienPlaner-Daten beendet\n", True)
def updatePlanerData(self): webChannels = self.database.getActiveChannels() SRLogger.writeLog("\nLaden der SerienPlaner-Daten gestartet ...", True) markers = self.database.getAllMarkers(config.plugins.serienRec.BoxID.value) downloadPlanerDataResults = [] for daypage in range(int(config.plugins.serienRec.planerCacheSize.value)): planerData = downloadPlanerData(int(daypage), webChannels) downloadPlanerDataResults.append(planerData) planerData.start() try: for planerDataThread in downloadPlanerDataResults: planerDataThread.join() if not planerDataThread.getData(): continue (daypage, planerData) = planerDataThread.getData() self.processPlanerData(planerData, markers, daypage) self.postProcessPlanerData() except: SRLogger.writeLog("Fehler beim Abrufen oder Verarbeiten der SerienPlaner-Daten") SRLogger.writeLog("... Laden der SerienPlaner-Daten beendet\n", True)
def startScreen(self): print "[SerienRecorder] version %s is running..." % config.plugins.serienRec.showversion.value if not SerienRecorder.refreshTimer: if config.plugins.serienRec.timeUpdate.value: SerienRecorder.serienRecCheckForRecording( self.session, False, False) if not SerienRecorder.initDB(): print "[SerienRecorder] initDB failed" super(self.__class__, self).close() self.database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) if not self.database.hasChannels(): print "[SerienRecorder] Channellist is empty !" from SerienRecorderChannelScreen import serienRecMainChannelEdit self.session.openWithCallback(self.readPlanerData, serienRecMainChannelEdit) else: self.serviceRefs = self.database.getActiveServiceRefs() remoteChannelListLastUpdated = SeriesServer.getChannelListLastUpdate( ) channelListUpToDate = True if remoteChannelListLastUpdated: localChannelListLastUpdated = self.database.getChannelListLastUpdate( ) if 0 < localChannelListLastUpdated < remoteChannelListLastUpdated: SRLogger.writeLog( "Auf dem Serien-Server wurde die Senderliste aktualisiert - bitte führen Sie auch eine Aktualisierung in der Senderzuordnung aus.", True) channelListUpToDate = False if channelListUpToDate: self.switchStartScreen() else: self.session.openWithCallback( self.handleChannelListUpdate, MessageBox, "Die Senderliste wurde auf dem Server aktualisiert.\nSie muss auch im SerienRecorder aktualisiert werden.\nWechseln Sie zur Senderzuordnung und aktualisieren Sie die Senderliste mit der grünen Taste.\n\nZur Senderzuordnung wechseln?", MessageBox.TYPE_YESNO)
def keyOK(self): if self.loading: return check = self['menu_list'].getCurrent() if check is None: print "[SerienRecorder] keine infos gefunden" return Serie = self['menu_list'].getCurrent()[0][0] Year = self['menu_list'].getCurrent()[0][1] Id = self['menu_list'].getCurrent()[0][2] print Serie, Year, Id if Id == "": return if Id == "-1": self.chooseMenuList.setList([]) self.searchSerie(int(Year)) return self.serien_name = "" database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) if config.plugins.serienRec.activateNewOnThisSTBOnly.value: boxID = None else: boxID = config.plugins.serienRec.BoxID.value if database.addMarker(str(Id), Serie, Year, boxID, 0): from SerienRecorderLogWriter import SRLogger SRLogger.writeLog("\nSerien Marker für ' %s ' wurde angelegt" % Serie, True) self['title'].setText("Serie '- %s -' zum Serien Marker hinzugefügt." % Serie) self['title'].instance.setForegroundColor(parseColor("green")) if config.plugins.serienRec.openMarkerScreen.value: self.close(Serie) else: self['title'].setText("Serie '- %s -' existiert bereits im Serien Marker." % Serie) self['title'].instance.setForegroundColor(parseColor("red"))
def keyOK(self): if self.modus == "list": if self.loading: return check = self['menu_list'].getCurrent() if check is None: return (serien_name, serien_id) = self.getSeriesNameID() if config.plugins.serienRec.activateNewOnThisSTBOnly.value: boxID = None else: boxID = config.plugins.serienRec.BoxID.value if self.database.addMarker(str(serien_id), serien_name, '', boxID, 0): SRLogger.writeLog( "\nSerien Marker für ' %s ' wurde angelegt" % serien_name, True) self['title'].setText( "Serie '- %s -' zum Serien Marker hinzugefügt." % serien_name) self['title'].instance.setForegroundColor(parseColor("green")) if config.plugins.serienRec.tvplaner_full_check.value: config.plugins.serienRec.tvplaner_last_full_check.value = int( 0) config.plugins.serienRec.tvplaner_last_full_check.save() SerienRecorder.configfile.save() if config.plugins.serienRec.openMarkerScreen.value: from SerienRecorderMarkerScreen import serienRecMarker self.session.open(serienRecMarker, serien_name) else: self['title'].setText( "Serie '- %s -' existiert bereits im Serien Marker." % serien_name) self['title'].instance.setForegroundColor(parseColor("red"))
def autostart(reason, **kwargs): if reason == 0 and "session" in kwargs: session = kwargs["session"] global startTimer global startTimerConnection global autoCheckFinished lt = time.localtime() uhrzeit = time.strftime("%d.%m.%Y - %H:%M:%S", lt) SRLogger.writeLog("\nSerienRecorder Start: %s" % uhrzeit, True) def startAutoCheckTimer(): serienRecCheckForRecording(session, False, False) if config.plugins.serienRec.autochecktype.value in ("1", "2") and config.plugins.serienRec.timeUpdate.value: print "[SerienRecorder] Auto-Check: AN" startTimer = eTimer() if isDreamOS(): startTimerConnection = startTimer.timeout.connect(startAutoCheckTimer) else: startTimer.callback.append(startAutoCheckTimer) startTimer.start(60 * 1000, True) else: print "[SerienRecorder] Auto-Check: AUS"
def getCoverDataError(error, self, serien_nameCover): if self is not None and self.ErrorMsg: SRLogger.writeLog("Fehler bei: %s (%s)" % (self.ErrorMsg, serien_nameCover), True) print "[SerienRecorder] Fehler bei: %s" % self.ErrorMsg else: ErrorMsg = "Cover-Suche (%s) auf 'Wunschliste.de' erfolglos" % serien_nameCover SRLogger.writeLog("Fehler: %s" % ErrorMsg, True) print "[SerienRecorder] Fehler: %s" % ErrorMsg SRLogger.writeLog(" %s" % str(error), True) print error
def createBackup(): import SerienRecorder from SerienRecorderLogWriter import SRLogger lt = time.localtime() # Remove old backups if config.plugins.serienRec.deleteBackupFilesOlderThan.value > 0: SRLogger.writeLog("\nEntferne alte Backup-Dateien und erzeuge neues Backup.", True) now = time.time() logFolderPattern = re.compile('\d{4}\d{2}\d{2}\d{2}\d{2}') for root, dirs, files in os.walk(config.plugins.serienRec.BackupPath.value, topdown=False): for name in dirs: if logFolderPattern.match(name) and os.stat(os.path.join(root, name)).st_ctime < (now - config.plugins.serienRec.deleteBackupFilesOlderThan.value * 24 * 60 * 60): shutil.rmtree(os.path.join(root, name), True) SRLogger.writeLog("Lösche Ordner: %s" % os.path.join(root, name), True) else: SRLogger.writeLog("Erzeuge neues Backup", True) BackupPath = "%s%s%s%s%s%s/" % (config.plugins.serienRec.BackupPath.value, lt.tm_year, str(lt.tm_mon).zfill(2), str(lt.tm_mday).zfill(2), str(lt.tm_hour).zfill(2), str(lt.tm_min).zfill(2)) if not os.path.exists(BackupPath): try: os.makedirs(BackupPath) except: pass if os.path.isdir(BackupPath): try: if fileExists(SerienRecorder.serienRecDataBaseFilePath): from SerienRecorderDatabase import SRDatabase database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) database.backup(BackupPath) if fileExists(SRLogger.getLogFilePath()): shutil.copy(SRLogger.getLogFilePath(), BackupPath) if fileExists("/etc/enigma2/timers.xml"): shutil.copy("/etc/enigma2/timers.xml", BackupPath) if fileExists("%sConfig.backup" % SerienRecorder.serienRecMainPath): shutil.copy("%sConfig.backup" % SerienRecorder.serienRecMainPath, BackupPath) STBHelpers.saveEnigmaSettingsToFile(BackupPath) for filename in os.listdir(BackupPath): os.chmod(os.path.join(BackupPath, filename), 0o777) except Exception, e: SRLogger.writeLog("Backup konnte nicht erstellt werden: " + str(e), True)
def checkFinal(self): print "[SerienRecorder] checkFinal" # final processing if config.plugins.serienRec.tvplaner.value and config.plugins.serienRec.tvplaner_movies.value: # remove all serien markers created for movies try: self.database.removeMovieMarkers() print "[SerienRecorder] ' TV-Planer FilmMarker gelöscht '" except: SRLogger.writeLog("' TV-Planer FilmMarker löschen fehlgeschlagen '", True) print "[SerienRecorder] ' TV-Planer FilmMarker löschen fehlgeschlagen '" global transmissionFailed if transmissionFailed: # always do fullcheck after transmission error config.plugins.serienRec.tvplaner_last_full_check.value = int(0) config.plugins.serienRec.tvplaner_last_full_check.save() configfile.save() if config.plugins.serienRec.AutoBackup.value == "after": createBackup() from SerienRecorderTVPlaner import backupTVPlanerHTML backupTVPlanerHTML() # trigger read of log file global autoCheckFinished autoCheckFinished = True print "[SerienRecorder] checkFinal: autoCheckFinished" if config.plugins.serienRec.autochecktype.value == "1": lt = time.localtime() deltatime = self.getNextAutoCheckTimer(lt) SRLogger.writeLog("\nVerbleibende Zeit bis zum nächsten Auto-Check: %s Stunden\n" % TimeHelpers.td2HHMMstr(datetime.timedelta(minutes=deltatime+int(config.plugins.serienRec.maxDelayForAutocheck.value))), True) if config.plugins.serienRec.tvplaner_full_check.value: autoCheckDays = ((int(config.plugins.serienRec.tvplaner_last_full_check.value) + (int(config.plugins.serienRec.checkfordays.value) - 1) * 86400) - int(time.time())) / 86400 if autoCheckDays < 0: autoCheckDays = 0 SRLogger.writeLog("Verbleibende Zeit bis zum nächsten vollen Auto-Check: %d Tage" % autoCheckDays, True) self.tempDB = None self.database = None # in den deep-standby fahren. self.askForDSB()
def gotoDeepStandby(self, answer): if answer: if config.plugins.serienRec.afterAutocheck.value == "2": if not NavigationInstance.instance.RecordTimer.isRecording(): for each in self.messageList: Notifications.RemovePopup(each[3]) print "[SerienRecorder] gehe in Deep-Standby" SRLogger.writeLog("gehe in Deep-Standby") if Screens.Standby.inStandby: from RecordTimer import RecordTimerEntry RecordTimerEntry.TryQuitMainloop() else: Notifications.AddNotificationWithID("Shutdown", Screens.Standby.TryQuitMainloop, 1) else: print "[SerienRecorder] Eine laufende Aufnahme verhindert den Deep-Standby" SRLogger.writeLog("Eine laufende Aufnahme verhindert den Deep-Standby") else: print "[SerienRecorder] gehe in Standby" SRLogger.writeLog("gehe in Standby") Notifications.AddNotification(Screens.Standby.Standby)
def processTransmission(self, data, serien_id, serien_name, staffeln, AbEpisode, AnzahlAufnahmen, current_time, future_time, excludedWeekdays=None): print "[SerienRecorder] processTransmissions: %r" % serien_name self.count_url += 1 if data is None: SRLogger.writeLog("Fehler beim Abrufen und Verarbeiten der Ausstrahlungstermine [%s]" % serien_name, True) #print "[SerienRecorder] processTransmissions: no Data" return (fromTime, toTime) = self.database.getTimeSpan(serien_name, config.plugins.serienRec.globalFromTime.value, config.plugins.serienRec.globalToTime.value) if self.noOfRecords < AnzahlAufnahmen: self.noOfRecords = AnzahlAufnahmen TimeSpan_time = int(future_time) if config.plugins.serienRec.forceRecording.value: TimeSpan_time += (int(config.plugins.serienRec.TimeSpanForRegularTimer.value) - int(config.plugins.serienRec.checkfordays.value)) * 86400 # loop over all transmissions self.tempDB.beginTransaction() for current_serien_name, sender, startzeit, endzeit, staffel, episode, title, status in data: start_unixtime = startzeit end_unixtime = endzeit # install missing covers (dirname, dirname_serie) = getDirname(self.database, serien_name, staffel) STBHelpers.createDirectory(current_serien_name, dirname, dirname_serie, True) # setze die vorlauf/nachlauf-zeit (margin_before, margin_after) = self.database.getMargins(serien_name, sender, config.plugins.serienRec.margin_before.value, config.plugins.serienRec.margin_after.value) start_unixtime = int(start_unixtime) - (int(margin_before) * 60) end_unixtime = int(end_unixtime) + (int(margin_after) * 60) # if there is no season or episode number it can be a special # but if we have more than one special and wunschliste.de does not # give us an episode number we are unable to differentiate between these specials if not staffel and not episode: staffel = "S" episode = "00" # initialize strings seasonEpisodeString = "S%sE%s" % (str(staffel).zfill(2), str(episode).zfill(2)) label_serie = "%s - %s - %s" % (serien_name, seasonEpisodeString, title) if not config.plugins.serienRec.forceRecording.value: if (int(fromTime) > 0) or (int(toTime) < (23*60)+59): start_time = (time.localtime(int(start_unixtime)).tm_hour * 60) + time.localtime(int(start_unixtime)).tm_min end_time = (time.localtime(int(end_unixtime)).tm_hour * 60) + time.localtime(int(end_unixtime)).tm_min if not TimeHelpers.allowedTimeRange(fromTime, toTime, start_time, end_time): print "[SerienRecorder] processTransmissions time range ignore: %r" % serien_name timeRangeConfigured = "%s:%s - %s:%s" % (str(int(fromTime) / 60).zfill(2), str(int(fromTime) % 60).zfill(2), str(int(toTime) / 60).zfill(2), str(int(toTime) % 60).zfill(2)) timeRangeTransmission = "%s:%s - %s:%s" % (str(int(start_time) / 60).zfill(2), str(int(start_time) % 60).zfill(2), str(int(end_time) / 60).zfill(2), str(int(end_time) % 60).zfill(2)) SRLogger.writeLogFilter("timeRange", "' %s ' - Sendung (%s) nicht in Zeitspanne [%s]" % (label_serie, timeRangeTransmission, timeRangeConfigured)) continue # Process channel relevant data ############################## # # CHECK # # ueberprueft welche sender aktiviert und eingestellt sind. # (webChannel, stbChannel, stbRef, altstbChannel, altstbRef, status) = self.checkSender(sender) if stbChannel == "": SRLogger.writeLogFilter("channels", "' %s ' - STB-Sender nicht gefunden ' -> ' %s '" % (label_serie, webChannel)) continue if int(status) == 0: SRLogger.writeLogFilter("channels", "' %s ' - STB-Sender deaktiviert -> ' %s '" % (label_serie, webChannel)) continue ############################## # # CHECK # # ueberprueft welche staffel(n) erlaubt sind # serieAllowed = False if -2 in staffeln: # 'Manuell' serieAllowed = False elif (-1 in staffeln) and (0 in staffeln): # 'Alle' serieAllowed = True elif str(staffel).isdigit(): if int(staffel) == 0: if str(episode).isdigit(): if int(episode) < int(AbEpisode): if config.plugins.serienRec.writeLogAllowedEpisodes.value: liste = staffeln[:] liste.sort() liste.reverse() if -1 in staffeln: liste.remove(-1) liste[0] = "ab %s" % liste[0] liste.reverse() liste.insert(0, "0 ab E%s" % str(AbEpisode).zfill(2)) SRLogger.writeLogFilter("allowedEpisodes", "' %s ' - Episode nicht erlaubt -> ' %s ' -> ' %s '" % (label_serie, seasonEpisodeString, str(liste).replace("'", "").replace('"', ""))) continue else: serieAllowed = True elif int(staffel) in staffeln: serieAllowed = True elif -1 in staffeln: # 'folgende' if int(staffel) >= max(staffeln): serieAllowed = True elif self.database.getSpecialsAllowed(serien_name): serieAllowed = True vomMerkzettel = False if not serieAllowed: if self.database.hasBookmark(serien_name, staffel, episode): SRLogger.writeLog("' %s ' - Timer vom Merkzettel wird angelegt @ %s" % (label_serie, stbChannel), True) serieAllowed = True vomMerkzettel = True if not serieAllowed: if config.plugins.serienRec.writeLogAllowedEpisodes.value: liste = staffeln[:] liste.sort() liste.reverse() if -1 in staffeln: liste.remove(-1) liste[0] = "ab %s" % liste[0] liste.reverse() if str(episode).isdigit(): if int(episode) < int(AbEpisode): liste.insert(0, "0 ab E%s" % str(AbEpisode).zfill(2)) if -2 in staffeln: liste.remove(-2) liste.insert(0, "Manuell") SRLogger.writeLogFilter("allowedEpisodes", "' %s ' - Staffel nicht erlaubt -> ' %s ' -> ' %s '" % (label_serie, seasonEpisodeString, str(liste).replace("'", "").replace('"', ""))) continue ############################## # # try to get eventID (eit) from epgCache # eit, new_end_unixtime, new_start_unixtime = STBHelpers.getStartEndTimeFromEPG(start_unixtime, end_unixtime, margin_before, margin_after, serien_name, stbRef) alt_eit = 0 alt_end_unixtime = end_unixtime alt_start_unixtime = start_unixtime if altstbRef: alt_eit, alt_end_unixtime, alt_start_unixtime = STBHelpers.getStartEndTimeFromEPG(start_unixtime, end_unixtime, margin_before, margin_after, serien_name, altstbRef) updateFromEPG = self.database.getUpdateFromEPG(serien_name) if updateFromEPG is False: new_start_unixtime = start_unixtime new_end_unixtime = end_unixtime alt_end_unixtime = end_unixtime alt_start_unixtime = start_unixtime (dirname, dirname_serie) = getDirname(self.database, serien_name, staffel) self.tempDB.addTransmission([(current_time, future_time, serien_name, staffel, episode, seasonEpisodeString, title, label_serie, webChannel, stbChannel, stbRef, new_start_unixtime, new_end_unixtime, eit, altstbChannel, altstbRef, alt_start_unixtime, alt_end_unixtime, alt_eit, dirname, AnzahlAufnahmen, fromTime, toTime, int(vomMerkzettel), excludedWeekdays, updateFromEPG)]) self.tempDB.commitTransaction()
def createTimer(self, result=True): from SerienRecorderTimer import serienRecTimer timer = serienRecTimer() timer.setTempDB(self.tempDB) # versuche deaktivierte Timer zu erstellen timer.activate() # jetzt die Timer erstellen for x in range(self.noOfRecords): timer.search(x) # gleiche alte Timer mit EPG ab current_time = int(time.time()) timer.adjustEPGtimes(current_time) SRLogger.writeLog("\n", True) # Datenbank aufräumen self.database.rebuild() self.tempDB.rebuild() global autoCheckFinished autoCheckFinished = True (countTimer, countTimerUpdate, countNotActiveTimer, countTimerFromWishlist, self.messageList) = timer.getCounts() # Statistik self.speedEndTime = time.clock() speedTime = (self.speedEndTime - self.speedStartTime) if config.plugins.serienRec.eventid.value: SRLogger.writeLog("%s/%s Serie(n) sind vorgemerkt davon wurde(n) %s Timer erstellt und %s Timer aktualisiert." % (str(self.countActivatedSeries), str(self.countSerien), str(countTimer), str(countTimerUpdate)), True) print "[SerienRecorder] %s/%s Serie(n) sind vorgemerkt davon wurde(n) %s Timer erstellt und %s Timer aktualisiert." % (str(self.countActivatedSeries), str(self.countSerien), str(countTimer), str(countTimerUpdate)) else: SRLogger.writeLog("%s/%s Serie(n) sind vorgemerkt davon wurde(n) %s Timer erstellt." % (str(self.countActivatedSeries), str(self.countSerien), str(countTimer)), True) print "[SerienRecorder] %s/%s Serie(n) sind vorgemerkt davon wurde(n) %s Timer erstellt." % (str(self.countActivatedSeries), str(self.countSerien), str(countTimer)) if countNotActiveTimer > 0: SRLogger.writeLog("%s Timer wurde(n) wegen Konflikten deaktiviert erstellt!" % str(countNotActiveTimer), True) print "[SerienRecorder] %s Timer wurde(n) wegen Konflikten deaktiviert erstellt!" % str(countNotActiveTimer) if countTimerFromWishlist > 0: SRLogger.writeLog("%s Timer vom Merkzettel wurde(n) erstellt!" % str(countTimerFromWishlist), True) print "[SerienRecorder] %s Timer vom Merkzettel wurde(n) erstellt!" % str(countTimerFromWishlist) SRLogger.writeLog("---------' Auto-Check beendet (Ausführungsdauer: %3.2f Sek.)'---------" % speedTime, True) print "[SerienRecorder] ---------' Auto-Check beendet (Ausführungsdauer: %3.2f Sek.)'---------" % speedTime if (config.plugins.serienRec.showNotification.value in ("2", "3")) and (not self.manuell): statisticMessage = "Serien vorgemerkt: %s/%s\nTimer erstellt: %s\nTimer aktualisiert: %s\nTimer mit Konflikten: %s\nTimer vom Merkzettel: %s" % ( str(self.countActivatedSeries), str(self.countSerien), str(countTimer), str(countTimerUpdate), str(countNotActiveTimer), str(countTimerFromWishlist)) newSeasonOrEpisodeMessage = "" if self.newSeriesOrEpisodesFound: newSeasonOrEpisodeMessage = "\n\nNeuer Serien- oder Staffelbeginn gefunden" Notifications.AddPopup("SerienRecorder Suchlauf für neue Timer wurde beendet.\n\n%s%s" % ( statisticMessage, newSeasonOrEpisodeMessage), MessageBox.TYPE_INFO, timeout=10, id="Suchlauf wurde beendet") return result
def startCheckTransmissions(self): self.database = SRDatabase(serienRecDataBaseFilePath) self.tempDB = SRTempDatabase() self.tempDB.initialize() # read channels self.senderListe = {} for s in self.database.getChannels(): self.senderListe[s[0].lower()] = s[:] webChannels = self.database.getActiveChannels() SRLogger.writeLog("\nAnzahl aktiver Websender: %d" % len(webChannels), True) # get reference times current_time = int(time.time()) future_time = int(config.plugins.serienRec.checkfordays.value) * 86400 future_time += int(current_time) search_start = time.strftime("%d.%m.%Y - %H:%M", time.localtime(int(current_time))) search_end = time.strftime("%d.%m.%Y - %H:%M", time.localtime(int(future_time))) search_rerun_end = time.strftime("%d.%m.%Y - %H:%M", time.localtime(future_time + (int(config.plugins.serienRec.TimeSpanForRegularTimer.value) - int(config.plugins.serienRec.checkfordays.value)) * 86400)) SRLogger.writeLog("Berücksichtige Ausstrahlungstermine zwischen %s und %s" % (search_start, search_end), True) SRLogger.writeLog("Berücksichtige Wiederholungen zwischen %s und %s" % (search_start, search_rerun_end), True) # hier werden die wunschliste markers eingelesen self.emailData = None if config.plugins.serienRec.tvplaner.value and (not self.manuell or self.tvplaner_manuell): # When TV-Planer processing is enabled then regular autocheck # is only running for the transmissions received by email. try: from SerienRecorderTVPlaner import getEmailData emailParserThread = backgroundThread(getEmailData) emailParserThread.start() emailParserThread.join() self.emailData = emailParserThread.result except: SRLogger.writeLog("TV-Planer Verarbeitung fehlgeschlagen!", True) print "[SerienRecorder] TV-Planer exception!" self.emailData = None print "[SerienRecorder] lastFullCheckTime %s" % time.strftime("%d.%m.%Y - %H:%M", time.localtime(int(config.plugins.serienRec.tvplaner_last_full_check.value))) if self.emailData is None: self.markers = self.database.getMarkers(config.plugins.serienRec.BoxID.value, config.plugins.serienRec.NoOfRecords.value) config.plugins.serienRec.tvplaner_last_full_check.value = int(time.time()) config.plugins.serienRec.tvplaner_last_full_check.save() configfile.save() if config.plugins.serienRec.tvplaner.value: fullCheck = "- keine TV-Planer Daten - voller Suchlauf'" else: fullCheck = "- voller Suchlauf'" elif config.plugins.serienRec.tvplaner_full_check.value and (int(config.plugins.serienRec.tvplaner_last_full_check.value) + (int(config.plugins.serienRec.checkfordays.value) - 1) * 86400) < int(time.time()): self.markers = self.database.getMarkers(config.plugins.serienRec.BoxID.value, config.plugins.serienRec.NoOfRecords.value) config.plugins.serienRec.tvplaner_last_full_check.value = int(time.time()) config.plugins.serienRec.tvplaner_last_full_check.save() configfile.save() fullCheck = "- Zeit abgelaufen - voller Suchlauf'" else: self.markers = self.database.getMarkers(config.plugins.serienRec.BoxID.value, config.plugins.serienRec.NoOfRecords.value, self.emailData.keys()) fullCheck = "- nur Serien der TV-Planer E-Mail'" self.count_url = 0 self.countSerien = 0 self.countActivatedSeries = 0 self.noOfRecords = int(config.plugins.serienRec.NoOfRecords.value) # regular processing through serienrecorder server # TODO: save all transmissions in files to protect from temporary SerienServer fails # data will be read by the file reader below and used for timer programming if len(self.markers) > 0: while True: #if config.plugins.serienRec.tvplaner.value and config.plugins.serienRec.tvplaner_skipSerienServer.value: # Skip serien server processing # break global transmissionFailed transmissionFailed = False self.tempDB.cleanUp() if not (config.plugins.serienRec.tvplaner.value and config.plugins.serienRec.tvplaner_skipSerienServer.value): SRLogger.writeLog("\n---------' Verarbeite Daten vom Server %s ---------\n" % fullCheck, True) print "[SerienRecorder] Verarbeite Daten vom Server" # Create a job queue to keep the jobs processed by the threads # Create a result queue to keep the results of the job threads jobQueue = Queue.Queue() resultQueue = Queue.Queue() #SRLogger.writeLog("Active threads: %d" % threading.active_count(), True) # Create the threads for i in range(2): worker = downloadTransmissionsThread(jobQueue, resultQueue) worker.setDaemon(True) worker.start() for serienTitle,SerieUrl,SerieStaffel,SerieSender,AbEpisode,AnzahlAufnahmen,SerieEnabled,excludedWeekdays,skipSeriesServer,markerType in self.markers: if config.plugins.serienRec.tvplaner.value and (config.plugins.serienRec.tvplaner_skipSerienServer.value or (skipSeriesServer is not None and skipSeriesServer)): # Skip serien server processing SRLogger.writeLog("' %s ' - Für diesen Serien-Marker sollen nur Timer aus der E-Mail angelegt werden." % serienTitle, True) continue if markerType == 1: # temporary marker for movie recording print "[SerienRecorder] ' %s - TV-Planer Film wird ignoriert '" % serienTitle continue self.countSerien += 1 if SerieEnabled: # Download only if series is enabled if 'Alle' in SerieSender: markerChannels = webChannels else: markerChannels = SerieSender self.countActivatedSeries += 1 seriesID = SerieUrl jobQueue.put((seriesID, (int(config.plugins.serienRec.TimeSpanForRegularTimer.value)), markerChannels, serienTitle, SerieStaffel, AbEpisode, AnzahlAufnahmen, current_time, future_time, excludedWeekdays)) jobQueue.join() while not resultQueue.empty(): (transmissionFailed, transmissions, seriesID, serienTitle, SerieStaffel, AbEpisode, AnzahlAufnahmen, current_time, future_time, excludedWeekdays) = resultQueue.get() self.processTransmission(transmissions, seriesID, serienTitle, SerieStaffel, AbEpisode, AnzahlAufnahmen, current_time, future_time, excludedWeekdays) resultQueue.task_done() break # # In order to provide an emergency recording service when serien server is down or # because Wunschliste isn't accessable, it is now possible to use the TV Wunschliste # TV-Planer Infomails. # # With an account at www.wunschliste.de it is possible to mark series to appear at # "TV-Planer" screen. This screen shows the transmissions of up to a week in advance. # In "Einstellungen" it is possible to enable Infomails about TV-Planer. This Infomails # can now be used by SerienRecorder to create timers without any further access to # Wunschliste, and therefore avoids hitting Wunschliste with the enormous # internet traffic that was caused by the many boxes with SerienRecorder. # # Wunschliste Settings: # - put your favourite series on TV-Planer # - enable TV-Planer Infomails in "Einstellungen" # - set Vorlauf (i.e. 1 day) # - set Programmtag-Beginn (i.e. 5.00 Uhr) # - set MailFormat to HTML+Text (currently only HTML emails are recognized) # # When this has been finished the first TV-Planer email will be received next day. # # SerienRecorder Settings: # - enable TVPlaner feature # - set email server, login, password and possibly modify the other parameters # - set the autocheck time to about 1 h after the time you receive the TV-planer emails # # Now every time the regular SerienRecorder autocheck runs, received # TV-Planer emails will be used to program timers, even no marker # has been created by SerienMarker before. The marker is created automatically, # except for the correct url. # if config.plugins.serienRec.tvplaner.value and self.emailData is not None: # check mailbox for TV-Planer EMail and create timer SRLogger.writeLog("\n---------' Verarbeite Daten aus TV-Planer E-Mail '---------\n", True) jobQueue = Queue.Queue() resultQueue = Queue.Queue() # Create the threads for i in range(2): worker = processEMailDataThread(self.emailData, jobQueue, resultQueue) worker.setDaemon(True) worker.start() for serienTitle,SerieUrl,SerieStaffel,SerieSender,AbEpisode,AnzahlAufnahmen,SerieEnabled,excludedWeekdays,skipSeriesServer,markerType in self.database.getMarkers(config.plugins.serienRec.BoxID.value, config.plugins.serienRec.NoOfRecords.value, self.emailData.keys()): print serienTitle if SerieEnabled: # Process only if series is enabled if 'Alle' in SerieSender: markerChannels = { x : x for x in webChannels } else: markerChannels = { x : x for x in SerieSender } jobQueue.put((markerChannels, SerieUrl, serienTitle, SerieStaffel, AbEpisode, AnzahlAufnahmen, current_time, future_time, excludedWeekdays)) jobQueue.join() while not resultQueue.empty(): (transmissions, seriesID, serienTitle, SerieStaffel, AbEpisode, AnzahlAufnahmen, current_time, future_time, excludedWeekdays) = resultQueue.get() self.processTransmission(transmissions, seriesID, serienTitle, SerieStaffel, AbEpisode, AnzahlAufnahmen, current_time, future_time, excludedWeekdays) resultQueue.task_done() self.createTimer() self.checkFinal()
def update(self, timer_list, eit, end_unixtime, episode, new_serien_title, serien_name, serien_time, staffel, start_unixtime, stbRef, title, dirname): timerUpdated = False timerFound = False for timer in timer_list: if timer and timer.service_ref: # skip all timer with false service ref if (str(timer.service_ref).lower() == str(stbRef).lower()) and (str(timer.begin) == str(serien_time)): # Timer gefunden, weil auf dem richtigen Sender und Startzeit im Timer entspricht Startzeit in SR DB timerFound = True # Muss der Timer aktualisiert werden? # Event ID updateEIT = False old_eit = timer.eit if timer.eit != int(eit): timer.eit = eit updateEIT = True # Startzeit updateStartTime = False if start_unixtime and timer.begin != start_unixtime and abs(start_unixtime - timer.begin) > 30: timer.begin = start_unixtime timer.end = end_unixtime NavigationInstance.instance.RecordTimer.timeChanged(timer) updateStartTime = True # Timername updateName = False old_timername = timer.name if config.plugins.serienRec.TimerName.value == "0": timer_name = "%s - S%sE%s - %s" % (serien_name, str(staffel).zfill(2), str(episode).zfill(2), new_serien_title) elif config.plugins.serienRec.TimerName.value == "2": timer_name = "S%sE%s - %s" % (str(staffel).zfill(2), str(episode).zfill(2), new_serien_title) else: timer_name = serien_name if timer.name != timer_name: timer.name = timer_name updateName = True # Timerbeschreibung updateDescription = False old_timerdescription = timer.description timer_description = "S%sE%s - %s" % (str(staffel).zfill(2), str(episode).zfill(2), new_serien_title) if timer.description != timer_description: timer.description = timer_description updateDescription = True # Directory updateDirectory = False old_dirname = timer.dirname if timer.dirname != dirname: (dirname, dirname_serie) = getDirname(self.database, serien_name, staffel) STBHelpers.createDirectory(serien_name, dirname, dirname_serie) timer.dirname = dirname updateDirectory = True if updateEIT or updateStartTime or updateName or updateDescription or updateDirectory: SRLogger.writeLog("' %s - %s '" % (title, dirname), True) new_start = time.strftime("%d.%m. - %H:%M", time.localtime(int(start_unixtime))) old_start = time.strftime("%d.%m. - %H:%M", time.localtime(int(serien_time))) if updateStartTime: SRLogger.writeLog(" Startzeit wurde aktualisiert von %s auf %s" % (old_start, new_start), True) timer.log(0, "[SerienRecorder] Changed timer start from %s to %s" % (old_start, new_start)) if updateEIT: SRLogger.writeLog(" Event ID wurde aktualisiert von %s auf %s" % (str(old_eit), str(eit)), True) timer.log(0, "[SerienRecorder] Changed event ID from %s to %s" % (str(old_eit), str(eit))) if updateName: SRLogger.writeLog(" Name wurde aktualisiert von %s auf %s" % (old_timername, timer_name), True) timer.log(0, "[SerienRecorder] Changed name from %s to %s" % (old_timername, timer_name)) if updateDescription: SRLogger.writeLog(" Beschreibung wurde aktualisiert von %s auf %s" % (old_timerdescription, timer_description), True) timer.log(0, "[SerienRecorder] Changed description from %s to %s" % (old_timerdescription, timer_description)) if updateDirectory: SRLogger.writeLog(" Verzeichnis wurde aktualisiert von %s auf %s" % (old_dirname, dirname), True) timer.log(0, "[SerienRecorder] Changed directory from %s to %s" % (old_dirname, dirname)) self.countTimerUpdate += 1 NavigationInstance.instance.RecordTimer.saveTimer() self.database.updateTimerStartTime(start_unixtime, eit, new_serien_title, serien_time, stbRef) timerUpdated = True else: # SRLogger.writeLog("' %s - %s '" % (title, dirname), True) # SRLogger.writeLog(" Timer muss nicht aktualisiert werden", True) timerUpdated = True break # Timer not found - maybe removed from image timer list if not timerFound: SRLogger.writeLog("' %s - %s '" % (title, dirname), True) SRLogger.writeLog(" Timer konnte nicht aktualisiert werden, weil er nicht gefunden werden konnte!", True) return timerUpdated
def startCheck(self): self.database = SRDatabase(serienRecDataBaseFilePath) global autoCheckFinished autoCheckFinished = False print "[SerienRecorder] settings:" print "[SerienRecorder] manuell:", self.manuell print "[SerienRecorder] tvplaner_manuell:", self.tvplaner_manuell print "[SerienRecorder] uhrzeit check:", config.plugins.serienRec.timeUpdate.value lt = time.localtime() self.uhrzeit = time.strftime("%d.%m.%Y - %H:%M:%S", lt) global refreshTimer global refreshTimerConnection SRLogger.checkFileAccess() SRLogger.writeLog("\n---------' %s '---------" % self.uhrzeit, True) if not self.manuell and not initDB(): self.askForDSB() return if not self.database.hasMarkers() and not config.plugins.serienRec.tvplaner and not config.plugins.serienRec.tvplaner_create_marker: SRLogger.writeLog("\n---------' Starte Auto-Check um %s '---------" % self.uhrzeit, True) print "[SerienRecorder] check: Tabelle SerienMarker leer." SRLogger.writeLog("Es sind keine Serien-Marker vorhanden - Auto-Check kann nicht ausgeführt werden.", True) SRLogger.writeLog("---------' Auto-Check beendet '---------", True) self.askForDSB() return if not self.database.hasChannels(): SRLogger.writeLog("\n---------' Starte Auto-Check um %s '---------" % self.uhrzeit, True) print "[SerienRecorder] check: Tabelle Channels leer." SRLogger.writeLog("Es wurden keine Sender zugeordnet - Auto-Check kann nicht ausgeführt werden.", True) SRLogger.writeLog("---------' Auto-Check beendet '---------", True) self.askForDSB() return if refreshTimer: refreshTimer.stop() refreshTimer = None if refreshTimerConnection: refreshTimerConnection = None print "[SerienRecorder] Auto-Check Timer stop." SRLogger.writeLog("Auto-Check stop.", True) if config.plugins.serienRec.autochecktype.value == "1" and config.plugins.serienRec.timeUpdate.value: deltatime = self.getNextAutoCheckTimer(lt) refreshTimer = eTimer() if isDreamOS(): refreshTimerConnection = refreshTimer.timeout.connect(self.startCheck) else: refreshTimer.callback.append(self.startCheck) refreshTimer.start(((deltatime * 60) + random.randint(0, int(config.plugins.serienRec.maxDelayForAutocheck.value)*60)) * 1000, True) print "[SerienRecorder] Auto-Check Uhrzeit-Timer gestartet." print "[SerienRecorder] Verbleibende Zeit: %s Stunden" % (TimeHelpers.td2HHMMstr(datetime.timedelta(minutes=deltatime+int(config.plugins.serienRec.maxDelayForAutocheck.value)))) SRLogger.writeLog("Auto-Check Uhrzeit-Timer gestartet.", True) SRLogger.writeLog("Verbleibende Zeit: %s Stunden" % TimeHelpers.td2HHMMstr(datetime.timedelta(minutes=deltatime+int(config.plugins.serienRec.maxDelayForAutocheck.value))), True) if config.plugins.serienRec.AutoBackup.value == "before": createBackup() SRLogger.reset() from SerienRecorderTVPlaner import resetTVPlanerHTMLBackup resetTVPlanerHTMLBackup() self.database.removeExpiredTimerConflicts() if self.tvplaner_manuell and config.plugins.serienRec.tvplaner.value: print "\n---------' Starte Check um %s (TV-Planer manuell) '---------" % self.uhrzeit SRLogger.writeLog("\n---------' Starte Check um %s (TV-Planer manuell) '---------\n" % self.uhrzeit, True) elif self.manuell: print "\n---------' Starte Check um %s (manuell) '---------" % self.uhrzeit SRLogger.writeLog("\n---------' Starte Check um %s (manuell) '---------\n" % self.uhrzeit, True) elif config.plugins.serienRec.tvplaner.value: print "\n---------' Starte Auto-Check um %s (TV-Planer auto) '---------" % self.uhrzeit SRLogger.writeLog("\n---------' Starte Auto-Check um %s (TV-Planer auto) '---------\n" % self.uhrzeit, True) else: print "\n---------' Starte Auto-Check um %s (auto)'---------" % self.uhrzeit SRLogger.writeLog("\n---------' Starte Auto-Check um %s (auto)'---------\n" % self.uhrzeit, True) if config.plugins.serienRec.showNotification.value in ("1", "3"): Notifications.AddPopup("SerienRecorder Suchlauf nach neuen Timern wurde gestartet.", MessageBox.TYPE_INFO, timeout=3, id="Suchlauf wurde gestartet") if config.plugins.serienRec.writeLogVersion.value: SRLogger.writeLog("STB Type: %s\nImage: %s" % (STBHelpers.getSTBType(), STBHelpers.getImageVersionString()), True) SRLogger.writeLog("SR Version: %s\nDatenbank Version: %s" % (config.plugins.serienRec.showversion.value, str(self.database.getVersion())), True) SRLogger.writeLog("Skin Auflösung: %s x %s" % (str(getDesktop(0).size().width()), str(getDesktop(0).size().height())), True) sMsg = "\nDEBUG Filter: " if config.plugins.serienRec.writeLogChannels.value: sMsg += "Senderliste " if config.plugins.serienRec.writeLogAllowedEpisodes.value: sMsg += "Episoden " if config.plugins.serienRec.writeLogAdded.value: sMsg += "Added " if config.plugins.serienRec.writeLogDisk.value: sMsg += "Disk " if config.plugins.serienRec.writeLogTimeRange.value: sMsg += "Tageszeit " if config.plugins.serienRec.writeLogTimeLimit.value: sMsg += "Zeitlimit " if config.plugins.serienRec.writeLogTimerDebug.value: sMsg += "Timer " SRLogger.writeLog(sMsg, True) self.markers = [] self.messageList = [] self.speedStartTime = time.clock() # teste Verbindung ins Internet if not testWebConnection(): SRLogger.writeLog("\nKeine Verbindung ins Internet. Check wurde abgebrochen!!\n", True) # Statistik self.speedEndTime = time.clock() speedTime = (self.speedEndTime - self.speedStartTime) SRLogger.writeLog("---------' Auto-Check beendet ( Ausführungsdauer: %3.2f Sek.)'---------" % speedTime, True) print "[SerienRecorder] ---------' Auto-Check beendet ( Ausführungsdauer: %3.2f Sek.)'---------" % speedTime from SerienRecorderTVPlaner import backupTVPlanerHTML backupTVPlanerHTML() global autoCheckFinished autoCheckFinished = True if config.plugins.serienRec.AutoBackup.value == "after": createBackup() # in den deep-standby fahren. self.askForDSB() return # Versuche Verzeichnisse zu erreichen try: SRLogger.writeLog("\nPrüfe konfigurierte Aufnahmeverzeichnisse:", True) recordDirectories = self.database.getRecordDirectories(config.plugins.serienRec.savetopath.value) for directory in recordDirectories: SRLogger.writeLog(" %s" % directory, True) os.path.exists(directory) except: SRLogger.writeLog("Es konnten nicht alle Aufnahmeverzeichnisse gefunden werden", True) # suche nach neuen Serien, Covern und Planer-Cache from twisted.internet import reactor from SerienRecorderSeriesPlanner import serienRecSeriesPlanner seriesPlanner = serienRecSeriesPlanner(self.manuell) reactor.callFromThread(seriesPlanner.updatePlanerData()) #if config.plugins.serienRec.downloadCover.value: # reactor.callFromThread(self.getMarkerCover()) self.startCheckTransmissions()
def adjustEPGtimes(self, current_time): SRLogger.writeLog("\n---------' Aktualisiere Timer '---------\n", True) ############################## # # try to get eventID (eit) from epgCache # recordHandler = NavigationInstance.instance.RecordTimer #SRLogger.writeLog("<< Suche im EPG anhand der Uhrzeit", True) timers = self.database.getAllTimer(current_time) for timer in timers: (serien_name, staffel, episode, serien_title, serien_time, stbRef, webChannel, eit, active) = timer title = "%s - S%sE%s - %s" % (serien_name, str(staffel).zfill(2), str(episode).zfill(2), serien_title) new_serien_title = serien_title new_serien_time = 0 updateFromEPG = True transmission = None if str(episode).isdigit(): if int(episode) != 0: transmission = self.tempDB.getTransmissionForTimerUpdate(serien_name, staffel, episode) else: transmission = self.tempDB.getTransmissionForTimerUpdate(serien_name, staffel, episode) if transmission: (new_serien_name, new_staffel, new_episode, new_serien_title, new_serien_time, updateFromEPG) = transmission (margin_before, margin_after) = self.database.getMargins(serien_name, webChannel, config.plugins.serienRec.margin_before.value, config.plugins.serienRec.margin_after.value) # event_matches = STBHelpers.getEPGEvent(['RITBDSE',("1:0:19:EF75:3F9:1:C00000:0:0:0:", 0, 1392755700, -1)], "1:0:19:EF75:3F9:1:C00000:0:0:0:", "2 Broke Girls", 1392755700) event_matches = STBHelpers.getEPGEvent(['RITBDSE',(stbRef, 0, int(serien_time)+(int(margin_before) * 60), -1)], stbRef, serien_name, int(serien_time)+(int(margin_before) * 60)) new_event_matches = None if new_serien_time != 0 and eit > 0: new_event_matches = STBHelpers.getEPGEvent(['RITBDSE',(stbRef, 0, int(new_serien_time)+(int(margin_before) * 60), -1)], stbRef, serien_name, int(new_serien_time)+(int(margin_before) * 60)) if new_event_matches and len(new_event_matches) > 0 and (not event_matches or (event_matches and len(event_matches) == 0)): # Old event not found but new one with different start time event_matches = new_event_matches (dirname, dirname_serie) = getDirname(self.database, serien_name, staffel) if event_matches and len(event_matches) > 0: for event_entry in event_matches: eit = int(event_entry[1]) if config.plugins.serienRec.eventid.value and updateFromEPG: start_unixtime = int(event_entry[3]) - (int(margin_before) * 60) end_unixtime = int(event_entry[3]) + int(event_entry[4]) + (int(margin_after) * 60) else: start_unixtime = None end_unixtime = None print "[SerienRecorder] try to modify enigma2 Timer:", title, serien_time if (str(staffel) is 'S' or str(staffel) is '0') and (str(episode) is '0' or str(episode) is '00'): SRLogger.writeLog("' %s - %s '" % (title, dirname), True) SRLogger.writeLog(" Timer kann nicht aktualisiert werden @ %s" % webChannel, True) break try: # suche in aktivierten Timern self.update(recordHandler.timer_list + recordHandler.processed_timers, eit, end_unixtime, episode, new_serien_title, serien_name, serien_time, staffel, start_unixtime, stbRef, title, dirname) except Exception: print "[SerienRecorder] Modifying enigma2 Timer failed:", title, serien_time SRLogger.writeLog("' %s - %s '" % (title, dirname), True) SRLogger.writeLog(" Timeraktualisierung fehlgeschlagen @ %s" % webChannel, True) break else: SRLogger.writeLog("' %s - %s '" % (title, dirname), True) SRLogger.writeLog(" Timer konnte nicht aus dem EPG aktualisiert werden, da der Abgleich fehlgeschlagen ist @ %s" % webChannel)
def getEmailData(): # extract all html parts def get_html(email_message_instance): maintype = email_message_instance.get_content_maintype() if maintype == 'multipart': for part in email_message_instance.get_payload(): if part.get_content_type() == 'text/html': return part.get_payload() SRLogger.writeLog("\n---------' Lade TV-Planer E-Mail '---------\n", True) # get emails if len(config.plugins.serienRec.imap_server.value) == 0: SRLogger.writeLog("TV-Planer: imap_server nicht gesetzt", True) return None if len(config.plugins.serienRec.imap_login_hidden.value) == 0: SRLogger.writeLog("TV-Planer: imap_login nicht gesetzt", True) return None if len(config.plugins.serienRec.imap_password_hidden.value) == 0: SRLogger.writeLog("TV-Planer: imap_password nicht gesetzt", True) return None if len(config.plugins.serienRec.imap_mailbox.value) == 0: SRLogger.writeLog("TV-Planer: imap_mailbox nicht gesetzt", True) return None if len(config.plugins.serienRec.imap_mail_subject.value) == 0: SRLogger.writeLog("TV-Planer: imap_mail_subject nicht gesetzt", True) return None if 1 > config.plugins.serienRec.imap_mail_age.value > 100: config.plugins.serienRec.imap_mail_age.value = 1 try: if config.plugins.serienRec.imap_server_ssl.value: mail = imaplib.IMAP4_SSL(config.plugins.serienRec.imap_server.value, config.plugins.serienRec.imap_server_port.value) else: mail = imaplib.IMAP4(config.plugins.serienRec.imap_server.value, config.plugins.serienRec.imap_server_port.value) except imaplib.IMAP4.abort: SRLogger.writeLog("TV-Planer: Verbindung zum Server fehlgeschlagen", True) return None except imaplib.IMAP4.error: SRLogger.writeLog("TV-Planer: Verbindung zum Server fehlgeschlagen", True) return None try: mail.login(decrypt(getmac("eth0"), config.plugins.serienRec.imap_login_hidden.value), decrypt(getmac("eth0"), config.plugins.serienRec.imap_password_hidden.value)) print "[serienrecorder]: imap login ok" except imaplib.IMAP4.error: SRLogger.writeLog("TV-Planer: Anmeldung auf Server fehlgeschlagen", True) print "[serienrecorder]: imap login failed" return None try: mail.select(config.plugins.serienRec.imap_mailbox.value) except imaplib.IMAP4.error: SRLogger.writeLog("TV-Planer: Mailbox %r nicht gefunden" % config.plugins.serienRec.imap_mailbox.value, True) return None searchstr = TimeHelpers.getMailSearchString() try: result, data = mail.uid('search', None, searchstr) if result != 'OK': SRLogger.writeLog("TV-Planer: Fehler bei der Suche nach TV-Planer E-Mails", True) SRLogger.writeLog("TV-Planer: %s" % data, True) return None except imaplib.IMAP4.error: SRLogger.writeLog("TV-Planer: Keine TV-Planer Nachricht in den letzten %s Tagen" % str(config.plugins.serienRec.imap_mail_age.value), True) SRLogger.writeLog("TV-Planer: %s" % searchstr, True) return None if len(data[0]) == 0: SRLogger.writeLog("TV-Planer: Keine TV-Planer Nachricht in den letzten %s Tagen" % str(config.plugins.serienRec.imap_mail_age.value), True) SRLogger.writeLog("TV-Planer: %s" % searchstr, True) return None # get the latest email latest_email_uid = data[0].split()[-1] # fetch the email body (RFC822) for the given UID try: result, data = mail.uid('fetch', latest_email_uid, '(RFC822)') except: SRLogger.writeLog("TV-Planer: Laden der E-Mail fehlgeschlagen", True) return None mail.logout() # extract email message including headers and alternate payloads email_message = email.message_from_string(data[0][1]) if len(email_message) == 0: SRLogger.writeLog("TV-Planer: leere E-Mail", True) return None # get html of wunschliste html = get_html(email_message) if html is None or len(html) == 0: SRLogger.writeLog("TV-Planer: leeres HTML", True) return None # make one line and convert characters html = html.replace('=\r\n', '').replace('=\n', '').replace('=\r', '').replace('\n', '').replace('\r', '') html = html.replace('=3D', '=') try: def getTextContentByTitle(node, titleValue, default): titleNodes = node.childNodes.getElementsByAttr('title', titleValue) if titleNodes: return titleNodes[0].textContent.encode('utf-8') else: return default def getEpisodeTitle(node): childNodes = node.childNodes.getElementsByTagName('a') if childNodes: return childNodes[0].textContent.encode('utf-8') else: # Movies does not a link to the episode => only country, year childNodes = node.childNodes.getElementsByTagName('span') if childNodes: return childNodes[0].textContent.encode('utf-8') else: return '' import AdvancedHTMLParser parser = AdvancedHTMLParser.AdvancedHTMLParser() html = parser.unescape(html).encode('utf-8') parser.parseStr(html) # Get tables from HTML tables = parser.getElementsByTagName('table') # Initialize regular expressions date_regexp = re.compile('.*TV-Planer.*?den ([0-3][0-9]\.[0-1][0-9]\.20[0-9][0-9])\s.(?:\(ab (.*?) Uhr\))?') url_title_regexp = re.compile('.*<a href="([^\?]+)(?:\?.*)?".*><strong.*>(.*)</strong>') endtime_regexp = re.compile('.*bis:\s(.*)\sUhr.*') # Get date and time of TV-Planer header = tables[1].getAllChildNodes().getElementsByTagName('div')[0].textContent.encode('utf-8') planerDateTime = date_regexp.findall(header)[0] print planerDateTime # Get transmissions transmissions = [] transmissionTable = tables[1].getAllChildNodes().getElementsByTagName('table')[0] transmissionRows = transmissionTable.childNodes for transmissionRow in transmissionRows: transmission = [] if not transmissionRow.hasAttribute('style'): transmissionColumns = transmissionRow.childNodes # Each transmission row has three columns # [0]: Start time starttime = transmissionColumns[0].textContent.encode('utf-8') if starttime != 'Anzeige': transmission.append(starttime.replace(' Uhr', '')) # [1]: URL, Title, Season, Episode, Info transmissionColumn = transmissionColumns[1] # Season, Episode, Title, Episode info, End time episodeInfo = ['0', '00', '', '', '0.00'] if transmissionColumn.firstChild: # First child is always URL + Title url_title = url_title_regexp.findall(transmissionColumn.firstChild.toHTML().encode('utf-8'))[0] transmission.extend(url_title) if transmissionColumn.lastChild: # Last element => End time (it has to be filled with a time because later on the time will be splitted) endtime = endtime_regexp.findall(transmissionColumn.lastChild.toHTML().encode('utf-8')) if endtime: episodeInfo[4] = endtime[0] divPartIndex = 0 for transmissionPart in transmissionColumn.childNodes: if transmissionPart is transmissionColumn.lastChild: # Skip part if it the "last" part continue if transmissionPart.tagName == 'div' and divPartIndex == 0: # First div element => Season / Episode / Title / e.g. NEU episodeInfo[0] = getTextContentByTitle(transmissionPart, 'Staffel', '0') episodeInfo[1] = getTextContentByTitle(transmissionPart, 'Episode', '00') episodeInfo[2] = getEpisodeTitle(transmissionPart) divPartIndex += 1 elif transmissionPart.tagName == 'div' and divPartIndex == 1: # Second div element => Episode info episodeInfo[3] = transmissionPart.textContent.encode('utf-8') transmission.extend(episodeInfo) # [2] Channel transmission.append(transmissionColumns[2].textContent.encode('utf-8')) print transmission transmissions.append(transmission) except: SRLogger.writeLog("TV-Planer: HTML Parsing abgebrochen", True) return None # prepare transmissions # [ ( seriesName, channel, start, end, season, episode, title, '0' ) ] # calculate start time and end time of list in E-Mail missingTime = False if len(planerDateTime) != 2: SRLogger.writeLog("TV-Planer: falsches Datumsformat", True) return None (day, month, year) = planerDateTime[0].split('.') if not planerDateTime[1]: if transmissions: # Get time of first transmission (hour, minute) = transmissions[0][0].split(':') else: missingTime = True (hour, minute) = ('00', '00') else: (hour, minute) = planerDateTime[1].split(':') liststarttime_unix = TimeHelpers.getRealUnixTime(minute, hour, day, month, year) # generate dictionary with final transmissions SRLogger.writeLog("Ab dem %s %s Uhr wurden die folgenden Sendungen gefunden:\n" % (planerDateTime[0], planerDateTime[1])) print "[SerienRecorder] Ab dem %s %s Uhr wurden die folgenden Sendungen gefunden:" % (planerDateTime[0], planerDateTime[1]) if missingTime: SRLogger.writeLog("In der Kopfzeile der TV-Planer E-Mail konnte keine Uhrzeit gefunden werden, bitte kontrollieren Sie die angelegten Timer!\n") transmissiondict = dict() for starttime, url, seriesname, season, episode, titel, description, endtime, channel in transmissions: try: if url.startswith('https://www.wunschliste.de/spielfilm'): if not config.plugins.serienRec.tvplaner_movies.value: SRLogger.writeLog("' %s - Filmaufzeichnung ist deaktiviert '" % seriesname, True) print "' %s - Filmaufzeichnung ist deaktiviert '" % seriesname continue transmissiontype = '[ Film ]' elif url.startswith('https://www.wunschliste.de/serie'): if not config.plugins.serienRec.tvplaner_series.value: SRLogger.writeLog("' %s - Serienaufzeichnung ist deaktiviert '" % seriesname, True) print "' %s - Serienaufzeichnung ist deaktiviert '" % seriesname continue transmissiontype = '[ Serie ]' else: SRLogger.writeLog("' %s - Ungültige URL %r '" % (seriesname, url), True) print "' %s - Serienaufzeichnung ist deaktiviert '" % seriesname continue # series transmission = [ seriesname ] # channel channel = channel.replace(' (Pay-TV)','').replace(' (Schweiz)','').replace(' (GB)','').replace(' (Österreich)','').replace(' (USA)','').replace(' (RP)','').replace(' (F)','').strip() transmission += [ channel ] # start time (hour, minute) = starttime.split(':') transmissionstart_unix = TimeHelpers.getRealUnixTime(minute, hour, day, month, year) if transmissionstart_unix < liststarttime_unix: transmissionstart_unix = TimeHelpers.getRealUnixTimeWithDayOffset(minute, hour, day, month, year, 1) transmission += [ transmissionstart_unix ] # end time (hour, minute) = endtime.split('.') transmissionend_unix = TimeHelpers.getRealUnixTime(minute, hour, day, month, year) if transmissionend_unix < transmissionstart_unix: transmissionend_unix = TimeHelpers.getRealUnixTimeWithDayOffset(minute, hour, day, month, year, 1) transmission += [ transmissionend_unix ] # season if season == '': season = '0' transmission += [ season ] # episode if episode == '': episode = '00' transmission += [ episode ] # title transmission += [ quopri.decodestring(titel) ] # last transmission += [ '0' ] # url transmission += [ url ] # store in dictionary transmissiondict[seriesname] = [ seriesname: [ transmission 0 ], [ transmission 1], .... ] if seriesname in transmissiondict: transmissiondict[seriesname] += [ transmission ] else: transmissiondict[seriesname] = [ transmission ] SRLogger.writeLog("' %s - S%sE%s - %s - %s - %s - %s - %s '" % (transmission[0], str(transmission[4]).zfill(2), str(transmission[5]).zfill(2), transmission[6], transmission[1], time.strftime("%d.%m.%Y %H:%M", time.localtime(int(transmissionstart_unix))), time.strftime("%d.%m.%Y %H:%M", time.localtime(int(transmissionend_unix))), transmissiontype), True) print "[SerienRecorder] ' %s - S%sE%s - %s - %s - %s - %s - %s'" % (transmission[0], str(transmission[4]).zfill(2), str(transmission[5]).zfill(2), transmission[6], transmission[1], time.strftime("%d.%m.%Y %H:%M", time.localtime(int(transmissionstart_unix))), time.strftime("%d.%m.%Y %H:%M", time.localtime(int(transmissionend_unix))), transmissiontype) except Exception as e: SRLogger.writeLog("TV-Planer Verarbeitung fehlgeschlagen! [%s]" % str(e), True) if config.plugins.serienRec.tvplaner_create_marker.value: database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) for seriesname in transmissiondict.keys(): # marker isn't in database, create new marker # url stored in marker isn't the final one, it is corrected later url = transmissiondict[seriesname][0][-1] marker_type = "Serien Marker" try: boxID = None if url.startswith('https://www.wunschliste.de/serie'): seriesID = SeriesServer().getIDByFSID(url[str.rindex(url, '/') + 1:]) if seriesID > 0: url = str(seriesID) else: url = None if config.plugins.serienRec.tvplaner_series_activeSTB.value: boxID = config.plugins.serienRec.BoxID.value elif url.startswith('https://www.wunschliste.de/spielfilm'): marker_type = "Temporärer Serien Marker" if config.plugins.serienRec.tvplaner_movies_activeSTB.value: boxID = config.plugins.serienRec.BoxID.value else: url = None if url and not database.markerExists(url): if database.addMarker(url, seriesname, "", boxID, 1 if url.startswith('https://www.wunschliste.de/spielfilm') else 0): SRLogger.writeLog("\n%s für ' %s ' wurde angelegt" % (marker_type, seriesname), True) print "[SerienRecorder] ' %s - %s erzeugt '" % (seriesname, marker_type) except Exception as e: SRLogger.writeLog("\n%s für ' %s ' konnte wegen eines Fehlers nicht angelegt werden [%s]" % (marker_type, seriesname, str(e)), True) print "[SerienRecorder] ' %s - %s konnte wegen eines Fehlers nicht angelegt werden [%s]'" % (seriesname, marker_type, str(e)) else: SRLogger.writeLog("Es werden keine Serien-Marker aus der TV-Planer E-Mail erstellt.", True) return transmissiondict
def getEmailData(): # extract all html parts def get_html(email_message_instance): maintype = email_message_instance.get_content_maintype() if maintype == 'multipart': for part in email_message_instance.get_payload(): if part.get_content_type() == 'text/html': return part.get_payload() SRLogger.writeLog("\n---------' Lade TV-Planer E-Mail '---------\n", True) # get emails if len(config.plugins.serienRec.imap_server.value) == 0: SRLogger.writeLog("TV-Planer: imap_server nicht gesetzt", True) return None if len(config.plugins.serienRec.imap_login_hidden.value) == 0: SRLogger.writeLog("TV-Planer: imap_login nicht gesetzt", True) return None if len(config.plugins.serienRec.imap_password_hidden.value) == 0: SRLogger.writeLog("TV-Planer: imap_password nicht gesetzt", True) return None if len(config.plugins.serienRec.imap_mailbox.value) == 0: SRLogger.writeLog("TV-Planer: imap_mailbox nicht gesetzt", True) return None if len(config.plugins.serienRec.imap_mail_subject.value) == 0: SRLogger.writeLog("TV-Planer: imap_mail_subject nicht gesetzt", True) return None if 1 > config.plugins.serienRec.imap_mail_age.value > 100: config.plugins.serienRec.imap_mail_age.value = 1 try: if config.plugins.serienRec.imap_server_ssl.value: mail = imaplib.IMAP4_SSL(config.plugins.serienRec.imap_server.value, config.plugins.serienRec.imap_server_port.value) else: mail = imaplib.IMAP4(config.plugins.serienRec.imap_server.value, config.plugins.serienRec.imap_server_port.value) except imaplib.IMAP4.abort: SRLogger.writeLog("TV-Planer: Verbindung zum Server fehlgeschlagen", True) return None except imaplib.IMAP4.error: SRLogger.writeLog("TV-Planer: Verbindung zum Server fehlgeschlagen", True) return None try: mail.login(decrypt(getmac("eth0"), config.plugins.serienRec.imap_login_hidden.value), decrypt(getmac("eth0"), config.plugins.serienRec.imap_password_hidden.value)) print "[serienrecorder]: imap login ok" except imaplib.IMAP4.error: SRLogger.writeLog("TV-Planer: Anmeldung auf Server fehlgeschlagen", True) print "[serienrecorder]: imap login failed" return None try: mail.select(config.plugins.serienRec.imap_mailbox.value) except imaplib.IMAP4.error: SRLogger.writeLog("TV-Planer: Mailbox %r nicht gefunden" % config.plugins.serienRec.imap_mailbox.value, True) return None searchstr = TimeHelpers.getMailSearchString() try: result, data = mail.uid('search', None, searchstr) if result != 'OK': SRLogger.writeLog("TV-Planer: Fehler bei der Suche nach TV-Planer E-Mails", True) SRLogger.writeLog("TV-Planer: %s" % data, True) return None except imaplib.IMAP4.error: SRLogger.writeLog("TV-Planer: Keine TV-Planer Nachricht in den letzten %s Tagen" % str(config.plugins.serienRec.imap_mail_age.value), True) SRLogger.writeLog("TV-Planer: %s" % searchstr, True) return None if len(data[0]) == 0: SRLogger.writeLog("TV-Planer: Keine TV-Planer Nachricht in den letzten %s Tagen" % str(config.plugins.serienRec.imap_mail_age.value), True) SRLogger.writeLog("TV-Planer: %s" % searchstr, True) return None # get the latest email latest_email_uid = data[0].split()[-1] # fetch the email body (RFC822) for the given UID try: result, data = mail.uid('fetch', latest_email_uid, '(RFC822)') except: SRLogger.writeLog("TV-Planer: Laden der E-Mail fehlgeschlagen", True) return None mail.logout() # extract email message including headers and alternate payloads email_message = email.message_from_string(data[0][1]) if len(email_message) == 0: SRLogger.writeLog("TV-Planer: leere E-Mail", True) return None # get html of wunschliste html = get_html(email_message) if html is None or len(html) == 0: SRLogger.writeLog("TV-Planer: leeres HTML", True) return None if config.plugins.serienRec.tvplaner.value and config.plugins.serienRec.tvplaner_backupHTML.value: try: htmlFilePath = SERIENRECORDER_TVPLANER_HTML_FILENAME % config.plugins.serienRec.LogFilePath.value writeTVPlanerHTML = open(htmlFilePath, "w") writeTVPlanerHTML.write(html) writeTVPlanerHTML.close() except: SRLogger.writeLog("TV-Planer: HTML konnte nicht für die Fehlersuche gespeichert werden.", True) # make one line and convert characters html = html.replace('=\r\n', '').replace('=\n', '').replace('=\r', '').replace('\n', '').replace('\r', '') html = html.replace('=3D', '=') try: def getTextContentByTitle(node, titleValue, default): titleNodes = node.childNodes.getElementsByAttr('title', titleValue) if titleNodes: return titleNodes[0].textContent.encode('utf-8') else: return default def getEpisodeTitle(node): childNodes = node.childNodes.getElementsByTagName('a') if childNodes: return childNodes[0].textContent.encode('utf-8') else: # Movies does not a link to the episode => only country, year childNodes = node.childNodes.getElementsByTagName('span') if childNodes: return childNodes[0].textContent.encode('utf-8') else: return '' import AdvancedHTMLParser parser = AdvancedHTMLParser.AdvancedHTMLParser() html = parser.unescape(html).encode('utf-8') parser.parseStr(html) # Get tables from HTML tables = parser.getElementsByTagName('table') # Initialize regular expressions date_regexp = re.compile('.*TV-Planer.*?den ([0-3][0-9]\.[0-1][0-9]\.20[0-9][0-9])\s.(?:\(ab (.*?) Uhr\))?') url_title_regexp = re.compile('.*<a href="([^\?]+)(?:\?.*)?".*><strong.*>(.*)</strong>') endtime_regexp = re.compile('.*bis:\s(.*)\sUhr.*') # Get date and time of TV-Planer header = tables[1].getAllChildNodes().getElementsByTagName('div')[0].textContent.encode('utf-8') planerDateTime = date_regexp.findall(header)[0] print planerDateTime # Get transmissions transmissions = [] transmissionTable = tables[1].getAllChildNodes().getElementsByTagName('table')[0] transmissionRows = transmissionTable.childNodes for transmissionRow in transmissionRows: transmission = [] if not transmissionRow.hasAttribute('style'): transmissionColumns = transmissionRow.childNodes # Each transmission row has three columns # [0]: Start time starttime = transmissionColumns[0].textContent.encode('utf-8') if starttime != 'Anzeige': transmission.append(starttime.replace(' Uhr', '')) # [1]: URL, Title, Season, Episode, Info transmissionColumn = transmissionColumns[1] # Season, Episode, Title, Episode info, End time episodeInfo = ['0', '00', '', '', '0.00'] if transmissionColumn.firstChild: # First child is always URL + Title url_title = url_title_regexp.findall(transmissionColumn.firstChild.toHTML().encode('utf-8'))[0] transmission.extend(url_title) if transmissionColumn.lastChild: # Last element => End time (it has to be filled with a time because later on the time will be splitted) endtime = endtime_regexp.findall(transmissionColumn.lastChild.toHTML().encode('utf-8')) if endtime: episodeInfo[4] = endtime[0] divPartIndex = 0 for transmissionPart in transmissionColumn.childNodes: if transmissionPart is transmissionColumn.lastChild: # Skip part if it the "last" part continue if transmissionPart.tagName == 'div' and divPartIndex == 0: # First div element => Season / Episode / Title / e.g. NEU episodeInfo[0] = getTextContentByTitle(transmissionPart, 'Staffel', '0') episodeInfo[1] = getTextContentByTitle(transmissionPart, 'Episode', '00') episodeInfo[2] = getEpisodeTitle(transmissionPart) divPartIndex += 1 elif transmissionPart.tagName == 'div' and divPartIndex == 1: # Second div element => Episode info episodeInfo[3] = transmissionPart.textContent.encode('utf-8') transmission.extend(episodeInfo) # [2] Channel transmission.append(transmissionColumns[2].textContent.encode('utf-8')) print transmission transmissions.append(transmission) except: SRLogger.writeLog("TV-Planer: HTML Parsing abgebrochen", True) return None # prepare transmissions # [ ( seriesName, channel, start, end, season, episode, title, '0' ) ] # calculate start time and end time of list in E-Mail missingTime = False if len(planerDateTime) != 2: SRLogger.writeLog("TV-Planer: falsches Datumsformat", True) return None (day, month, year) = planerDateTime[0].split('.') if not planerDateTime[1]: if transmissions: # Get time of first transmission (hour, minute) = transmissions[0][0].split(':') else: missingTime = True (hour, minute) = ('00', '00') else: (hour, minute) = planerDateTime[1].split(':') liststarttime_unix = TimeHelpers.getRealUnixTime(minute, hour, day, month, year) # generate dictionary with final transmissions SRLogger.writeLog("Ab dem %s %s Uhr wurden die folgenden Sendungen gefunden:\n" % (planerDateTime[0], planerDateTime[1])) print "[SerienRecorder] Ab dem %s %s Uhr wurden die folgenden Sendungen gefunden:" % (planerDateTime[0], planerDateTime[1]) if missingTime: SRLogger.writeLog("In der Kopfzeile der TV-Planer E-Mail konnte keine Uhrzeit gefunden werden, bitte kontrollieren Sie die angelegten Timer!\n") transmissiondict = dict() for starttime, url, seriesname, season, episode, titel, description, endtime, channel in transmissions: try: if url.startswith('https://www.wunschliste.de/spielfilm'): if not config.plugins.serienRec.tvplaner_movies.value: SRLogger.writeLog("' %s - Filmaufzeichnung ist deaktiviert '" % seriesname, True) print "' %s - Filmaufzeichnung ist deaktiviert '" % seriesname continue transmissiontype = '[ Film ]' elif url.startswith('https://www.wunschliste.de/serie'): if not config.plugins.serienRec.tvplaner_series.value: SRLogger.writeLog("' %s - Serienaufzeichnung ist deaktiviert '" % seriesname, True) print "' %s - Serienaufzeichnung ist deaktiviert '" % seriesname continue transmissiontype = '[ Serie ]' else: SRLogger.writeLog("' %s - Ungültige URL %r '" % (seriesname, url), True) print "' %s - Serienaufzeichnung ist deaktiviert '" % seriesname continue # series transmission = [ seriesname ] # channel channel = channel.replace(' (Pay-TV)','').replace(' (Schweiz)','').replace(' (GB)','').replace(' (Österreich)','').replace(' (USA)','').replace(' (RP)','').replace(' (F)','').strip() transmission += [ channel ] # start time (hour, minute) = starttime.split(':') transmissionstart_unix = TimeHelpers.getRealUnixTime(minute, hour, day, month, year) if transmissionstart_unix < liststarttime_unix: transmissionstart_unix = TimeHelpers.getRealUnixTimeWithDayOffset(minute, hour, day, month, year, 1) transmission += [ transmissionstart_unix ] # end time (hour, minute) = endtime.split('.') transmissionend_unix = TimeHelpers.getRealUnixTime(minute, hour, day, month, year) if transmissionend_unix < transmissionstart_unix: transmissionend_unix = TimeHelpers.getRealUnixTimeWithDayOffset(minute, hour, day, month, year, 1) transmission += [ transmissionend_unix ] # season if season == '': season = '0' transmission += [ season ] # episode if episode == '': episode = '00' transmission += [ episode ] # title transmission += [ quopri.decodestring(titel) ] # last transmission += [ '0' ] # url transmission += [ url ] # store in dictionary transmissiondict[seriesname] = [ seriesname: [ transmission 0 ], [ transmission 1], .... ] if seriesname in transmissiondict: transmissiondict[seriesname] += [ transmission ] else: transmissiondict[seriesname] = [ transmission ] SRLogger.writeLog("' %s - S%sE%s - %s - %s - %s - %s - %s '" % (transmission[0], str(transmission[4]).zfill(2), str(transmission[5]).zfill(2), transmission[6], transmission[1], time.strftime("%d.%m.%Y %H:%M", time.localtime(int(transmissionstart_unix))), time.strftime("%d.%m.%Y %H:%M", time.localtime(int(transmissionend_unix))), transmissiontype), True) print "[SerienRecorder] ' %s - S%sE%s - %s - %s - %s - %s - %s'" % (transmission[0], str(transmission[4]).zfill(2), str(transmission[5]).zfill(2), transmission[6], transmission[1], time.strftime("%d.%m.%Y %H:%M", time.localtime(int(transmissionstart_unix))), time.strftime("%d.%m.%Y %H:%M", time.localtime(int(transmissionend_unix))), transmissiontype) except Exception as e: SRLogger.writeLog("TV-Planer Verarbeitung fehlgeschlagen! [%s]" % str(e), True) if config.plugins.serienRec.tvplaner_create_marker.value: database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) for seriesname in transmissiondict.keys(): # marker isn't in database, create new marker # url stored in marker isn't the final one, it is corrected later url = transmissiondict[seriesname][0][-1] marker_type = "Serien Marker" try: boxID = None if url.startswith('https://www.wunschliste.de/serie'): seriesID = SeriesServer().getIDByFSID(url[str.rindex(url, '/') + 1:]) if seriesID > 0: url = str(seriesID) else: url = None if config.plugins.serienRec.tvplaner_series_activeSTB.value: boxID = config.plugins.serienRec.BoxID.value elif url.startswith('https://www.wunschliste.de/spielfilm'): marker_type = "Temporärer Serien Marker" if config.plugins.serienRec.tvplaner_movies_activeSTB.value: boxID = config.plugins.serienRec.BoxID.value else: url = None if url and not database.markerExists(url): if database.addMarker(url, seriesname, "", boxID, 1 if url.startswith('https://www.wunschliste.de/spielfilm') else 0): SRLogger.writeLog("\n%s für ' %s ' wurde angelegt" % (marker_type, seriesname), True) print "[SerienRecorder] ' %s - %s erzeugt '" % (seriesname, marker_type) except Exception as e: SRLogger.writeLog("\n%s für ' %s ' konnte wegen eines Fehlers nicht angelegt werden [%s]" % (marker_type, seriesname, str(e)), True) print "[SerienRecorder] ' %s - %s konnte wegen eines Fehlers nicht angelegt werden [%s]'" % (seriesname, marker_type, str(e)) else: SRLogger.writeLog("Es werden keine Serien-Marker aus der TV-Planer E-Mail erstellt.", True) return transmissiondict
def doTimer(self, current_time, future_time, title, staffel, episode, label_serie, start_unixtime, end_unixtime, stbRef, eit, dirname, serien_name, webChannel, stbChannel, optionalText='', vomMerkzettel=False, tryDisabled=False): seasonEpisodeString = "S%sE%s" % (str(staffel).zfill(2), str(episode).zfill(2)) ############################## # # CHECK # # ueberprueft ob tage x voraus passt und ob die startzeit nicht kleiner ist als die aktuelle uhrzeit # show_start = time.strftime("%d.%m.%Y - %H:%M", time.localtime(int(start_unixtime))) if int(start_unixtime) > int(future_time): show_future = time.strftime("%d.%m.%Y - %H:%M", time.localtime(int(future_time))) SRLogger.writeLogFilter("timeLimit", "' %s ' - Timer wird evtl. später angelegt -> Sendetermin: %s - Erlaubte Zeitspanne bis %s" % (label_serie, show_start, show_future)) return True if int(current_time) > int(start_unixtime): show_current = time.strftime("%d.%m.%Y - %H:%M", time.localtime(int(current_time))) SRLogger.writeLogFilter("timeLimit", "' %s ' - Der Sendetermin liegt in der Vergangenheit: %s - Aktuelles Datum: %s" % (label_serie, show_start, show_current)) return True # get VPS settings for channel vpsSettings = self.database.getVPS(serien_name, webChannel) # get tags from marker tags = self.database.getTags(serien_name) # get addToDatabase for marker addToDatabase = self.database.getAddToDatabase(serien_name) # versuche timer anzulegen # setze strings für addtimer if STBHelpers.checkTuner(start_unixtime, end_unixtime, stbRef): if config.plugins.serienRec.TimerName.value == "0": timer_name = label_serie elif config.plugins.serienRec.TimerName.value == "2": timer_name = "%s - %s" % (seasonEpisodeString, title) else: timer_name = serien_name result = serienRecBoxTimer.addTimer(stbRef, str(start_unixtime), str(end_unixtime), timer_name, "%s - %s" % (seasonEpisodeString, title), eit, False, dirname, vpsSettings, tags, None) # SRLogger.writeLog("%s: %s => %s" % (timer_name, str(start_unixtime), str(end_unixtime)), True) if result["result"]: self.countTimer += 1 # Eintrag in die Datenbank self.addTimerToDB(serien_name, staffel, episode, title, start_unixtime, stbRef, webChannel, eit, addToDatabase) if vomMerkzettel: self.countTimerFromWishlist += 1 SRLogger.writeLog("' %s ' - Timer (vom Merkzettel) wurde angelegt%s -> %s %s @ %s" % (label_serie, optionalText, show_start, timer_name, stbChannel), True) self.database.updateBookmark(serien_name, staffel, episode) self.database.removeBookmark(serien_name, staffel, episode) else: SRLogger.writeLog("' %s ' - Timer wurde angelegt%s -> %s %s @ %s" % (label_serie, optionalText, show_start, timer_name, stbChannel), True) # Event-Programmierung verarbeiten if (config.plugins.serienRec.splitEventTimer.value == "1" or (config.plugins.serienRec.splitEventTimer.value == "2" and config.plugins.serienRec.addSingleTimersForEvent.value == "1")) and '/' in str(episode): splitedSeasonEpisodeList, splitedTitleList, useTitles = self.splitEvent(episode, staffel, title) for idx, entry in enumerate(splitedSeasonEpisodeList): splitedTitle = "dump" if useTitles: splitedTitle = splitedTitleList[idx] alreadyExists = self.database.getNumberOfTimers(serien_name, entry[0], entry[1], splitedTitle, False) if alreadyExists == 0 and addToDatabase: # Nicht vorhandene Einzelfolgen als bereits aufgenommen markieren self.database.addToTimerList(serien_name, entry[1], entry[1], entry[0], splitedTitle, int(time.time() - 10), "", "", 0, 1) SRLogger.writeLogFilter("timerDebug", " Für die Einzelepisode wird kein Timer mehr erstellt: %s S%sE%s - %s" % (serien_name, str(entry[0]).zfill(2), str(entry[1]).zfill(2), splitedTitle)) self.enableDirectoryCreation = True return True elif not tryDisabled: self.konflikt = result["message"].replace("! ", "!\n").replace(" / ", "\n") print "' %s ' - ACHTUNG! -> %s" % (label_serie, result["message"]) SRLogger.writeLog("' %s ' - Timer konnte nicht angelegt werden%s -> %s %s @ %s" % ( label_serie, optionalText, show_start, timer_name, stbChannel), True) SRLogger.writeLog("' %s ' - ACHTUNG! -> %s" % (label_serie, result["message"]), True) else: self.konflikt = result["message"].replace("! ", "!\n").replace(" / ", "\n") print "' %s ' - ACHTUNG! -> %s" % (label_serie, result["message"]) SRLogger.writeLog("' %s ' - ACHTUNG! -> %s" % (label_serie, result["message"]), True) dbMessage = result["message"].replace("In Konflikt stehende Timer vorhanden!", "").strip() result = serienRecBoxTimer.addTimer(stbRef, str(start_unixtime), str(end_unixtime), timer_name, "%s - %s" % (seasonEpisodeString, title), eit, True, dirname, vpsSettings, tags, None) if result["result"]: self.countNotActiveTimer += 1 # Eintrag in die Datenbank self.addTimerToDB(serien_name, staffel, episode, title, start_unixtime, stbRef, webChannel, eit, addToDatabase, False) self.database.addTimerConflict(dbMessage, start_unixtime, webChannel) if vomMerkzettel: self.countTimerFromWishlist += 1 SRLogger.writeLog( "' %s ' - Timer (vom Merkzettel) wurde deaktiviert angelegt%s -> %s %s @ %s" % ( label_serie, optionalText, show_start, timer_name, stbChannel), True) else: SRLogger.writeLog("' %s ' - Timer wurde deaktiviert angelegt%s -> %s %s @ %s" % ( label_serie, optionalText, show_start, timer_name, stbChannel), True) self.enableDirectoryCreation = True return True else: self.konflikt = result["message"].replace("! ", "!\n").replace(" / ", "\n") print "' %s ' - ACHTUNG! -> %s" % (label_serie, result["message"]) SRLogger.writeLog("' %s ' - ACHTUNG! -> %s" % (label_serie, result["message"]), True) else: print "Tuner belegt %s %s" % (label_serie, show_start) SRLogger.writeLog("Tuner belegt: %s %s" % (label_serie, show_start), True) return False
def createWebChannels(self, webChannelList, autoMatch): if webChannelList: webChannelList.sort(key=lambda x: x.lower()) self.serienRecChannelList = [] if len(webChannelList) != 0: self['title'].setText("Erstelle Sender-Liste...") # Get existing channels from database dbChannels = self.database.getChannelPairs() if autoMatch: # Get all unassigned web channels and try to find the STB channel equivalent # Update only matching channels in list #sql = "UPDATE OR IGNORE Channels SET STBChannel=?, ServiceRef=?, Erlaubt=? WHERE LOWER(WebChannel)=?" unassignedWebChannels = self.getUnassignedWebChannels( dbChannels) channels = [] for webChannel in unassignedWebChannels: # Unmapped web channel (servicename, serviceref ) = self.findWebChannelInSTBChannels(webChannel) if servicename and serviceref: channels.append((servicename, serviceref, 1, webChannel.lower())) self.serienRecChannelList.append( (webChannel, servicename, "", "1")) self.database.updateChannels(channels) self.changesMade = True else: # Get all new web channels (missing in SR database) (newWebChannels, removedWebChannels) = self.getMissingWebChannels( webChannelList, dbChannels) # Delete remove channels if removedWebChannels: SRLogger.writeLog( "Folgende Sender wurden bei Wunschliste nicht mehr gefunden, die Zuordnung im SerienRecorder wurde gelöscht:\n" + "\n".join(removedWebChannels), True) self.session.open( MessageBox, "Folgende Sender wurden bei Wunschliste nicht mehr gefunden,\ndie Zuordnung im SerienRecorder wurde gelöscht:\n\n" + "\n".join(removedWebChannels), MessageBox.TYPE_INFO, timeout=10) for webChannel in removedWebChannels: self.selected_sender = webChannel self.channelDelete(True) if not newWebChannels: SRLogger.writeLog( "Die SerienRecorder Senderliste ist aktuell, es wurden keine neuen Sender bei Wunschliste gefunden." ) self.session.open( MessageBox, "Die SerienRecorder Senderliste ist aktuell,\nes wurden keine neuen Sender bei Wunschliste gefunden.", MessageBox.TYPE_INFO, timeout=10) self.showChannels() else: newChannelsMessage = "Folgende Sender wurden neu bei Wunschliste gefunden:\n" + "\n".join( newWebChannels) SRLogger.writeLog(newChannelsMessage, True) self.session.open( MessageBox, "Folgende Sender wurden neu bei Wunschliste gefunden,\nsie wurden am Ende der Liste eingefügt:\n\n" + "\n".join(newWebChannels), MessageBox.TYPE_INFO, timeout=10) channels = [] for webChannel in newWebChannels: channels.append((webChannel, "", "", 0)) self.serienRecChannelList.append( (webChannel, "", "", "0")) self.database.addChannels(channels) else: print "[SerienRecorder] webChannel list leer." if len(self.serienRecChannelList) != 0: self.chooseMenuList.setList( map(self.buildList, self.serienRecChannelList)) else: print "[SerienRecorder] Fehler bei der Erstellung der SerienRecChlist." else: print "[SerienRecorder] get webChannel error." self['title'].setText("Wunschliste-Sender / STB-Sender")
def doSearch(self, serien_name, staffel, episode, title, optionalText, usedChannel): # print "doSearch: %r" % serien_name # prepare postprocessing for forced recordings forceRecordings = [] forceRecordings_W = [] eventRecordings = [] self.konflikt = "" TimerDone = False if str(episode).isdigit(): if int(episode) == 0: transmissionsForTimer = self.tempDB.getTransmissionsToCreateTimer(serien_name, staffel, episode, title) else: transmissionsForTimer = self.tempDB.getTransmissionsToCreateTimer(serien_name, staffel, episode) else: transmissionsForTimer = self.tempDB.getTransmissionsToCreateTimer(serien_name, staffel, episode) self.tempDB.beginTransaction() for transmissionForTimer in transmissionsForTimer: (current_time, future_time, serien_name, staffel, episode, check_SeasonEpisode, title, label_serie, webChannel, stbChannel, stbRef, start_unixtime, end_unixtime, eit, altstbChannel, altstbRef, alt_start_unixtime, alt_end_unixtime, alt_eit, dirname, AnzahlAufnahmen, fromTime, toTime, vomMerkzettel, excludedWeekdays, updateFromEPG) = transmissionForTimer if usedChannel == 1: timer_stbChannel = stbChannel timer_stbRef = stbRef timer_start_unixtime = start_unixtime timer_end_unixtime = end_unixtime timer_eit = eit else: timer_stbChannel = altstbChannel timer_stbRef = altstbRef timer_start_unixtime = alt_start_unixtime timer_end_unixtime = alt_end_unixtime timer_eit = alt_eit # Is channel assigned if timer_stbChannel == "": SRLogger.writeLogFilter("channels", "' %s ' - STB-Sender nicht in bevorzugter Senderliste zugewiesen -> ' %s '" % (label_serie, webChannel)) # Nicht in bevorzugter Kanalliste - dann gehen wir davon aus, dass kein Timer angelegt werden soll. TimerDone = True continue ############################## # # CHECK # # ueberprueft anhand des Seriennamen, Season, Episode ob die serie bereits auf der HDD existiert # # check ob timer existiert startTimeLowBound = int(timer_start_unixtime) - (int(STBHelpers.getEPGTimeSpan()) * 60) startTimeHighBound = int(timer_start_unixtime) + (int(STBHelpers.getEPGTimeSpan()) * 60) if self.database.timerExists(webChannel, serien_name, staffel, episode, startTimeLowBound, startTimeHighBound): SRLogger.writeLogFilter("added", "' %s ' - Timer für diese Episode%s wurde bereits erstellt -> ' %s '" % (label_serie, optionalText, check_SeasonEpisode)) if str(episode).isdigit(): if int(episode) == 0: self.tempDB.removeTransmission(serien_name, staffel, episode, title, start_unixtime, stbRef) else: self.tempDB.removeTransmission(serien_name, staffel, episode, None, start_unixtime, stbRef) else: self.tempDB.removeTransmission(serien_name, staffel, episode, None, start_unixtime, stbRef) continue # check anzahl timer und auf hdd bereits_vorhanden_HDD = 0 if str(episode).isdigit(): if int(episode) == 0: bereits_vorhanden = self.database.getNumberOfTimers(serien_name, staffel, episode, title, searchOnlyActiveTimers=True) if config.plugins.serienRec.sucheAufnahme.value: bereits_vorhanden_HDD = STBHelpers.countEpisodeOnHDD(dirname, check_SeasonEpisode, serien_name, False, title) else: bereits_vorhanden = self.database.getNumberOfTimers(serien_name, staffel, episode, searchOnlyActiveTimers=True) if config.plugins.serienRec.sucheAufnahme.value: bereits_vorhanden_HDD = STBHelpers.countEpisodeOnHDD(dirname, check_SeasonEpisode, serien_name, False) else: bereits_vorhanden = self.database.getNumberOfTimers(serien_name, staffel, episode, searchOnlyActiveTimers=True) if config.plugins.serienRec.sucheAufnahme.value: bereits_vorhanden_HDD = STBHelpers.countEpisodeOnHDD(dirname, check_SeasonEpisode, serien_name, False) if bereits_vorhanden >= AnzahlAufnahmen: SRLogger.writeLogFilter("added", "' %s ' - Eingestellte Anzahl Timer für diese Episode%s wurden bereits erstellt -> ' %s '" % (label_serie, optionalText, check_SeasonEpisode)) TimerDone = True break if bereits_vorhanden_HDD >= AnzahlAufnahmen: SRLogger.writeLogFilter("disk", "' %s ' - Episode%s bereits auf HDD vorhanden -> ' %s '" % (label_serie, optionalText, check_SeasonEpisode)) TimerDone = True break # check for excluded weekdays - this can be done early so we can skip all other checks # if the transmission date is on an excluded weekday if str(excludedWeekdays).isdigit(): print "[SerienRecorder] - Excluded weekdays check" # SRLogger.writeLog("- Excluded weekdays check", True) transmissionDate = datetime.date.fromtimestamp((int(timer_start_unixtime))) weekday = transmissionDate.weekday() print " Serie = %s, Datum = %s, Wochentag = %s" % (label_serie, time.strftime("%d.%m.%Y - %H:%M", time.localtime(int(timer_start_unixtime))), weekday) # SRLogger.writeLog(" Serie = %s, Datum = %s, Wochentag = %s" % (label_serie, time.strftime("%d.%m.%Y - %H:%M", time.localtime(int(timer_start_unixtime))), weekday), True) if excludedWeekdays & (1 << weekday) != 0: SRLogger.writeLogFilter("timeRange", "' %s ' - Wochentag auf der Ausnahmeliste -> ' %s '" % (label_serie, transmissionDate.strftime('%A'))) TimerDone = True continue if config.plugins.serienRec.splitEventTimer.value != "0" and '/' in str(episode): # Event-Programmierung auflösen -> 01/1x02/1x03 SRLogger.writeLogFilter("timerDebug", "Event-Programmierung gefunden: %s S%sE%s - %s" % (serien_name, str(staffel).zfill(2), str(episode).zfill(2), title)) splitedSeasonEpisodeList, splitedTitleList, useTitles = self.splitEvent(episode, staffel, title) alreadyExistsCount = 0 for idx, entry in enumerate(splitedSeasonEpisodeList): splitedTitle = "dump" if useTitles: splitedTitle = splitedTitleList[idx] alreadyExists = self.database.getNumberOfTimers(serien_name, entry[0], entry[1], splitedTitle, False) if alreadyExists: alreadyExistsCount += 1 if len(splitedSeasonEpisodeList) == alreadyExistsCount: # Alle Einzelfolgen wurden bereits aufgenommen - der Event muss nicht mehr aufgenommen werden. SRLogger.writeLogFilter("timerDebug", " ' %s ' - Timer für Einzelepisoden wurden bereits erstellt -> ' %s '" % (serien_name, check_SeasonEpisode)) TimerDone = True continue elif config.plugins.serienRec.splitEventTimer.value == "2": # Nicht alle Einzelfolgen wurden bereits aufgenommen, es sollen aber Einzelfolgen bevorzugt werden SRLogger.writeLogFilter("timerDebug", " ' %s ' - Versuche zunächst Timer für Einzelepisoden anzulegen" % serien_name) eventRecordings.append((title, staffel, episode, label_serie, timer_start_unixtime, timer_end_unixtime, timer_stbRef, timer_eit, dirname, serien_name, webChannel, timer_stbChannel, check_SeasonEpisode, vomMerkzettel, current_time, future_time)) continue ############################## # # CHECK # # Ueberpruefe ob der sendetermin zwischen der fromTime und toTime liegt und finde Wiederholungen auf dem gleichen Sender # # prepare valid time range if (int(fromTime) > 0) or (int(toTime) < (23 * 60) + 59): start_time = (time.localtime(int(timer_start_unixtime)).tm_hour * 60) + time.localtime(int(timer_start_unixtime)).tm_min end_time = (time.localtime(int(timer_end_unixtime)).tm_hour * 60) + time.localtime(int(timer_end_unixtime)).tm_min if not TimeHelpers.allowedTimeRange(fromTime, toTime, start_time, end_time): timeRangeString = "%s:%s-%s:%s" % (str(int(fromTime) / 60).zfill(2), str(int(fromTime) % 60).zfill(2), str(int(toTime) / 60).zfill(2), str(int(toTime) % 60).zfill(2)) timeRangeList = "[%s]" % timeRangeString SRLogger.writeLogFilter("timeRange", "' %s ' - Timer (%s) nicht in Zeitspanne %s" % (label_serie, timeRangeString, timeRangeList)) # forced recording activated? if not config.plugins.serienRec.forceRecording.value: continue # backup timer data for post processing show_start = time.strftime("%d.%m.%Y - %H:%M", time.localtime(int(timer_start_unixtime))) SRLogger.writeLogFilter("timeRange", "' %s ' - Backup Timer -> %s" % (label_serie, show_start)) forceRecordings.append((title, staffel, episode, label_serie, timer_start_unixtime, timer_end_unixtime, timer_stbRef, timer_eit, dirname, serien_name, webChannel, timer_stbChannel, check_SeasonEpisode, vomMerkzettel, current_time, future_time)) continue ############################## # # CHECK # # Ueberpruefe ob der sendetermin innerhalb der Wartezeit für Wiederholungen liegt # if config.plugins.serienRec.forceRecording.value: TimeSpan_time = int(future_time) + (int(config.plugins.serienRec.TimeSpanForRegularTimer.value) - int(config.plugins.serienRec.checkfordays.value)) * 86400 if int(timer_start_unixtime) > int(TimeSpan_time): # backup timer data for post processing show_start = time.strftime("%d.%m.%Y - %H:%M", time.localtime(int(timer_start_unixtime))) SRLogger.writeLogFilter("timeRange", "' %s ' - Backup Timer -> %s" % (label_serie, show_start)) forceRecordings_W.append((title, staffel, episode, label_serie, timer_start_unixtime, timer_end_unixtime, timer_stbRef, timer_eit, dirname, serien_name, webChannel, timer_stbChannel, check_SeasonEpisode, vomMerkzettel, current_time, future_time)) continue ############################## # # Setze Timer # if self.doTimer(current_time, future_time, title, staffel, episode, label_serie, timer_start_unixtime, timer_end_unixtime, timer_stbRef, timer_eit, dirname, serien_name, webChannel, timer_stbChannel, optionalText, vomMerkzettel): if str(episode).isdigit(): if int(episode) == 0: self.tempDB.removeTransmission(serien_name, staffel, episode, title, timer_start_unixtime, timer_stbRef) else: self.tempDB.removeTransmission(serien_name, staffel, episode, None, timer_start_unixtime, timer_stbRef) else: self.tempDB.removeTransmission(serien_name, staffel, episode, None, timer_start_unixtime, timer_stbRef) TimerDone = True break ### end of for loop self.tempDB.commitTransaction() if not TimerDone: # post processing for forced recordings for title, staffel, episode, label_serie, timer_start_unixtime, timer_end_unixtime, timer_stbRef, timer_eit, dirname, serien_name, webChannel, timer_stbChannel, check_SeasonEpisode, vomMerkzettel, current_time, future_time in forceRecordings_W: if self.database.getNumberOfTimers(serien_name, staffel, episode, title, False): continue # programmiere Timer (Wiederholung) if self.doTimer(current_time, future_time, title, staffel, episode, label_serie, timer_start_unixtime, timer_end_unixtime, timer_stbRef, timer_eit, dirname, serien_name, webChannel, timer_stbChannel, optionalText, vomMerkzettel): if str(episode).isdigit(): if int(episode) == 0: self.tempDB.removeTransmission(serien_name, staffel, episode, title, timer_start_unixtime, timer_stbRef) else: self.tempDB.removeTransmission(serien_name, staffel, episode, None, timer_start_unixtime, timer_stbRef) else: self.tempDB.removeTransmission(serien_name, staffel, episode, None, timer_start_unixtime, timer_stbRef) TimerDone = True if not TimerDone: # post processing for forced recordings for title, staffel, episode, label_serie, timer_start_unixtime, timer_end_unixtime, timer_stbRef, timer_eit, dirname, serien_name, webChannel, timer_stbChannel, check_SeasonEpisode, vomMerkzettel, current_time, future_time in forceRecordings: if self.database.getNumberOfTimers(serien_name, staffel, episode, title, False): continue show_start = time.strftime("%d.%m.%Y - %H:%M", time.localtime(int(timer_start_unixtime))) SRLogger.writeLog("' %s ' - Keine Wiederholung gefunden! -> %s" % (label_serie, show_start), True) # programmiere Timer if self.doTimer(current_time, future_time, title, staffel, episode, label_serie, timer_start_unixtime, timer_end_unixtime, timer_stbRef, timer_eit, dirname, serien_name, webChannel, timer_stbChannel, optionalText, vomMerkzettel): if str(episode).isdigit(): if int(episode) == 0: self.tempDB.removeTransmission(serien_name, staffel, episode, title, timer_start_unixtime, timer_stbRef) else: self.tempDB.removeTransmission(serien_name, staffel, episode, None, timer_start_unixtime, timer_stbRef) else: self.tempDB.removeTransmission(serien_name, staffel, episode, None, timer_start_unixtime, timer_stbRef) TimerDone = True if not TimerDone: # post processing event recordings for singleTitle, staffel, singleEpisode, label_serie, timer_start_unixtime, timer_end_unixtime, timer_stbRef, timer_eit, dirname, serien_name, webChannel, timer_stbChannel, check_SeasonEpisode, vomMerkzettel, current_time, future_time in eventRecordings[:]: if self.shouldCreateEventTimer(serien_name, staffel, singleEpisode, singleTitle): show_start = time.strftime("%d.%m.%Y - %H:%M", time.localtime(int(timer_start_unixtime))) SRLogger.writeLog(" ' %s ' - Einzelepisoden nicht gefunden! -> %s" % (label_serie, show_start), True) # programmiere Timer if self.doTimer(current_time, future_time, title, staffel, episode, label_serie, timer_start_unixtime, timer_end_unixtime, timer_stbRef, timer_eit, dirname, serien_name, webChannel, timer_stbChannel, optionalText, vomMerkzettel): TimerDone = True return TimerDone
def activate(self): # versuche deaktivierte Timer zu aktivieren oder auf anderer Box zu erstellen from enigma import eEPGCache deactivatedTimers = self.database.getDeactivatedTimers() for deactivatedTimer in deactivatedTimers: (serien_name, staffel, episode, serien_title, serien_time, stbRef, webChannel, eit) = deactivatedTimer if eit > 0: recordHandler = NavigationInstance.instance.RecordTimer (dirname, dirname_serie) = getDirname(self.database, serien_name, staffel) try: timerFound = False # suche in deaktivierten Timern for timer in recordHandler.processed_timers: if timer and timer.service_ref: if (timer.begin == serien_time) and (timer.eit == eit) and ( str(timer.service_ref).lower() == stbRef.lower()): # versuche deaktivierten Timer zu aktivieren label_serie = "%s - S%sE%s - %s" % ( serien_name, str(staffel).zfill(2), str(episode).zfill(2), serien_title) if config.plugins.serienRec.TimerName.value == "0": timer_name = label_serie elif config.plugins.serienRec.TimerName.value == "2": timer_name = "S%sE%s - %s" % ( str(staffel).zfill(2), str(episode).zfill(2), serien_title) else: timer_name = serien_name SRLogger.writeLog("Versuche deaktivierten Timer zu aktivieren: ' %s - %s '" % ( serien_title, dirname)) if STBHelpers.checkTuner(str(timer.begin), str(timer.end), str(timer.service_ref)): from Components.TimerSanityCheck import TimerSanityCheck timer.disabled = False timersanitycheck = TimerSanityCheck(recordHandler.timer_list, timer) if timersanitycheck.check(): self.countTimerUpdate += 1 NavigationInstance.instance.RecordTimer.timeChanged(timer) # Eintrag in das timer file self.database.activateTimer(serien_name, staffel, episode, serien_title, serien_time, stbRef, webChannel, eit) show_start = time.strftime("%d.%m.%Y - %H:%M", time.localtime(int(serien_time))) SRLogger.writeLog("' %s ' - Timer wurde aktiviert -> %s %s @ %s" % ( label_serie, show_start, timer_name, webChannel), True) timer.log(0, "[SerienRecorder] Activated timer") else: timer.disabled = True timerFound = True break if not timerFound: # suche in (manuell) aktivierten Timern for timer in recordHandler.timer_list: if timer and timer.service_ref: if (timer.begin == serien_time) and (timer.eit == eit) and ( str(timer.service_ref).lower() == stbRef.lower()): # Eintrag in das timer file self.database.activateTimer(serien_name, staffel, episode, serien_title, serien_time, stbRef, webChannel, eit) timerFound = True break if not timerFound: # versuche deaktivierten Timer (auf anderer Box) zu erstellen (margin_before, margin_after) = self.database.getMargins(serien_name, webChannel, config.plugins.serienRec.margin_before.value, config.plugins.serienRec.margin_after.value) # get VPS settings for channel vpsSettings = self.database.getVPS(serien_name, webChannel) # get tags from marker tags = self.database.getTags(serien_name) # get addToDatabase for marker addToDatabase = self.database.getAddToDatabase(serien_name) epgcache = eEPGCache.getInstance() allevents = epgcache.lookupEvent(['IBD', (stbRef, 2, eit, -1)]) or [] for eventid, begin, duration in allevents: if int(begin) == (int(serien_time) + (int(margin_before) * 60)): label_serie = "%s - S%sE%s - %s" % ( serien_name, str(staffel).zfill(2), str(episode).zfill(2), serien_title) if config.plugins.serienRec.TimerName.value == "0": timer_name = label_serie elif config.plugins.serienRec.TimerName.value == "2": timer_name = "S%sE%s - %s" % ( str(staffel).zfill(2), str(episode).zfill(2), serien_title) else: timer_name = serien_name SRLogger.writeLog("Versuche deaktivierten Timer aktiv zu erstellen: ' %s - %s '" % ( serien_title, dirname)) end_unixtime = int(begin) + int(duration) end_unixtime = int(end_unixtime) + (int(margin_after) * 60) result = serienRecBoxTimer.addTimer(stbRef, str(serien_time), str(end_unixtime), timer_name, "S%sE%s - %s" % ( str(staffel).zfill(2), str(episode).zfill(2), serien_title), eit, False, dirname, vpsSettings, tags, None) if result["result"]: self.countTimer += 1 if addToDatabase: # Eintrag in das timer file self.database.activateTimer(serien_name, staffel, episode, serien_title, serien_time, stbRef, webChannel, eit) show_start = time.strftime("%d.%m.%Y - %H:%M", time.localtime(int(serien_time))) SRLogger.writeLog("' %s ' - Timer wurde angelegt -> %s %s @ %s" % (label_serie, show_start, timer_name, webChannel), True) break except: pass
def imaptest(session): try: if config.plugins.serienRec.imap_server_ssl.value: mail = imaplib.IMAP4_SSL(config.plugins.serienRec.imap_server.value, config.plugins.serienRec.imap_server_port.value) else: mail = imaplib.IMAP4(config.plugins.serienRec.imap_server.value, config.plugins.serienRec.imap_server_port.value) except: session.open(MessageBox, "Verbindung zum E-Mail Server fehlgeschlagen", MessageBox.TYPE_INFO, timeout=10) SRLogger.writeLog("IMAP Check: Verbindung zum Server fehlgeschlagen", True) return None try: mail.login(decrypt(getmac("eth0"), config.plugins.serienRec.imap_login_hidden.value), decrypt(getmac("eth0"), config.plugins.serienRec.imap_password_hidden.value)) except imaplib.IMAP4.error: session.open(MessageBox, "Anmeldung am E-Mail Server fehlgeschlagen", MessageBox.TYPE_INFO, timeout=10) SRLogger.writeLog("IMAP Check: Anmeldung auf Server fehlgeschlagen", True) return None try: import string SRLogger.writeLog("Postfächer:", True) result, data = mail.list('""', '*') if result == 'OK': for item in data[:]: x = item.split() mailbox = string.join(x[2:]) SRLogger.writeLog("%s" % mailbox, True) except imaplib.IMAP4.error: session.open(MessageBox, "Abrufen der Postfächer vom E-Mail Server fehlgeschlagen", MessageBox.TYPE_INFO, timeout=10) SRLogger.writeLog("IMAP Check: Abrufen der Postfächer fehlgeschlagen", True) try: mail.select(config.plugins.serienRec.imap_mailbox.value) except imaplib.IMAP4.error: session.open(MessageBox, "Postfach [%r] nicht gefunden" % config.plugins.serienRec.imap_mailbox.value, MessageBox.TYPE_INFO, timeout=10) SRLogger.writeLog("IMAP Check: Mailbox %r nicht gefunden" % config.plugins.serienRec.imap_mailbox.value, True) mail.logout() return None searchstr = TimeHelpers.getMailSearchString() SRLogger.writeLog("IMAP Check: %s" % searchstr, True) try: result, data = mail.uid('search', None, searchstr) SRLogger.writeLog("IMAP Check: %s (%d)" % (result, len(data[0].split(' '))), True) if result != 'OK': SRLogger.writeLog("IMAP Check: %s" % data, True) except imaplib.IMAP4.error: session.open(MessageBox, "Fehler beim Abrufen der TV-Planer E-Mail", MessageBox.TYPE_INFO, timeout=10) SRLogger.writeLog("IMAP Check: Fehler beim Abrufen der Mailbox", True) SRLogger.writeLog("IMAP Check: %s" % mail.error.message, True) mail.logout() session.open(MessageBox, "IMAP Test abgeschlossen - siehe Log", MessageBox.TYPE_INFO, timeout=10)
def initDB(): # type: () -> object global serienRecDataBaseFilePath # If database is at old default location (SerienRecorder plugin folder) we have to move the db to new default location if fileExists("%sSerienRecorder.db" % serienRecMainPath): shutil.move("%sSerienRecorder.db" % serienRecMainPath, serienRecDataBaseFilePath) if not fileExists(serienRecDataBaseFilePath): config.plugins.serienRec.databasePath.value = "/etc/enigma2/" config.plugins.serienRec.databasePath.save() configfile.save() SRLogger.writeLog("Datenbankpfad nicht gefunden, auf Standardpfad zurückgesetzt!") print "[SerienRecorder] Datenbankpfad nicht gefunden, auf Standardpfad zurückgesetzt!" Notifications.AddPopup( "SerienRecorder Datenbank wurde nicht gefunden.\nDer Standardpfad für die Datenbank wurde wiederhergestellt!", MessageBox.TYPE_INFO, timeout=10) serienRecDataBaseFilePath = "%sSerienRecorder.db" % config.plugins.serienRec.databasePath.value try: database = SRDatabase(serienRecDataBaseFilePath) except: SRLogger.writeLog("Fehler beim Initialisieren der Datenbank") print "[SerienRecorder] Fehler beim Initialisieren der Datenbank" Notifications.AddPopup("SerienRecorder Datenbank kann nicht initialisiert werden.\nSerienRecorder wurde beendet!", MessageBox.TYPE_INFO, timeout=10) return False if os.path.getsize(serienRecDataBaseFilePath) == 0: database.initialize(config.plugins.serienRec.dbversion.value) else: dbVersionMatch = False dbIncompatible = False dbVersion = database.getVersion() if dbVersion: if dbVersion == config.plugins.serienRec.dbversion.value: dbVersionMatch = True elif dbVersion > config.plugins.serienRec.dbversion.value: SRLogger.writeLog("Datenbankversion nicht kompatibel: SerienRecorder Version muss mindestens %s sein." % dbVersion) Notifications.AddPopup("Die SerienRecorder Datenbank ist mit dieser Version nicht kompatibel.\nAktualisieren Sie mindestens auf die SerienRecorder Version %s!" % dbVersion, MessageBox.TYPE_INFO, timeout=10) dbIncompatible = True else: dbIncompatible = True mode = os.R_OK | os.W_OK if not os.access(serienRecDataBaseFilePath, mode): SRLogger.writeLog("Datenbankdatei hat nicht die richtigen Berechtigungen - es müssen Lese- und Schreibrechte gesetzt sein.") Notifications.AddPopup("Datenbankdatei hat nicht die richtigen Berechtigungen - es müssen Lese- und Schreibrechte gesetzt sein.", MessageBox.TYPE_INFO, timeout=10) dbIncompatible = True # Database incompatible - do cleanup if dbIncompatible: database.close() return False if not dbVersionMatch: SRLogger.writeLog("Datenbank ist zu alt - sie muss aktualisiert werden...", True) database.close() backupSerienRecDataBaseFilePath = "%sSerienRecorder_old.db" % config.plugins.serienRec.databasePath.value SRLogger.writeLog("Erstelle Datenbank Backup - es kann nach erfolgreichem Update gelöscht werden: %s" % backupSerienRecDataBaseFilePath, True) shutil.copy(serienRecDataBaseFilePath, backupSerienRecDataBaseFilePath) database = SRDatabase(serienRecDataBaseFilePath) if database.update(config.plugins.serienRec.dbversion.value): SRLogger.writeLog("Datenbank von Version %s auf Version %s aktualisiert" % (dbVersion, config.plugins.serienRec.dbversion.value), True) else: database.close() Notifications.AddPopup("SerienRecorder Datenbank konnte nicht aktualisiert werden. Fehler wurden in die Logdatei geschrieben.\nSerienRecorder wurde beendet!", MessageBox.TYPE_INFO, timeout=10) return False # Analyze database for query optimizer try: database.optimize() except Exception as e: database.close() SRLogger.writeLog("Fehler beim Zugriff auf die Datenbank [%s]" % str(e)) Notifications.AddPopup("Fehler beim Zugriff auf die Datenbank!\n%s" % str(e), MessageBox.TYPE_INFO, timeout=10) return False database.close() return True
def imaptest(session): try: if config.plugins.serienRec.imap_server_ssl.value: mail = imaplib.IMAP4_SSL(config.plugins.serienRec.imap_server.value, config.plugins.serienRec.imap_server_port.value) else: mail = imaplib.IMAP4(config.plugins.serienRec.imap_server.value, config.plugins.serienRec.imap_server_port.value) except: session.open(MessageBox, "Verbindung zum E-Mail Server fehlgeschlagen", MessageBox.TYPE_INFO, timeout=10) SRLogger.writeLog("IMAP Check: Verbindung zum Server fehlgeschlagen", True) return None try: mail.login(decrypt(getmac("eth0"), config.plugins.serienRec.imap_login_hidden.value), decrypt(getmac("eth0"), config.plugins.serienRec.imap_password_hidden.value)) except imaplib.IMAP4.error: session.open(MessageBox, "Anmeldung am E-Mail Server fehlgeschlagen", MessageBox.TYPE_INFO, timeout=10) SRLogger.writeLog("IMAP Check: Anmeldung auf Server fehlgeschlagen", True) return None try: import string SRLogger.writeLog("Postfächer:", True) result, data = mail.list('""', '*') if result == 'OK': for item in data[:]: x = item.split() mailbox = string.join(x[2:]) SRLogger.writeLog("%s" % mailbox, True) except imaplib.IMAP4.error: session.open(MessageBox, "Abrufen der Postfächer vom E-Mail Server fehlgeschlagen", MessageBox.TYPE_INFO, timeout=10) SRLogger.writeLog("IMAP Check: Abrufen der Postfächer fehlgeschlagen", True) try: mail.select(config.plugins.serienRec.imap_mailbox.value) except imaplib.IMAP4.error: session.open(MessageBox, "Postfach [%r] nicht gefunden" % config.plugins.serienRec.imap_mailbox.value, MessageBox.TYPE_INFO, timeout=10) SRLogger.writeLog("IMAP Check: Mailbox %r nicht gefunden" % config.plugins.serienRec.imap_mailbox.value, True) mail.logout() return None searchstr = TimeHelpers.getMailSearchString() SRLogger.writeLog("IMAP Check: %s" % searchstr, True) try: result, data = mail.uid('search', None, searchstr) SRLogger.writeLog("IMAP Check: %s (%d)" % (result, len(data[0].split(' '))), True) if result != 'OK': SRLogger.writeLog("IMAP Check: %s" % data, True) except imaplib.IMAP4.error: session.open(MessageBox, "Fehler beim Abrufen der TV-Planer E-Mail", MessageBox.TYPE_INFO, timeout=10) SRLogger.writeLog("IMAP Check: Fehler beim Abrufen der Mailbox", True) SRLogger.writeLog("IMAP Check: %s" % mail.error.message, True) mail.logout() session.open(MessageBox, "IMAP Test abgeschlossen - siehe Log", MessageBox.TYPE_INFO, timeout=10)
def __init__(self, session, manuell, tvplaner_manuell=False): assert not serienRecCheckForRecording.instance, "Go is a singleton class!" serienRecCheckForRecording.instance = self self.session = session self.database = None self.manuell = manuell self.tvplaner_manuell = tvplaner_manuell print "[SerienRecorder] 1__init__ tvplaner_manuell: ", tvplaner_manuell self.newSeriesOrEpisodesFound = False self.senderListe = {} self.markers = [] self.messageList = [] self.speedStartTime = 0 self.speedEndTime = 0 self.konflikt = "" self.count_url = 0 self.countSerien = 0 self.countActivatedSeries = 0 self.noOfRecords = int(config.plugins.serienRec.NoOfRecords.value) self.emailData = None SRLogger.checkFileAccess() lt = time.localtime() self.uhrzeit = time.strftime("%d.%m.%Y - %H:%M:%S", lt) SRLogger.writeLog("\n---------' %s '---------" % self.uhrzeit, True) self.daypage = 0 global refreshTimer if refreshTimer: refreshTimer.stop() refreshTimer = None global refreshTimerConnection if refreshTimerConnection: refreshTimerConnection = None self.tempDB = None if config.plugins.serienRec.autochecktype.value == "0": SRLogger.writeLog("Auto-Check ist deaktiviert - nur manuelle Timersuche", True) elif config.plugins.serienRec.autochecktype.value == "1": SRLogger.writeLog("Auto-Check ist aktiviert - er wird zur gewählten Uhrzeit gestartet", True) elif config.plugins.serienRec.autochecktype.value == "2": SRLogger.writeLog("Auto-Check ist aktiviert - er wird nach dem EPGRefresh ausgeführt", True) if not self.manuell and config.plugins.serienRec.autochecktype.value == "1" and config.plugins.serienRec.timeUpdate.value: deltatime = self.getNextAutoCheckTimer(lt) refreshTimer = eTimer() if isDreamOS(): refreshTimerConnection = refreshTimer.timeout.connect(self.startCheck) else: refreshTimer.callback.append(self.startCheck) refreshTimer.start(((deltatime * 60) + random.randint(0, int(config.plugins.serienRec.maxDelayForAutocheck.value)*60)) * 1000, True) print "[SerienRecorder] Auto-Check Uhrzeit-Timer gestartet." print "[SerienRecorder] Verbleibende Zeit: %s Stunden" % (TimeHelpers.td2HHMMstr(datetime.timedelta(minutes=deltatime+int(config.plugins.serienRec.maxDelayForAutocheck.value)))) SRLogger.writeLog("Verbleibende Zeit bis zum nächsten Auto-Check: %s Stunden\n" % TimeHelpers.td2HHMMstr(datetime.timedelta(minutes=deltatime+int(config.plugins.serienRec.maxDelayForAutocheck.value))), True) if self.manuell: print "[SerienRecorder] checkRecTimer manuell." self.startCheck() self.manuell = False self.tvplaner_manuell = False else: try: from Plugins.Extensions.EPGRefresh.EPGRefresh import epgrefresh self.epgrefresh_instance = epgrefresh config.plugins.serienRec.autochecktype.addNotifier(self.setEPGRefreshCallback) except Exception as e: SRLogger.writeLog("EPGRefresh plugin nicht installiert! " + str(e), True)
def run(self): try: from SerienRecorderSeriesServer import SeriesServer self.planerData = SeriesServer().doGetPlanerData(self.daypage, self.webChannels) except: SRLogger.writeLog("Fehler beim Abrufen und Verarbeiten der SerienPlaner-Daten [%s]\n" % str(self.daypage), True)
def search(self, NoOfRecords): if NoOfRecords: optionalText = " (%s. Wiederholung)" % NoOfRecords else: optionalText = "" SRLogger.writeLog("\n---------' Erstelle Timer%s '---------\n" % optionalText, True) transmissions = self.tempDB.getTransmissionsOrderedByNumberOfRecordings(NoOfRecords) for transmission in transmissions: (serien_name, staffel, episode, title, anzahl) = transmission (noOfRecords, preferredChannel, useAlternativeChannel) = self.database.getPreferredMarkerChannels(serien_name, config.plugins.serienRec.useAlternativeChannel.value, config.plugins.serienRec.NoOfRecords.value) (dirname, dirname_serie) = getDirname(self.database, serien_name, staffel) self.enableDirectoryCreation = False self.konflikt = "" TimerDone = self.doSearch(serien_name, staffel, episode, title, optionalText, preferredChannel) if (not TimerDone) and useAlternativeChannel: if preferredChannel == 1: usedChannel = 2 else: usedChannel = 1 TimerDone = self.doSearch(serien_name, staffel, episode, title, optionalText, usedChannel) # Setze deaktivierten Timer if not TimerDone: if str(episode).isdigit(): if int(episode) == 0: transmissionsForTimer = self.tempDB.getTransmissionsToCreateTimer(serien_name, staffel, episode, title) else: transmissionsForTimer = self.tempDB.getTransmissionsToCreateTimer(serien_name, staffel, episode) else: transmissionsForTimer = self.tempDB.getTransmissionsToCreateTimer(serien_name, staffel, episode) for transmissionForTimer in transmissionsForTimer: (current_time, future_time, serien_name, staffel, episode, check_SeasonEpisode, title, label_serie, webChannel, stbChannel, stbRef, start_unixtime, end_unixtime, eit, altstbChannel, altstbRef, alt_start_unixtime, alt_end_unixtime, alt_eit, dirname, AnzahlAufnahmen, fromTime, toTime, vomMerkzettel, excludedWeekdays, updateFromEPG) = transmissionForTimer if preferredChannel == 1: timer_stbChannel = stbChannel timer_stbRef = stbRef timer_start_unixtime = start_unixtime timer_end_unixtime = end_unixtime timer_eit = eit else: timer_stbChannel = altstbChannel timer_stbRef = altstbRef timer_start_unixtime = alt_start_unixtime timer_end_unixtime = alt_end_unixtime timer_eit = alt_eit ############################## # # Setze deaktivierten Timer # # Ueberpruefe ob der sendetermin zwischen der fromTime und toTime liegt start_time = (time.localtime(int(timer_start_unixtime)).tm_hour * 60) + time.localtime(int(timer_start_unixtime)).tm_min end_time = (time.localtime(int(timer_end_unixtime)).tm_hour * 60) + time.localtime(int(timer_end_unixtime)).tm_min if TimeHelpers.allowedTimeRange(fromTime, toTime, start_time, end_time): if self.doTimer(current_time, future_time, title, staffel, episode, label_serie, timer_start_unixtime, timer_end_unixtime, timer_stbRef, timer_eit, dirname, serien_name, webChannel, timer_stbChannel, optionalText, vomMerkzettel, True): if str(episode).isdigit(): if int(episode) == 0: self.tempDB.removeTransmission(serien_name, staffel, episode, title, start_unixtime, stbRef) else: self.tempDB.removeTransmission(serien_name, staffel, episode, None, start_unixtime, stbRef) else: self.tempDB.removeTransmission(serien_name, staffel, episode, None, start_unixtime, stbRef) break if len(self.konflikt) > 0: if config.plugins.serienRec.showMessageOnConflicts.value: self.messageList.append(("Timerkonflikte beim SerienRecorder Suchlauf:\n%s" % self.konflikt, MessageBox.TYPE_INFO, -1, self.konflikt)) Notifications.AddPopup("Timerkonflikte beim SerienRecorder Suchlauf:\n%s" % self.konflikt, MessageBox.TYPE_INFO, timeout=-1, id=self.konflikt) ############################## # # erstellt das serien verzeichnis if TimerDone and self.enableDirectoryCreation: STBHelpers.createDirectory(serien_name, dirname, dirname_serie)