def getCover(self, serienName): serien_id = None from SerienRecorder import serienRecDataBaseFilePath, getCover database = SRDatabase(serienRecDataBaseFilePath) url = database.getMarkerURL(serienName) if url: serien_id = url getCover(self, serienName, serien_id)
def __init__(self, session): serienRecBaseScreen.__init__(self, session) Screen.__init__(self, session) HelpableScreen.__init__(self) self.skin = None self.conflictsListe = [] self.session = session self.database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) self["actions"] = HelpableActionMap(self, "SerienRecorderActions", { "cancel": (self.keyCancel, "zurück zur vorherigen Ansicht"), "left": (self.keyLeft, "zur vorherigen Seite blättern"), "right": (self.keyRight, "zur nächsten Seite blättern"), "up": (self.keyUp, "eine Zeile nach oben"), "down": (self.keyDown, "eine Zeile nach unten"), "red": (self.keyCancel, "zurück zur vorherigen Ansicht"), "blue": (self.keyBlue, "alle Einträge aus der Liste endgültig löschen"), "menu": (self.recSetup, "Menü für globale Einstellungen öffnen"), "0" : (self.readLogFile, "Log-File des letzten Suchlaufs anzeigen"), "3" : (self.showProposalDB, "Liste der Serien/Staffel-Starts anzeigen"), "7" : (self.showWishlist, "Merkzettel (vorgemerkte Folgen) anzeigen"), }, -1) self.helpList[0][2].sort() self["helpActions"] = ActionMap(["SerienRecorderActions" ,], { "displayHelp" : self.showHelp, "displayHelp_long" : self.showManual, }, 0) self.setupSkin() self.onLayoutFinish.append(self.readConflicts) self.onClose.append(self.__onClose) self.onLayoutFinish.append(self.setSkinProperties)
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 __init__(self): self.countTimer = 0 self.countTimerUpdate = 0 self.countNotActiveTimer = 0 self.countTimerFromWishlist = 0 self.messageList = [] self.database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) self.tempDB = None self.konflikt = "" self.enableDirectoryCreation = False
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 __init__(self, session, skip=True): serienRecBaseScreen.__init__(self, session) Screen.__init__(self, session) HelpableScreen.__init__(self) self.session = session self.picload = ePicLoad() self.database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) self.chooseMenuList_popup = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self["actions"] = HelpableActionMap(self, "SerienRecorderActions", { "ok": (self.keyOK, "für die ausgewählte Serien neue Einträge hinzufügen"), "cancel": (self.keyCancel, "alle Änderungen verwerfen und zurück zur vorherigen Ansicht"), "left": (self.keyLeft, "zur vorherigen Seite blättern"), "right": (self.keyRight, "zur nächsten Seite blättern"), "up": (self.keyUp, "eine Zeile nach oben"), "down": (self.keyDown, "eine Zeile nach unten"), "red": (self.keyRed, "ausgewählten Eintrag löschen"), "green": (self.keyGreen, "alle Änderungen speichern und zurück zur vorherigen Ansicht"), "yellow": (self.keyYellow, "umschalten Sortierung ein/aus"), "menu": (self.recSetup, "Menü für globale Einstellungen öffnen"), "0" : (self.readLogFile, "Log-File des letzten Suchlaufs anzeigen"), "3" : (self.showProposalDB, "Liste der Serien/Staffel-Starts anzeigen"), "4" : (self.serieInfo, "Informationen zur ausgewählten Serie anzeigen"), "6" : (self.showConflicts, "Liste der Timer-Konflikte anzeigen"), "7" : (self.showWishlist, "Merkzettel (vorgemerkte Folgen) anzeigen"), }, -1) self.helpList[0][2].sort() self["helpActions"] = ActionMap(["SerienRecorderActions" ,], { "displayHelp" : self.showHelp, "displayHelp_long" : self.showManual, }, 0) self.setupSkin() self.delAdded = False self.addedlist = [] self.addedlist_tmp = [] self.dbData = [] self.modus = "menu_list" self.aSerie = "" self.aStaffel = "0" self.aFromEpisode = 0 self.aToEpisode = 0 if skip: self.onShown.append(self.functionWillBeDeleted) else: self.onLayoutFinish.append(self.readAdded) self.onClose.append(self.__onClose) self.onLayoutFinish.append(self.setSkinProperties)
def __init__(self, session): serienRecBaseScreen.__init__(self, session) Screen.__init__(self, session) HelpableScreen.__init__(self) self.modus = "menu_list" self.session = session self.picload = ePicLoad() self.ErrorMsg = "unbekannt" self.piconLoader = PiconLoader() self.picloader = None self.filter = False self.database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) self.changesMade = False self["actions"] = HelpableActionMap(self, "SerienRecorderActions", { "ok": (self.keyOK, "Marker für die ausgewählte Serie hinzufügen"), "cancel": (self.keyCancel, "zurück zur vorherigen Ansicht"), "left": (self.keyLeft, "zur vorherigen Seite blättern"), "right": (self.keyRight, "zur nächsten Seite blättern"), "up": (self.keyUp, "eine Zeile nach oben"), "down": (self.keyDown, "eine Zeile nach unten"), "menu": (self.recSetup, "Menü für globale Einstellungen öffnen"), "yellow": (self.keyYellow, "Zeige nur Serien-Starts"), "startTeletext": (self.wunschliste, "Informationen zur ausgewählten Serie auf Wunschliste anzeigen"), "0" : (self.readLogFile, "Log-File des letzten Suchlaufs anzeigen"), "4" : (self.serieInfo, "Informationen zur ausgewählten Serie anzeigen"), "6" : (self.showConflicts, "Liste der Timer-Konflikte anzeigen"), "7" : (self.showWishlist, "Merkzettel (vorgemerkte Folgen) anzeigen"), }, -1) self.helpList[0][2].sort() self["helpActions"] = ActionMap(["SerienRecorderActions" ,], { "displayHelp" : self.showHelp, "displayHelp_long" : self.showManual, }, 0) self.setupSkin() self.timer_default = eTimer() if isDreamOS(): self.timer_default_conn = self.timer_default.timeout.connect(self.readProposal) else: self.timer_default.callback.append(self.readProposal) self.proposalList = [] self.transmissions = {} self.serviceRefs = self.database.getActiveServiceRefs() self.onLayoutFinish.append(self.setSkinProperties) self.onLayoutFinish.append(self.__onLayoutFinish) self.onClose.append(self.__onClose)
def __init__(self, session): serienRecBaseScreen.__init__(self, session) Screen.__init__(self, session) HelpableScreen.__init__(self) self.skin = None self.session = session self.picload = ePicLoad() self.WochenTag = ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"] self.database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) self["actions"] = HelpableActionMap(self, "SerienRecorderActions", { "ok": (self.keyOK, "Liste der erstellten Timer bearbeiten"), "cancel": (self.keyCancel, "zurück zur Serienplaner-Ansicht"), "left": (self.keyLeft, "zur vorherigen Seite blättern"), "right": (self.keyRight, "zur nächsten Seite blättern"), "up": (self.keyUp, "eine Zeile nach oben"), "down": (self.keyDown, "eine Zeile nach unten"), "red": (self.keyRed, "ausgewählten Timer löschen"), "green": (self.viewChange, "Sortierung ändern"), "yellow": (self.keyYellow, "umschalten alle/nur aktive Timer anzeigen"), "blue": (self.keyBlue, "alle noch ausstehenden Timer löschen"), "menu": (self.recSetup, "Menü für globale Einstellungen öffnen"), "startTeletext": (self.wunschliste, "Informationen zur ausgewählten Serie auf Wunschliste anzeigen"), "0" : (self.readLogFile, "Log-File des letzten Suchlaufs anzeigen"), "3" : (self.showProposalDB, "Liste der Serien/Staffel-Starts anzeigen"), "4" : (self.serieInfo, "Informationen zur ausgewählten Serie anzeigen"), "6" : (self.showConflicts, "Liste der Timer-Konflikte anzeigen"), "7" : (self.showWishlist, "Merkzettel (vorgemerkte Folgen) anzeigen"), "9" : (self.dropAllTimer, "Alle Timer aus der Datenbank löschen"), }, -1) self.helpList[0][2].sort() self["helpActions"] = ActionMap(["SerienRecorderActions" ,], { # "ok" : self.keyOK, "displayHelp" : self.showHelp, "displayHelp_long" : self.showManual, }, 0) self.setupSkin() self.changesMade = False self.filter = True self.onLayoutFinish.append(self.readTimer) self.onClose.append(self.__onClose) self.onLayoutFinish.append(self.setSkinProperties)
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(): self.keyCancel() self.close() return 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() if not showMainScreen: from SerienRecorderMarkerScreen import serienRecMarker self.session.openWithCallback(self.readPlanerData, serienRecMarker) else: self.readPlanerData(False)
class serienRecChannelSetup(serienRecBaseScreen, Screen, ConfigListScreen, HelpableScreen): def __init__(self, session, webSender): serienRecBaseScreen.__init__(self, session) Screen.__init__(self, session) HelpableScreen.__init__(self) self.session = session self.webSender = webSender from SerienRecorder import serienRecDataBaseFilePath from SerienRecorderDatabase import SRDatabase self.database = SRDatabase(serienRecDataBaseFilePath) self["actions"] = HelpableActionMap( self, "SerienRecorderActions", { "red": (self.cancel, "Änderungen verwerfen und zurück zur Sender-Ansicht"), "green": (self.save, "Einstellungen speichern und zurück zur Sender-Ansicht"), "cancel": (self.cancel, "Änderungen verwerfen und zurück zur Sender-Ansicht"), "ok": (self.ok, "---"), "up": (self.keyUp, "eine Zeile nach oben"), "down": (self.keyDown, "eine Zeile nach unten"), "startTeletext": (self.showAbout, "Über dieses Plugin"), }, -1) self.helpList[0][2].sort() self["helpActions"] = ActionMap( [ "SerienRecorderActions", ], { "ok": self.ok, "displayHelp": self.showHelp, "displayHelp_long": self.showManual, }, 0) self.setupSkin() if config.plugins.serienRec.showAllButtons.value: setMenuTexts(self) (Vorlaufzeit, Nachlaufzeit, vps, autoAdjust) = self.database.getChannelsSettings(self.webSender) if str(Vorlaufzeit).isdigit(): self.margin_before = ConfigInteger(Vorlaufzeit, (0, 99)) self.enable_margin_before = ConfigYesNo(default=True) else: self.margin_before = ConfigInteger( config.plugins.serienRec.margin_before.value, (0, 99)) self.enable_margin_before = ConfigYesNo(default=False) if str(Nachlaufzeit).isdigit(): self.margin_after = ConfigInteger(Nachlaufzeit, (0, 99)) self.enable_margin_after = ConfigYesNo(default=True) else: self.margin_after = ConfigInteger( config.plugins.serienRec.margin_after.value, (0, 99)) self.enable_margin_after = ConfigYesNo(default=False) if str(vps).isdigit(): self.enable_vps = ConfigYesNo(default=bool(vps & 0x1)) self.enable_vps_savemode = ConfigYesNo(default=bool(vps & 0x2)) else: self.enable_vps = ConfigYesNo(default=False) self.enable_vps_savemode = ConfigYesNo(default=False) if str(autoAdjust).isdigit(): self.autoAdjust = ConfigYesNo(default=bool(autoAdjust)) self.enable_autoAdjust = ConfigYesNo(default=True) else: self.autoAdjust = ConfigYesNo(default=False) self.enable_autoAdjust = ConfigYesNo(default=False) self.changedEntry() ConfigListScreen.__init__(self, self.list) self.setInfoText() self['config_information_text'].setText( self.HilfeTexte[self.enable_margin_before]) self.onLayoutFinish.append(self.setSkinProperties) def callHelpAction(self, *args): HelpableScreen.callHelpAction(self, *args) def setSkinProperties(self): super(self.__class__, self).setSkinProperties() self.num_bt_text = ([buttonText_na, buttonText_na, "Abbrechen"], [ buttonText_na, buttonText_na, buttonText_na ], [buttonText_na, buttonText_na, buttonText_na], [buttonText_na, buttonText_na, "Hilfe"], [buttonText_na, buttonText_na, buttonText_na]) self['text_red'].setText("Abbrechen") self['text_green'].setText("Speichern") super(self.__class__, self).startDisplayTimer() def setupSkin(self): self.skin = None InitSkin(self) self['config'] = ConfigList([]) self['config'].show() self['config_information'].show() self['config_information_text'].show() self['title'].setText("Senderzuordnung - Einstellungen für '%s':" % self.webSender) if not config.plugins.serienRec.showAllButtons.value: self['text_0'].setText("Abbrechen") self['text_1'].setText("About") self['bt_red'].show() self['bt_green'].show() self['bt_blue'].show() self['bt_ok'].show() self['bt_exit'].show() self['bt_text'].show() self['text_red'].show() self['text_green'].show() self['text_blue'].show() self['text_ok'].show() self['text_0'].show() self['text_1'].show() self['text_2'].show() self['text_3'].show() self['text_4'].show() else: self['text_0'].hide() self['text_1'].hide() self['text_2'].hide() self['text_3'].hide() self['text_4'].hide() self['text_5'].hide() self['text_6'].hide() self['text_7'].hide() self['text_8'].hide() self['text_9'].hide() self['bt_0'].hide() self['bt_1'].hide() self['bt_2'].hide() self['bt_3'].hide() self['bt_4'].hide() self['bt_5'].hide() self['bt_6'].hide() self['bt_7'].hide() self['bt_8'].hide() self['bt_9'].hide() def createConfigList(self): self.margin_after_index = 1 self.list = [] self.list.append( getConfigListEntry( "vom globalen Setup abweichenden Timervorlauf aktivieren:", self.enable_margin_before)) if self.enable_margin_before.value: self.list.append( getConfigListEntry(" Timervorlauf (in Min.):", self.margin_before)) self.margin_after_index += 1 self.list.append( getConfigListEntry( "vom globalen Setup abweichenden Timernachlauf aktivieren:", self.enable_margin_after)) if self.enable_margin_after.value: self.list.append( getConfigListEntry(" Timernachlauf (in Min.):", self.margin_after)) from SerienRecorder import VPSPluginAvailable if VPSPluginAvailable: self.list.append( getConfigListEntry("VPS für diesen Sender aktivieren:", self.enable_vps)) if self.enable_vps.value: self.list.append( getConfigListEntry(" Sicherheitsmodus aktivieren:", self.enable_vps_savemode)) if isVTI(): self.list.append( getConfigListEntry( "Aufnahmezeitenanpassung aus den EPG Daten für diesen Sender aktivieren:", self.enable_autoAdjust)) if self.enable_autoAdjust.value: self.list.append( getConfigListEntry( " Aufnahmezeiten automatisch an EPG Daten anpassen:", self.autoAdjust)) def UpdateMenuValues(self): if self['config'].instance.getCurrentIndex() == 0: if self.enable_margin_before.value and not self.margin_before.value: self.margin_before.value = config.plugins.serienRec.margin_before.value elif self['config'].instance.getCurrentIndex( ) == self.margin_after_index: if self.enable_margin_after.value and not self.margin_after.value: self.margin_after.value = config.plugins.serienRec.margin_after.value self.changedEntry() def changedEntry(self): self.createConfigList() self['config'].setList(self.list) def keyLeft(self): ConfigListScreen.keyLeft(self) self.UpdateMenuValues() def keyRight(self): ConfigListScreen.keyRight(self) self.UpdateMenuValues() def keyDown(self): # self.changedEntry() if self['config'].instance.getCurrentIndex() >= (len(self.list) - 1): self['config'].instance.moveSelectionTo(0) else: self['config'].instance.moveSelection( self['config'].instance.moveDown) # self.setInfoText() try: text = self.HilfeTexte[self['config'].getCurrent()[1]] except: text = "Keine Information verfügbar." self["config_information_text"].setText(text) def keyUp(self): # self.changedEntry() if self['config'].instance.getCurrentIndex() < 1: self['config'].instance.moveSelectionTo(len(self.list) - 1) else: self['config'].instance.moveSelection( self['config'].instance.moveUp) # self.setInfoText() try: text = self.HilfeTexte[self['config'].getCurrent()[1]] except: text = "Keine Information verfügbar." self["config_information_text"].setText(text) def ok(self): ConfigListScreen.keyOK(self) def setInfoText(self): self.HilfeTexte = { self.enable_margin_before: ("Bei 'ja' kann die Vorlaufzeit für Aufnahmen von '%s' eingestellt werden.\n" "Diese Einstellung hat Vorrang gegenüber der globalen Einstellung für die Vorlaufzeit.\n" "Ist auch bei der aufzunehmenden Serie eine Vorlaufzeit eingestellt, so hat der HÖHERE Wert Vorrang.\n" "Bei 'nein' gilt die Einstellung im globalen Setup.") % self.webSender, self.margin_before: ("Die Vorlaufzeit für Aufnahmen von '%s' in Minuten.\n" "Diese Einstellung hat Vorrang gegenüber der globalen Einstellung für die Vorlaufzeit.\n" "Ist auch bei der aufzunehmenden Serie eine Vorlaufzeit eingestellt, so hat der HÖHERE Wert Vorrang." ) % self.webSender, self.enable_margin_after: ("Bei 'ja' kann die Nachlaufzeit für Aufnahmen von '%s' eingestellt werden.\n" "Diese Einstellung hat Vorrang gegenüber der globalen Einstellung für die Nachlaufzeit.\n" "Ist auch bei der aufzunehmenden Serie eine Nachlaufzeit eingestellt, so hat der HÖHERE Wert Vorrang.\n" "Bei 'nein' gilt die Einstellung im globalen Setup.") % self.webSender, self.margin_after: ("Die Nachlaufzeit für Aufnahmen von '%s' in Minuten.\n" "Diese Einstellung hat Vorrang gegenüber der globalen Einstellung für die Nachlaufzeit.\n" "Ist auch bei der aufzunehmenden Serie eine Nachlaufzeit eingestellt, so hat der HÖHERE Wert Vorrang." ) % self.webSender, self.enable_vps: ("Bei 'ja' wird VPS für '%s' aktiviert. Die Aufnahme startet erst, wenn der Sender den Beginn der Ausstrahlung angibt, " "und endet, wenn der Sender das Ende der Ausstrahlung angibt.") % self.webSender, self.enable_vps_savemode: ("Bei 'ja' wird der Sicherheitsmodus bei '%s' verwendet.Die programmierten Start- und Endzeiten werden eingehalten.\n" "Die Aufnahme wird nur ggf. früher starten bzw. länger dauern, aber niemals kürzer." ) % self.webSender, self.enable_autoAdjust: ("Bei 'ja' kann für Timer auf '%s' eingestellt werden, ob die Aufnahmezeit automatisch an die EPG Daten angepasst werden soll.\n" "Diese Einstellung hat Vorrang gegenüber der VTI Einstellung für die automatische Anpassung der Aufnahmezeit an EPG Daten.\n" "Bei 'nein' gilt die Einstellung im VTI.") % self.webSender, self.autoAdjust: ("Bei 'ja' wird 'Aufnahmezeit automatisch an EPG Daten anpassen' für Timer auf '%s' aktiviert.\n" "Diese Einstellung hat Vorrang gegenüber der Einstellung für die automatische Anpassung der Aufnahmezeit an EPG Daten im VTI.\n" "Bei 'nein' gilt die Einstellung im VTI.") % self.webSender, } try: text = self.HilfeTexte[self['config'].getCurrent()[1]] except: text = "Keine Information verfügbar." self["config_information_text"].setText(text) def save(self): if not self.enable_margin_before.value: Vorlaufzeit = None else: Vorlaufzeit = self.margin_before.value if not self.enable_margin_after.value: Nachlaufzeit = None else: Nachlaufzeit = self.margin_after.value vpsSettings = (int(self.enable_vps_savemode.value) << 1) + int( self.enable_vps.value) if not self.enable_autoAdjust.value: autoAdjust = None else: autoAdjust = self.autoAdjust.value self.database.setChannelSettings(self.webSender, Vorlaufzeit, Nachlaufzeit, vpsSettings, autoAdjust) self.close() def cancel(self): self.close()
def __init__(self, session, webSender): serienRecBaseScreen.__init__(self, session) Screen.__init__(self, session) HelpableScreen.__init__(self) self.session = session self.webSender = webSender from SerienRecorder import serienRecDataBaseFilePath from SerienRecorderDatabase import SRDatabase self.database = SRDatabase(serienRecDataBaseFilePath) self["actions"] = HelpableActionMap( self, "SerienRecorderActions", { "red": (self.cancel, "Änderungen verwerfen und zurück zur Sender-Ansicht"), "green": (self.save, "Einstellungen speichern und zurück zur Sender-Ansicht"), "cancel": (self.cancel, "Änderungen verwerfen und zurück zur Sender-Ansicht"), "ok": (self.ok, "---"), "up": (self.keyUp, "eine Zeile nach oben"), "down": (self.keyDown, "eine Zeile nach unten"), "startTeletext": (self.showAbout, "Über dieses Plugin"), }, -1) self.helpList[0][2].sort() self["helpActions"] = ActionMap( [ "SerienRecorderActions", ], { "ok": self.ok, "displayHelp": self.showHelp, "displayHelp_long": self.showManual, }, 0) self.setupSkin() if config.plugins.serienRec.showAllButtons.value: setMenuTexts(self) (Vorlaufzeit, Nachlaufzeit, vps, autoAdjust) = self.database.getChannelsSettings(self.webSender) if str(Vorlaufzeit).isdigit(): self.margin_before = ConfigInteger(Vorlaufzeit, (0, 99)) self.enable_margin_before = ConfigYesNo(default=True) else: self.margin_before = ConfigInteger( config.plugins.serienRec.margin_before.value, (0, 99)) self.enable_margin_before = ConfigYesNo(default=False) if str(Nachlaufzeit).isdigit(): self.margin_after = ConfigInteger(Nachlaufzeit, (0, 99)) self.enable_margin_after = ConfigYesNo(default=True) else: self.margin_after = ConfigInteger( config.plugins.serienRec.margin_after.value, (0, 99)) self.enable_margin_after = ConfigYesNo(default=False) if str(vps).isdigit(): self.enable_vps = ConfigYesNo(default=bool(vps & 0x1)) self.enable_vps_savemode = ConfigYesNo(default=bool(vps & 0x2)) else: self.enable_vps = ConfigYesNo(default=False) self.enable_vps_savemode = ConfigYesNo(default=False) if str(autoAdjust).isdigit(): self.autoAdjust = ConfigYesNo(default=bool(autoAdjust)) self.enable_autoAdjust = ConfigYesNo(default=True) else: self.autoAdjust = ConfigYesNo(default=False) self.enable_autoAdjust = ConfigYesNo(default=False) self.changedEntry() ConfigListScreen.__init__(self, self.list) self.setInfoText() self['config_information_text'].setText( self.HilfeTexte[self.enable_margin_before]) self.onLayoutFinish.append(self.setSkinProperties)
class serienRecShowSeasonBegins(serienRecBaseScreen, Screen, HelpableScreen): def __init__(self, session): serienRecBaseScreen.__init__(self, session) Screen.__init__(self, session) HelpableScreen.__init__(self) self.modus = "menu_list" self.session = session self.picload = ePicLoad() self.ErrorMsg = "unbekannt" self.piconLoader = PiconLoader() self.picloader = None self.filter = False self.database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) self.changesMade = False self["actions"] = HelpableActionMap(self, "SerienRecorderActions", { "ok": (self.keyOK, "Marker für die ausgewählte Serie hinzufügen"), "cancel": (self.keyCancel, "zurück zur vorherigen Ansicht"), "left": (self.keyLeft, "zur vorherigen Seite blättern"), "right": (self.keyRight, "zur nächsten Seite blättern"), "up": (self.keyUp, "eine Zeile nach oben"), "down": (self.keyDown, "eine Zeile nach unten"), "menu": (self.recSetup, "Menü für globale Einstellungen öffnen"), "yellow": (self.keyYellow, "Zeige nur Serien-Starts"), "startTeletext": (self.wunschliste, "Informationen zur ausgewählten Serie auf Wunschliste anzeigen"), "0" : (self.readLogFile, "Log-File des letzten Suchlaufs anzeigen"), "4" : (self.serieInfo, "Informationen zur ausgewählten Serie anzeigen"), "6" : (self.showConflicts, "Liste der Timer-Konflikte anzeigen"), "7" : (self.showWishlist, "Merkzettel (vorgemerkte Folgen) anzeigen"), }, -1) self.helpList[0][2].sort() self["helpActions"] = ActionMap(["SerienRecorderActions" ,], { "displayHelp" : self.showHelp, "displayHelp_long" : self.showManual, }, 0) self.setupSkin() self.timer_default = eTimer() if isDreamOS(): self.timer_default_conn = self.timer_default.timeout.connect(self.readProposal) else: self.timer_default.callback.append(self.readProposal) self.proposalList = [] self.transmissions = {} self.serviceRefs = self.database.getActiveServiceRefs() self.onLayoutFinish.append(self.setSkinProperties) self.onLayoutFinish.append(self.__onLayoutFinish) self.onClose.append(self.__onClose) def callHelpAction(self, *args): HelpableScreen.callHelpAction(self, *args) def setSkinProperties(self): super(self.__class__, self).setSkinProperties() self['text_ok'].setText("Marker hinzufügen") self['text_yellow'].setText("Zeige Serienstarts") self.num_bt_text[3][0] = buttonText_na super(self.__class__, self).startDisplayTimer() def setupSkin(self): super(self.__class__, self).setupSkin() self[self.modus].show() if config.plugins.serienRec.showCover.value: self['cover'].show() if not config.plugins.serienRec.showAllButtons.value: self['bt_ok'].show() self['bt_yellow'].show() self['bt_exit'].show() self['bt_text'].show() self['bt_info'].show() self['bt_menu'].show() self['text_ok'].show() self['text_yellow'].show() self['text_0'].show() self['text_1'].show() self['text_2'].show() self['text_3'].show() self['text_4'].show() self['text_6'].show() self['text_7'].show() self['text_8'].show() self['text_9'].show() def updateMenuKeys(self): updateMenuKeys(self) def __onLayoutFinish(self): self['title'].setText("Lade neue Serien/Staffeln...") self.timer_default.start(0) def readProposal(self): self.timer_default.stop() webChannels = self.database.getActiveChannels() self.proposalList = [] transmissionResults = downloadSeasonBegins(webChannels) transmissionResults.start() transmissionResults.join() if not transmissionResults.getData(): print "[SerienRecorder]: Abfrage beim SerienServer doGetSeasonBegins() fehlgeschlagen" else: self.transmissions = transmissionResults.getData() self.buildProposalList() def buildProposalList(self): markers = self.database.getAllMarkerStatusForBoxID(config.plugins.serienRec.BoxID.value) self.proposalList = [] if self.filter: self['text_yellow'].setText("Serien-/Staffelstarts") else: self['text_yellow'].setText("Zeige Serienstarts") for event in self.transmissions['events']: if self.filter and str(event['season']).isdigit() and int(event['season']) > 1: continue seriesName = event['name'].encode('utf-8') seriesID = int(event['id']) # marker flags: 0 = no marker, 1 = active marker, 2 = inactive marker markerFlag = 0 if seriesID in markers: markerFlag = 1 if markers[seriesID] else 2 self.proposalList.append([seriesName, event['season'], event['channel'].encode('utf-8'), event['start'], event['id'], markerFlag]) if self.filter: self['title'].setText("%d neue Serien gefunden:" % len(self.proposalList)) else: self['title'].setText("%d neue Serien/Staffeln gefunden:" % len(self.proposalList)) self.chooseMenuList.setList(map(self.buildList, self.proposalList)) if self['menu_list'].getCurrent(): serien_name = self[self.modus].getCurrent()[0][0] serien_id = self[self.modus].getCurrent()[0][4] SerienRecorder.getCover(self, serien_name, serien_id) def buildList(self, entry): (Serie, Staffel, Sender, UTCTime, ID, MarkerFlag) = entry icon = imageNone = "%simages/black.png" % SerienRecorder.serienRecMainPath imageNeu = "%simages/neu.png" % SerienRecorder.serienRecMainPath if MarkerFlag == 1: setFarbe = parseColor('green').argb() elif MarkerFlag == 2: setFarbe = parseColor('red').argb() else: setFarbe = parseColor('foreground').argb() if str(Staffel).isdigit() and int(Staffel) == 1: icon = imageNeu foregroundColor = parseColor('foreground').argb() Staffel = "Staffel %s" % str(Staffel) WochenTag = ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"] xtime = time.strftime(WochenTag[time.localtime(int(UTCTime)).tm_wday]+ ", %d.%m.%Y", time.localtime(int(UTCTime))) if config.plugins.serienRec.showPicons.value != "0": picon = loadPNG(imageNone) if Sender and self.serviceRefs.get(Sender): # Get picon by reference or by name piconPath = self.piconLoader.getPicon(self.serviceRefs.get(Sender)[0] if config.plugins.serienRec.showPicons.value == "1" else self.serviceRefs.get(Sender)[1]) if piconPath: self.picloader = PicLoader(80 * skinFactor, 40 * skinFactor) picon = self.picloader.load(piconPath) self.picloader.destroy() return [entry, (eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 10, 5, 80 * skinFactor, 40 * skinFactor, picon), (eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 340 * skinFactor, 15 * skinFactor, 30 * skinFactor, 30 * skinFactor, loadPNG(icon)), (eListboxPythonMultiContent.TYPE_TEXT, 110 * skinFactor, 3, 200 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, Sender, foregroundColor, foregroundColor), (eListboxPythonMultiContent.TYPE_TEXT, 110 * skinFactor, 29 * skinFactor, 200 * skinFactor, 18 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, xtime), (eListboxPythonMultiContent.TYPE_TEXT, 375 * skinFactor, 3, 500 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, Serie, setFarbe, setFarbe), (eListboxPythonMultiContent.TYPE_TEXT, 375 * skinFactor, 29 * skinFactor, 500 * skinFactor, 18 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, Staffel) ] else: return [entry, (eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 15, 15 * skinFactor, 30 * skinFactor, 30 * skinFactor, loadPNG(icon)), (eListboxPythonMultiContent.TYPE_TEXT, 50 * skinFactor, 3, 200 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, Sender, foregroundColor, foregroundColor), (eListboxPythonMultiContent.TYPE_TEXT, 50 * skinFactor, 29 * skinFactor, 200 * skinFactor, 18 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, xtime), (eListboxPythonMultiContent.TYPE_TEXT, 300 * skinFactor, 3, 500 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, Serie, setFarbe, setFarbe), (eListboxPythonMultiContent.TYPE_TEXT, 300 * skinFactor, 29 * skinFactor, 500 * skinFactor, 18 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, Staffel) ] def serieInfo(self): check = self[self.modus].getCurrent() if check is None: return serien_id = self[self.modus].getCurrent()[0][4] if serien_id > 0: serien_name = self[self.modus].getCurrent()[0][0] from SerienRecorderSeriesInfoScreen import serienRecShowInfo self.session.open(serienRecShowInfo, serien_name, serien_id) def wunschliste(self): serien_id = self[self.modus].getCurrent()[0][4] super(self.__class__, self).wunschliste(serien_id) def setupClose(self, result): super(self.__class__, self).setupClose(result) def keyOK(self): check = self[self.modus].getCurrent() if check is None: print "[SerienRecorder] Proposal-DB leer." return else: (Serie, Staffel, Sender, UTCTime, ID, MarkerFlag) = self[self.modus].getCurrent()[0] (existingID, AbStaffel, AlleSender) = self.database.getMarkerSeasonAndChannelSettings(Serie) if existingID > 0: # Add season and channel of selected series to marker self.database.updateMarkerSeasonAndChannelSettings(existingID, AbStaffel, Staffel, AlleSender, Sender) # Activate marker self.database.setMarkerStatus(Serie, config.plugins.serienRec.BoxID.value, True) else: if config.plugins.serienRec.activateNewOnThisSTBOnly.value: boxID = config.plugins.serienRec.BoxID.value else: boxID = None self.database.addMarker(str(ID), Serie, "", boxID, 0) if config.plugins.serienRec.openMarkerScreen.value: from SerienRecorderMarkerScreen import serienRecMarker self.session.open(serienRecMarker, Serie) self.changesMade = True self.buildProposalList() self.chooseMenuList.setList(map(self.buildList, self.proposalList)) def keyYellow(self): if self.filter: self.filter = False else: self.filter = True self.buildProposalList() def keyLeft(self): self[self.modus].pageUp() serien_name = self[self.modus].getCurrent()[0][0] serien_id = self[self.modus].getCurrent()[0][4] SerienRecorder.getCover(self, serien_name, serien_id) def keyRight(self): self[self.modus].pageDown() serien_name = self[self.modus].getCurrent()[0][0] serien_id = self[self.modus].getCurrent()[0][4] SerienRecorder.getCover(self, serien_name, serien_id) def keyDown(self): self[self.modus].down() serien_name = self[self.modus].getCurrent()[0][0] serien_id = self[self.modus].getCurrent()[0][4] SerienRecorder.getCover(self, serien_name, serien_id) def keyUp(self): self[self.modus].up() serien_name = self[self.modus].getCurrent()[0][0] serien_id = self[self.modus].getCurrent()[0][4] SerienRecorder.getCover(self, serien_name, serien_id) def __onClose(self): self.stopDisplayTimer()
def __init__(self, session): serienRecBaseScreen.__init__(self, session) Screen.__init__(self, session) HelpableScreen.__init__(self) self.skin = None self.session = session self.picload = ePicLoad() self.WochenTag = ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"] self.database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) self["actions"] = HelpableActionMap( self, "SerienRecorderActions", { "ok": (self.keyOK, "Liste der erstellten Timer bearbeiten"), "cancel": (self.keyCancel, "zurück zur Serienplaner-Ansicht"), "left": (self.keyLeft, "zur vorherigen Seite blättern"), "right": (self.keyRight, "zur nächsten Seite blättern"), "up": (self.keyUp, "eine Zeile nach oben"), "down": (self.keyDown, "eine Zeile nach unten"), "red": (self.keyRed, "ausgewählten Timer löschen"), "green": (self.viewChange, "Sortierung ändern"), "yellow": (self.keyYellow, "umschalten alle/nur aktive Timer anzeigen"), "blue": (self.keyBlue, "alle noch ausstehenden Timer löschen"), "menu": (self.recSetup, "Menü für globale Einstellungen öffnen"), "startTeletext": (self.wunschliste, "Informationen zur ausgewählten Serie auf Wunschliste anzeigen" ), "0": (self.readLogFile, "Log-File des letzten Suchlaufs anzeigen"), "3": (self.showProposalDB, "Liste der Serien/Staffel-Starts anzeigen"), "4": (self.serieInfo, "Informationen zur ausgewählten Serie anzeigen"), "6": (self.showConflicts, "Liste der Timer-Konflikte anzeigen"), "7": (self.showWishlist, "Merkzettel (vorgemerkte Folgen) anzeigen"), "8": (self.cleanUp, "Timerliste bereinigen"), "9": (self.dropAllTimer, "Alle Timer aus der Datenbank löschen"), }, -1) self.helpList[0][2].sort() self["helpActions"] = ActionMap( [ "SerienRecorderActions", ], { # "ok" : self.keyOK, "displayHelp": self.showHelp, "displayHelp_long": self.showManual, }, 0) self.setupSkin() self.changesMade = False self.filter = True self.onLayoutFinish.append(self.readTimer) self.onClose.append(self.__onClose) self.onLayoutFinish.append(self.setSkinProperties)
def __init__(self, session): serienRecBaseScreen.__init__(self, session) Screen.__init__(self, session) HelpableScreen.__init__(self) self.session = session self.picload = ePicLoad() self.database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) self.chooseMenuList_popup = MenuList( [], enableWrapAround=True, content=eListboxPythonMultiContent) self["actions"] = HelpableActionMap( self, "SerienRecorderActions", { "ok": (self.keyOK, "für die ausgewählte Serien neue Einträge hinzufügen"), "cancel": (self.keyCancel, "zurück zur vorherigen Ansicht"), "left": (self.keyLeft, "zur vorherigen Seite blättern"), "right": (self.keyRight, "zur nächsten Seite blättern"), "up": (self.keyUp, "eine Zeile nach oben"), "down": (self.keyDown, "eine Zeile nach unten"), "red": (self.keyRed, "ausgewählten Eintrag löschen"), "green": (self.keyGreen, "alle Änderungen speichern und zurück zur vorherigen Ansicht" ), "yellow": (self.keyYellow, "umschalten Sortierung ein/aus"), "blue": (self.keyBlue, "alle Einträge aus der Liste endgültig löschen"), "menu": (self.recSetup, "Menü für globale Einstellungen öffnen"), "0": (self.readLogFile, "Log-File des letzten Suchlaufs anzeigen"), "3": (self.showProposalDB, "Liste der Serien/Staffel-Starts anzeigen"), "4": (self.serieInfo, "Informationen zur ausgewählten Serie anzeigen"), "6": (self.showConflicts, "Liste der Timer-Konflikte anzeigen"), }, -1) self.helpList[0][2].sort() self["helpActions"] = ActionMap([ "SerienRecorderActions", ], { "displayHelp": self.showHelp, "displayHelp_long": self.showManual, }, 0) self.setupSkin() self.delAdded = False self.wishlist = [] self.wishlist_tmp = [] self.dbData = [] self.modus = "menu_list" self.aSerie = "" self.aStaffel = 0 self.aFromEpisode = 0 self.aToEpisode = 0 self.onLayoutFinish.append(self.readWishlist) self.onClose.append(self.__onClose) self.onLayoutFinish.append(self.setSkinProperties)
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()
class serienRecTimerListScreen(serienRecBaseScreen, Screen, HelpableScreen): def __init__(self, session): serienRecBaseScreen.__init__(self, session) Screen.__init__(self, session) HelpableScreen.__init__(self) self.skin = None self.session = session self.picload = ePicLoad() self.WochenTag = ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"] self.database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) self["actions"] = HelpableActionMap(self, "SerienRecorderActions", { "ok": (self.keyOK, "Liste der erstellten Timer bearbeiten"), "cancel": (self.keyCancel, "zurück zur Serienplaner-Ansicht"), "left": (self.keyLeft, "zur vorherigen Seite blättern"), "right": (self.keyRight, "zur nächsten Seite blättern"), "up": (self.keyUp, "eine Zeile nach oben"), "down": (self.keyDown, "eine Zeile nach unten"), "red": (self.keyRed, "ausgewählten Timer löschen"), "green": (self.viewChange, "Sortierung ändern"), "yellow": (self.keyYellow, "umschalten alle/nur aktive Timer anzeigen"), "blue": (self.keyBlue, "alle noch ausstehenden Timer löschen"), "menu": (self.recSetup, "Menü für globale Einstellungen öffnen"), "startTeletext": (self.wunschliste, "Informationen zur ausgewählten Serie auf Wunschliste anzeigen"), "0" : (self.readLogFile, "Log-File des letzten Suchlaufs anzeigen"), "3" : (self.showProposalDB, "Liste der Serien/Staffel-Starts anzeigen"), "4" : (self.serieInfo, "Informationen zur ausgewählten Serie anzeigen"), "6" : (self.showConflicts, "Liste der Timer-Konflikte anzeigen"), "7" : (self.showWishlist, "Merkzettel (vorgemerkte Folgen) anzeigen"), "9" : (self.dropAllTimer, "Alle Timer aus der Datenbank löschen"), }, -1) self.helpList[0][2].sort() self["helpActions"] = ActionMap(["SerienRecorderActions" ,], { # "ok" : self.keyOK, "displayHelp" : self.showHelp, "displayHelp_long" : self.showManual, }, 0) self.setupSkin() self.changesMade = False self.filter = True self.onLayoutFinish.append(self.readTimer) self.onClose.append(self.__onClose) self.onLayoutFinish.append(self.setSkinProperties) def callHelpAction(self, *args): HelpableScreen.callHelpAction(self, *args) def setSkinProperties(self): super(self.__class__, self).setSkinProperties() self['text_red'].setText("Entferne Timer") if config.plugins.serienRec.recordListView.value == 0: self['text_green'].setText("Zeige neueste Timer zuerst") elif config.plugins.serienRec.recordListView.value == 1: self['text_green'].setText("Zeige früheste Timer zuerst") self['text_ok'].setText("Liste bearbeiten") self['text_yellow'].setText("Zeige auch alte Timer") self['text_blue'].setText("Entferne neue Timer") self.num_bt_text[4][1] = "Datenbank leeren" super(self.__class__, self).startDisplayTimer() def setupSkin(self): InitSkin(self) self.chooseMenuList = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self.chooseMenuList.l.setFont(0, gFont('Regular', 20 + int(config.plugins.serienRec.listFontsize.value))) self.chooseMenuList.l.setItemHeight(int(50 *skinFactor)) self['menu_list'] = self.chooseMenuList self['menu_list'].show() if config.plugins.serienRec.showCover.value: self['cover'].show() if not config.plugins.serienRec.showAllButtons.value: self['bt_red'].show() self['bt_green'].show() self['bt_ok'].show() self['bt_yellow'].show() self['bt_blue'].show() self['bt_exit'].show() self['bt_text'].show() self['bt_info'].show() self['bt_menu'].show() self['text_red'].show() self['text_green'].show() self['text_ok'].show() self['text_yellow'].show() self['text_blue'].show() self['text_0'].show() self['text_1'].show() self['text_2'].show() self['text_3'].show() self['text_4'].show() def updateMenuKeys(self): updateMenuKeys(self) def serieInfo(self): check = self['menu_list'].getCurrent() if check is None: return serien_name = self['menu_list'].getCurrent()[0][0] url = self.database.getMarkerURL(serien_name) if url: serien_id = url if serien_id: from SerienRecorderSeriesInfoScreen import serienRecShowInfo self.session.open(serienRecShowInfo, serien_name, serien_id) def wunschliste(self): serien_name = self['menu_list'].getCurrent()[0][0] url = self.database.getMarkerURL(serien_name) serien_id = url super(self.__class__, self).wunschliste(serien_id) def setupClose(self, result): super(self.__class__, self).setupClose(result) if result[1]: self.readTimer() def viewChange(self): if config.plugins.serienRec.recordListView.value == 1: config.plugins.serienRec.recordListView.value = 0 self['text_green'].setText("Zeige neueste Timer zuerst") else: config.plugins.serienRec.recordListView.value = 1 self['text_green'].setText("Zeige früheste Timer zuerst") config.plugins.serienRec.recordListView.save() SerienRecorder.configfile.save() self.readTimer() def readTimer(self, showTitle=True): current_time = int(time.time()) deltimer = 0 timerList = [] timers = self.database.getAllTimer(current_time if self.filter else None) for timer in timers: (serie, staffel, episode, title, start_time, stbRef, webChannel, eit, activeTimer) = timer if int(start_time) < int(current_time): deltimer += 1 timerList.append((serie, staffel, episode, title, start_time, webChannel, "1", 0, bool(activeTimer))) else: timerList.append((serie, staffel, episode, title, start_time, webChannel, "0", eit, bool(activeTimer))) if showTitle: self['title'].instance.setForegroundColor(parseColor("foreground")) if self.filter: self['title'].setText("Timer-Liste: %s ausstehende Timer" % len(timerList)) else: self['title'].setText("Timer-Liste: %s abgeschlossene und %s ausstehende Timer" % (deltimer, len(timerList ) -deltimer)) if config.plugins.serienRec.recordListView.value == 0: timerList.sort(key=lambda t : t[4]) elif config.plugins.serienRec.recordListView.value == 1: timerList.sort(key=lambda t : t[4]) timerList.reverse() self.chooseMenuList.setList(map(self.buildList, timerList)) if len(timerList) == 0: if showTitle: self['title'].instance.setForegroundColor(parseColor("foreground")) self['title'].setText("Serien Timer - 0 Serien in der Aufnahmeliste.") self.getCover() def buildList(self, entry): (serie, staffel, episode, title, start_time, webChannel, foundIcon, eit, activeTimer) = entry xtime = time.strftime(self.WochenTag[time.localtime(int(start_time)).tm_wday ] +", %d.%m.%Y - %H:%M", time.localtime(int(start_time))) xtitle = "S%sE%s - %s" % (str(staffel).zfill(2), str(episode).zfill(2), title) if int(foundIcon) == 1: imageFound = "%simages/found.png" % SerienRecorder.serienRecMainPath else: imageFound = "%simages/black.png" % SerienRecorder.serienRecMainPath if activeTimer: SerieColor = None else: SerieColor = parseColor('red').argb() foregroundColor = parseColor('foreground').argb() return [entry, (eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 5, 8 * skinFactor, 32 * skinFactor, 32 * skinFactor, loadPNG(imageFound)), (eListboxPythonMultiContent.TYPE_TEXT, 40, 3, 200 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, webChannel, SerieColor), (eListboxPythonMultiContent.TYPE_TEXT, 40, 29 * skinFactor, 250 * skinFactor, 18 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, xtime, foregroundColor, foregroundColor), (eListboxPythonMultiContent.TYPE_TEXT, 300 * skinFactor, 3, 500 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, serie, SerieColor), (eListboxPythonMultiContent.TYPE_TEXT, 300 * skinFactor, 29 * skinFactor, 500 * skinFactor, 18 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, re.sub("(?<= - )dump\Z", "(Manuell hinzugefügt !!)", xtitle), foregroundColor, foregroundColor) ] def keyOK(self): self.session.open(serienRecModifyAdded, False) def callDeleteSelectedTimer(self, answer): if answer: serien_name = self['menu_list'].getCurrent()[0][0] staffel = self['menu_list'].getCurrent()[0][1] episode = self['menu_list'].getCurrent()[0][2] serien_title = self['menu_list'].getCurrent()[0][3] serien_time = self['menu_list'].getCurrent()[0][4] serien_channel = self['menu_list'].getCurrent()[0][5] serien_eit = self['menu_list'].getCurrent()[0][7] self.removeTimer(serien_name, staffel, episode, serien_title, serien_time, serien_channel, serien_eit) else: return def removeTimer(self, serien_name, staffel, episode, serien_title, serien_time, serien_channel, serien_eit=0): if config.plugins.serienRec.TimerName.value == "1": # "<Serienname>" title = serien_name elif config.plugins.serienRec.TimerName.value == "2": # "SnnEmm - <Episodentitel>" title = "S%sE%s - %s" % (str(staffel).zfill(2), str(episode).zfill(2), serien_title) else: # "<Serienname> - SnnEmm - <Episodentitel>" title = "%s - S%sE%s - %s" % (serien_name, str(staffel).zfill(2), str(episode).zfill(2), serien_title) from SerienRecorderTimer import serienRecBoxTimer removed = serienRecBoxTimer.removeTimerEntry(title, serien_time, serien_eit) if not removed: print "[SerienRecorder] enigma2 NOOOTTT removed" else: print "[SerienRecorder] enigma2 Timer removed." self.database.removeTimer(serien_name, staffel, episode, None, serien_time, serien_channel, (serien_eit if serien_eit > 0 else None)) self.changesMade = True self.readTimer(False) self['title'].instance.setForegroundColor(parseColor("red")) self['title'].setText("Timer '- %s -' entfernt." % serien_name) def keyRed(self): check = self['menu_list'].getCurrent() if check is None: print "[SerienRecorder] Serien Timer leer." return else: serien_name = self['menu_list'].getCurrent()[0][0] staffel = self['menu_list'].getCurrent()[0][1] episode = self['menu_list'].getCurrent()[0][2] serien_title = self['menu_list'].getCurrent()[0][3] serien_time = self['menu_list'].getCurrent()[0][4] serien_channel = self['menu_list'].getCurrent()[0][5] serien_eit = self['menu_list'].getCurrent()[0][7] print self['menu_list'].getCurrent()[0] if config.plugins.serienRec.confirmOnDelete.value: self.session.openWithCallback(self.callDeleteSelectedTimer, MessageBox, "Soll '%s - S%sE%s - %s' wirklich entfernt werden?" % (serien_name, str(staffel).zfill(2), str(episode).zfill(2), re.sub("\Adump\Z", "(Manuell hinzugefügt !!)", serien_title)), MessageBox.TYPE_YESNO, default=False) else: self.removeTimer(serien_name, staffel, episode, serien_title, serien_time, serien_channel, serien_eit) def keyYellow(self): if self.filter: self['text_yellow'].setText("Zeige nur neue Timer") self.filter = False else: self['text_yellow'].setText("Zeige auch alte Timer") self.filter = True self.readTimer() def keyBlue(self): if config.plugins.serienRec.confirmOnDelete.value: self.session.openWithCallback(self.removeNewTimerFromDB, MessageBox, "Sollen wirklich alle noch ausstehenden Timer von der Box und aus der Datenbank entfernt werden?", MessageBox.TYPE_YESNO, default=False) else: self.removeNewTimerFromDB(True) def removeNewTimerFromDB(self, answer): if answer: current_time = int(time.time()) timers = self.database.getAllTimer(current_time) for timer in timers: (serie, staffel, episode, title, start_time, stbRef, webChannel, eit, activeTimer) = timer self.removeTimer(serie, staffel, episode, title, start_time, webChannel, eit) self.readTimer(False) self['title'].instance.setForegroundColor(parseColor("red")) self['title'].setText("Alle noch ausstehenden Timer wurden entfernt.") else: return def removeOldTimerFromDB(self, answer): if answer: self.database.removeAllOldTimer() self.database.rebuild() self.readTimer(False) self['title'].instance.setForegroundColor(parseColor("red")) self['title'].setText("Alle alten Timer wurden entfernt.") else: return def dropAllTimer(self): if config.plugins.serienRec.confirmOnDelete.value: self.session.openWithCallback(self.removeOldTimerFromDB, MessageBox, "Sollen wirklich alle alten Timer aus der Datenbank entfernt werden?", MessageBox.TYPE_YESNO, default=False) else: self.removeOldTimerFromDB(True) def getCover(self): check = self['menu_list'].getCurrent() if check is None: return serien_name = self['menu_list'].getCurrent()[0][0] serien_id = None url = self.database.getMarkerURL(serien_name) if url: serien_id = url SerienRecorder.getCover(self, serien_name, serien_id) def keyLeft(self): self['menu_list'].pageUp() self.getCover() def keyRight(self): self['menu_list'].pageDown() self.getCover() def keyDown(self): self['menu_list'].down() self.getCover() def keyUp(self): self['menu_list'].up() self.getCover() def __onClose(self): self.stopDisplayTimer() def keyCancel(self): if config.plugins.serienRec.refreshViews.value: self.close(self.changesMade) else: self.close(False)
def __init__(self, session, serien_name, serie_url, serien_cover): serienRecBaseScreen.__init__(self, session) Screen.__init__(self, session) HelpableScreen.__init__(self) self.ErrorMsg = '' self.database = SRDatabase(serienRecDataBaseFilePath) self.modus = "menu_list" self.session = session self.picload = ePicLoad() self.serien_name = serien_name self.serien_id = 0 self.serien_cover = serien_cover self.addedEpisodes = self.database.getTimerForSeries(self.serien_name) self.episodes_list_cache = {} self.aStaffel = None self.aFromEpisode = None self.aToEpisode = None #self.pages = [] self.page = 1 self.maxPages = 1 self.loading = False self.changesMade = False self["actions"] = HelpableActionMap(self, "SerienRecorderActions", { "ok" : (self.keyOK, "Informationen zur ausgewählten Episode anzeigen"), "cancel": (self.keyCancel, "Zurück zur Serien-Marker-Ansicht"), "left" : (self.keyLeft, "Zur vorherigen Seite blättern"), "right" : (self.keyRight, "Zur nächsten Seite blättern"), "up" : (self.keyUp, "Eine Zeile nach oben"), "down" : (self.keyDown, "Eine Zeile nach unten"), "red" : (self.keyRed, "Zurück zur Serien-Marker-Ansicht"), "green" : (self.keyGreen, "Diese Folge (nicht mehr) aufnehmen"), "yellow": (self.keyYellow, "Ausgewählte Folge auf den Merkzettel"), "blue" : (self.keyBlue, "Neue Einträge manuell hinzufügen"), "menu" : (self.recSetup, "Menü für globale Einstellungen öffnen"), "nextBouquet" : (self.nextPage, "Nächste Seite laden"), "prevBouquet" : (self.backPage, "Vorherige Seite laden"), "startTeletext" : (self.wunschliste, "Informationen zur ausgewählten Serie auf Wunschliste anzeigen"), "0" : (self.readLogFile, "Log-File des letzten Suchlaufs anzeigen"), "3" : (self.showProposalDB, "Liste der Serien/Staffel-Starts anzeigen"), "4" : (self.serieInfo, "Informationen zur ausgewählten Serie anzeigen"), "6" : (self.showConflicts, "Liste der Timer-Konflikte anzeigen"), "7" : (self.showWishlist, "Merkzettel (vorgemerkte Folgen) anzeigen"), }, -1) self.helpList[0][2].sort() self["helpActions"] = ActionMap(["SerienRecorderActions", ], { "displayHelp" : self.showHelp, "displayHelp_long" : self.showManual, }, 0) self.setupSkin() self.serien_id = serie_url self.timer_default = eTimer() if isDreamOS(): self.timer_default_conn = self.timer_default.timeout.connect(self.loadEpisodes) else: self.timer_default.callback.append(self.loadEpisodes) self.onLayoutFinish.append(self.setSkinProperties) self.onLayoutFinish.append(self.searchEpisodes) self.onClose.append(self.__onClose)
def __init__(self, session): serienRecBaseScreen.__init__(self, session) Screen.__init__(self, session) HelpableScreen.__init__(self) self.modus = "menu_list" self.session = session self.picload = ePicLoad() self.ErrorMsg = "unbekannt" self.piconLoader = PiconLoader() self.picloader = None self.filter = False self.database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) self.changesMade = False self["actions"] = HelpableActionMap( self, "SerienRecorderActions", { "ok": (self.keyOK, "Marker für die ausgewählte Serie hinzufügen"), "cancel": (self.keyCancel, "zurück zur vorherigen Ansicht"), "left": (self.keyLeft, "zur vorherigen Seite blättern"), "right": (self.keyRight, "zur nächsten Seite blättern"), "up": (self.keyUp, "eine Zeile nach oben"), "down": (self.keyDown, "eine Zeile nach unten"), "menu": (self.recSetup, "Menü für globale Einstellungen öffnen"), "yellow": (self.keyYellow, "Zeige nur Serien-Starts"), "startTeletext": (self.wunschliste, "Informationen zur ausgewählten Serie auf Wunschliste anzeigen" ), "0": (self.readLogFile, "Log-File des letzten Suchlaufs anzeigen"), "2": (self.changeTVDBID, "TVDB-ID ändern"), "4": (self.serieInfo, "Informationen zur ausgewählten Serie anzeigen"), "6": (self.showConflicts, "Liste der Timer-Konflikte anzeigen"), "7": (self.showWishlist, "Merkzettel (vorgemerkte Folgen) anzeigen"), }, -1) self.helpList[0][2].sort() self["helpActions"] = ActionMap([ "SerienRecorderActions", ], { "displayHelp": self.showHelp, "displayHelp_long": self.showManual, }, 0) self.setupSkin() self.timer_default = eTimer() if isDreamOS(): self.timer_default_conn = self.timer_default.timeout.connect( self.readProposal) else: self.timer_default.callback.append(self.readProposal) self.proposalList = [] self.transmissions = {} self.serviceRefs = self.database.getActiveServiceRefs() self.onLayoutFinish.append(self.setSkinProperties) self.onLayoutFinish.append(self.__onLayoutFinish) self.onClose.append(self.__onClose)
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
class serienRecShowSeasonBegins(serienRecBaseScreen, Screen, HelpableScreen): def __init__(self, session): serienRecBaseScreen.__init__(self, session) Screen.__init__(self, session) HelpableScreen.__init__(self) self.modus = "menu_list" self.session = session self.picload = ePicLoad() self.ErrorMsg = "unbekannt" self.piconLoader = PiconLoader() self.picloader = None self.filter = False self.database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) self.changesMade = False self["actions"] = HelpableActionMap( self, "SerienRecorderActions", { "ok": (self.keyOK, "Marker für die ausgewählte Serie hinzufügen"), "cancel": (self.keyCancel, "zurück zur vorherigen Ansicht"), "left": (self.keyLeft, "zur vorherigen Seite blättern"), "right": (self.keyRight, "zur nächsten Seite blättern"), "up": (self.keyUp, "eine Zeile nach oben"), "down": (self.keyDown, "eine Zeile nach unten"), "menu": (self.recSetup, "Menü für globale Einstellungen öffnen"), "yellow": (self.keyYellow, "Zeige nur Serien-Starts"), "startTeletext": (self.wunschliste, "Informationen zur ausgewählten Serie auf Wunschliste anzeigen" ), "0": (self.readLogFile, "Log-File des letzten Suchlaufs anzeigen"), "2": (self.changeTVDBID, "TVDB-ID ändern"), "4": (self.serieInfo, "Informationen zur ausgewählten Serie anzeigen"), "6": (self.showConflicts, "Liste der Timer-Konflikte anzeigen"), "7": (self.showWishlist, "Merkzettel (vorgemerkte Folgen) anzeigen"), }, -1) self.helpList[0][2].sort() self["helpActions"] = ActionMap([ "SerienRecorderActions", ], { "displayHelp": self.showHelp, "displayHelp_long": self.showManual, }, 0) self.setupSkin() self.timer_default = eTimer() if isDreamOS(): self.timer_default_conn = self.timer_default.timeout.connect( self.readProposal) else: self.timer_default.callback.append(self.readProposal) self.proposalList = [] self.transmissions = {} self.serviceRefs = self.database.getActiveServiceRefs() self.onLayoutFinish.append(self.setSkinProperties) self.onLayoutFinish.append(self.__onLayoutFinish) self.onClose.append(self.__onClose) def callHelpAction(self, *args): HelpableScreen.callHelpAction(self, *args) def setSkinProperties(self): super(self.__class__, self).setSkinProperties() self['text_ok'].setText("Marker hinzufügen") self['text_yellow'].setText("Zeige Serienstarts") self.num_bt_text[2][0] = "TVDB-ID ändern" self.num_bt_text[3][0] = buttonText_na super(self.__class__, self).startDisplayTimer() def setupSkin(self): super(self.__class__, self).setupSkin() self[self.modus].show() if config.plugins.serienRec.showCover.value: self['cover'].show() if not config.plugins.serienRec.showAllButtons.value: self['bt_ok'].show() self['bt_yellow'].show() self['bt_exit'].show() self['bt_text'].show() self['bt_info'].show() self['bt_menu'].show() self['text_ok'].show() self['text_yellow'].show() self['text_0'].show() self['text_1'].show() self['text_2'].show() self['text_3'].show() self['text_4'].show() self['text_6'].show() self['text_7'].show() self['text_8'].show() self['text_9'].show() def updateMenuKeys(self): updateMenuKeys(self) def __onLayoutFinish(self): self['title'].setText("Lade neue Serien/Staffeln...") self.timer_default.start(0) def changeTVDBID(self): from SerienRecorderScreenHelpers import EditTVDBID serien_name = self[self.modus].getCurrent()[0][0] serien_id = self[self.modus].getCurrent()[0][4] editTVDBID = EditTVDBID(self, self.session, serien_name, serien_id) editTVDBID.changeTVDBID() def readProposal(self): self.timer_default.stop() webChannels = self.database.getActiveChannels() self.proposalList = [] transmissionResults = downloadSeasonBegins(webChannels) transmissionResults.start() transmissionResults.join() if not transmissionResults.getData(): print "[SerienRecorder]: Abfrage beim SerienServer doGetSeasonBegins() fehlgeschlagen" else: self.transmissions = transmissionResults.getData() self.buildProposalList() def buildProposalList(self): markers = self.database.getAllMarkerStatusForBoxID( config.plugins.serienRec.BoxID.value) self.proposalList = [] if self.filter: self['text_yellow'].setText("Serien-/Staffelstarts") else: self['text_yellow'].setText("Zeige Serienstarts") for event in self.transmissions['events']: if self.filter and str( event['season']).isdigit() and int(event['season']) > 1: continue seriesName = event['name'].encode('utf-8') seriesID = int(event['id']) # marker flags: 0 = no marker, 1 = active marker, 2 = inactive marker markerFlag = 0 if seriesID in markers: markerFlag = 1 if markers[seriesID] else 2 self.proposalList.append([ seriesName, event['season'], event['channel'].encode('utf-8'), event['start'], event['id'], markerFlag ]) if self.filter: self['title'].setText("%d neue Serien gefunden:" % len(self.proposalList)) else: self['title'].setText("%d neue Serien/Staffeln gefunden:" % len(self.proposalList)) self.chooseMenuList.setList(map(self.buildList, self.proposalList)) if self['menu_list'].getCurrent(): serien_name = self[self.modus].getCurrent()[0][0] serien_id = self[self.modus].getCurrent()[0][4] SerienRecorder.getCover(self, serien_name, serien_id) def buildList(self, entry): (Serie, Staffel, Sender, UTCTime, ID, MarkerFlag) = entry icon = imageNone = "%simages/black.png" % SerienRecorder.serienRecMainPath imageNeu = "%simages/neu.png" % SerienRecorder.serienRecMainPath if MarkerFlag == 1: setFarbe = parseColor('green').argb() elif MarkerFlag == 2: setFarbe = parseColor('red').argb() else: setFarbe = parseColor('foreground').argb() if str(Staffel).isdigit() and int(Staffel) == 1: icon = imageNeu foregroundColor = parseColor('foreground').argb() Staffel = "Staffel %s" % str(Staffel) WochenTag = ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"] xtime = time.strftime( WochenTag[time.localtime(int(UTCTime)).tm_wday] + ", %d.%m.%Y", time.localtime(int(UTCTime))) if config.plugins.serienRec.showPicons.value != "0": picon = loadPNG(imageNone) if Sender and self.serviceRefs.get(Sender): # Get picon by reference or by name piconPath = self.piconLoader.getPicon( self.serviceRefs.get(Sender)[0] if config.plugins. serienRec.showPicons.value == "1" else self.serviceRefs.get(Sender)[1]) if piconPath: self.picloader = PicLoader(80 * skinFactor, 40 * skinFactor) picon = self.picloader.load(piconPath) self.picloader.destroy() return [ entry, (eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 10, 5, 80 * skinFactor, 40 * skinFactor, picon), (eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 340 * skinFactor, 15 * skinFactor, 30 * skinFactor, 30 * skinFactor, loadPNG(icon)), (eListboxPythonMultiContent.TYPE_TEXT, 110 * skinFactor, 3, 230 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, Sender, foregroundColor, foregroundColor), (eListboxPythonMultiContent.TYPE_TEXT, 110 * skinFactor, 29 * skinFactor, 200 * skinFactor, 18 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, xtime), (eListboxPythonMultiContent.TYPE_TEXT, 375 * skinFactor, 3, 500 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, Serie, setFarbe, setFarbe), (eListboxPythonMultiContent.TYPE_TEXT, 375 * skinFactor, 29 * skinFactor, 500 * skinFactor, 18 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, Staffel) ] else: return [ entry, (eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 15, 15 * skinFactor, 30 * skinFactor, 30 * skinFactor, loadPNG(icon)), (eListboxPythonMultiContent.TYPE_TEXT, 50 * skinFactor, 3, 230 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, Sender, foregroundColor, foregroundColor), (eListboxPythonMultiContent.TYPE_TEXT, 50 * skinFactor, 29 * skinFactor, 200 * skinFactor, 18 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, xtime), (eListboxPythonMultiContent.TYPE_TEXT, 300 * skinFactor, 3, 500 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, Serie, setFarbe, setFarbe), (eListboxPythonMultiContent.TYPE_TEXT, 300 * skinFactor, 29 * skinFactor, 500 * skinFactor, 18 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, Staffel) ] def serieInfo(self): check = self[self.modus].getCurrent() if check is None: return serien_id = self[self.modus].getCurrent()[0][4] if serien_id > 0: serien_name = self[self.modus].getCurrent()[0][0] from SerienRecorderSeriesInfoScreen import serienRecShowInfo self.session.open(serienRecShowInfo, serien_name, serien_id) def wunschliste(self): serien_id = self[self.modus].getCurrent()[0][4] super(self.__class__, self).wunschliste(serien_id) def setupClose(self, result): super(self.__class__, self).setupClose(result) def keyOK(self): check = self[self.modus].getCurrent() if check is None: print "[SerienRecorder] Proposal-DB leer." return else: (Serie, Staffel, Sender, UTCTime, ID, MarkerFlag) = self[self.modus].getCurrent()[0] (existingID, AbStaffel, AlleSender ) = self.database.getMarkerSeasonAndChannelSettings(Serie) if existingID > 0: # Add season and channel of selected series to marker self.database.updateMarkerSeasonAndChannelSettings( existingID, AbStaffel, Staffel, AlleSender, Sender) # Activate marker self.database.setMarkerStatus( Serie, config.plugins.serienRec.BoxID.value, True) else: if config.plugins.serienRec.activateNewOnThisSTBOnly.value: boxID = config.plugins.serienRec.BoxID.value else: boxID = None self.database.addMarker(str(ID), Serie, "", boxID, 0) if config.plugins.serienRec.openMarkerScreen.value: from SerienRecorderMarkerScreen import serienRecMarker self.session.open(serienRecMarker, Serie) self.changesMade = True self.buildProposalList() self.chooseMenuList.setList(map(self.buildList, self.proposalList)) def keyYellow(self): if self.filter: self.filter = False else: self.filter = True self.buildProposalList() def keyLeft(self): self[self.modus].pageUp() serien_name = self[self.modus].getCurrent()[0][0] serien_id = self[self.modus].getCurrent()[0][4] SerienRecorder.getCover(self, serien_name, serien_id) def keyRight(self): self[self.modus].pageDown() serien_name = self[self.modus].getCurrent()[0][0] serien_id = self[self.modus].getCurrent()[0][4] SerienRecorder.getCover(self, serien_name, serien_id) def keyDown(self): self[self.modus].down() serien_name = self[self.modus].getCurrent()[0][0] serien_id = self[self.modus].getCurrent()[0][4] SerienRecorder.getCover(self, serien_name, serien_id) def keyUp(self): self[self.modus].up() serien_name = self[self.modus].getCurrent()[0][0] serien_id = self[self.modus].getCurrent()[0][4] SerienRecorder.getCover(self, serien_name, serien_id) def __onClose(self): self.stopDisplayTimer()
class serienRecTimerListScreen(serienRecBaseScreen, Screen, HelpableScreen): def __init__(self, session): serienRecBaseScreen.__init__(self, session) Screen.__init__(self, session) HelpableScreen.__init__(self) self.skin = None self.session = session self.picload = ePicLoad() self.WochenTag = ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"] self.database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) self["actions"] = HelpableActionMap( self, "SerienRecorderActions", { "ok": (self.keyOK, "Liste der erstellten Timer bearbeiten"), "cancel": (self.keyCancel, "zurück zur Serienplaner-Ansicht"), "left": (self.keyLeft, "zur vorherigen Seite blättern"), "right": (self.keyRight, "zur nächsten Seite blättern"), "up": (self.keyUp, "eine Zeile nach oben"), "down": (self.keyDown, "eine Zeile nach unten"), "red": (self.keyRed, "ausgewählten Timer löschen"), "green": (self.viewChange, "Sortierung ändern"), "yellow": (self.keyYellow, "umschalten alle/nur aktive Timer anzeigen"), "blue": (self.keyBlue, "alle noch ausstehenden Timer löschen"), "menu": (self.recSetup, "Menü für globale Einstellungen öffnen"), "startTeletext": (self.wunschliste, "Informationen zur ausgewählten Serie auf Wunschliste anzeigen" ), "0": (self.readLogFile, "Log-File des letzten Suchlaufs anzeigen"), "3": (self.showProposalDB, "Liste der Serien/Staffel-Starts anzeigen"), "4": (self.serieInfo, "Informationen zur ausgewählten Serie anzeigen"), "6": (self.showConflicts, "Liste der Timer-Konflikte anzeigen"), "7": (self.showWishlist, "Merkzettel (vorgemerkte Folgen) anzeigen"), "8": (self.cleanUp, "Timerliste bereinigen"), "9": (self.dropAllTimer, "Alle Timer aus der Datenbank löschen"), }, -1) self.helpList[0][2].sort() self["helpActions"] = ActionMap( [ "SerienRecorderActions", ], { # "ok" : self.keyOK, "displayHelp": self.showHelp, "displayHelp_long": self.showManual, }, 0) self.setupSkin() self.changesMade = False self.filter = True self.onLayoutFinish.append(self.readTimer) self.onClose.append(self.__onClose) self.onLayoutFinish.append(self.setSkinProperties) def callHelpAction(self, *args): HelpableScreen.callHelpAction(self, *args) def setSkinProperties(self): super(self.__class__, self).setSkinProperties() self['text_red'].setText("Entferne Timer") if config.plugins.serienRec.recordListView.value == 0: self['text_green'].setText("Zeige neueste Timer zuerst") elif config.plugins.serienRec.recordListView.value == 1: self['text_green'].setText("Zeige früheste Timer zuerst") self['text_ok'].setText("Liste bearbeiten") self['text_yellow'].setText("Zeige auch alte Timer") self['text_blue'].setText("Entferne neue Timer") self.num_bt_text[3][1] = "Bereinigen" self.num_bt_text[4][1] = "Datenbank leeren" super(self.__class__, self).startDisplayTimer() def setupSkin(self): InitSkin(self) self.chooseMenuList = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self.chooseMenuList.l.setFont( 0, gFont('Regular', 20 + int(config.plugins.serienRec.listFontsize.value))) self.chooseMenuList.l.setItemHeight(int(50 * skinFactor)) self['menu_list'] = self.chooseMenuList self['menu_list'].show() if config.plugins.serienRec.showCover.value: self['cover'].show() if not config.plugins.serienRec.showAllButtons.value: self['bt_red'].show() self['bt_green'].show() self['bt_ok'].show() self['bt_yellow'].show() self['bt_blue'].show() self['bt_exit'].show() self['bt_text'].show() self['bt_info'].show() self['bt_menu'].show() self['text_red'].show() self['text_green'].show() self['text_ok'].show() self['text_yellow'].show() self['text_blue'].show() self['text_0'].show() self['text_1'].show() self['text_2'].show() self['text_3'].show() self['text_4'].show() def updateMenuKeys(self): updateMenuKeys(self) def serieInfo(self): check = self['menu_list'].getCurrent() if check is None: return serien_name = self['menu_list'].getCurrent()[0][0] url = self.database.getMarkerURL(serien_name) if url: serien_id = url if serien_id: from SerienRecorderSeriesInfoScreen import serienRecShowInfo self.session.open(serienRecShowInfo, serien_name, serien_id) def wunschliste(self): serien_name = self['menu_list'].getCurrent()[0][0] url = self.database.getMarkerURL(serien_name) serien_id = url super(self.__class__, self).wunschliste(serien_id) def setupClose(self, result): super(self.__class__, self).setupClose(result) if result[1]: self.readTimer() def viewChange(self): if config.plugins.serienRec.recordListView.value == 1: config.plugins.serienRec.recordListView.value = 0 self['text_green'].setText("Zeige neueste Timer zuerst") else: config.plugins.serienRec.recordListView.value = 1 self['text_green'].setText("Zeige früheste Timer zuerst") config.plugins.serienRec.recordListView.save() SerienRecorder.configfile.save() self.readTimer() def readTimer(self, showTitle=True): current_time = int(time.time()) deltimer = 0 timerList = [] timers = self.database.getAllTimer( current_time if self.filter else None) for timer in timers: (serie, staffel, episode, title, start_time, stbRef, webChannel, eit, activeTimer) = timer if int(start_time) < int(current_time): deltimer += 1 timerList.append((serie, staffel, episode, title, start_time, webChannel, "1", 0, bool(activeTimer))) else: timerList.append((serie, staffel, episode, title, start_time, webChannel, "0", eit, bool(activeTimer))) if showTitle: self['title'].instance.setForegroundColor(parseColor("foreground")) if self.filter: self['title'].setText("Timer-Liste: %s ausstehende Timer" % len(timerList)) else: self['title'].setText( "Timer-Liste: %s abgeschlossene und %s ausstehende Timer" % (deltimer, len(timerList) - deltimer)) if config.plugins.serienRec.recordListView.value == 0: timerList.sort(key=lambda t: t[4]) elif config.plugins.serienRec.recordListView.value == 1: timerList.sort(key=lambda t: t[4]) timerList.reverse() self.chooseMenuList.setList(map(self.buildList, timerList)) if len(timerList) == 0: if showTitle: self['title'].instance.setForegroundColor( parseColor("foreground")) self['title'].setText( "Serien Timer - 0 Serien in der Aufnahmeliste.") self.getCover() def buildList(self, entry): (serie, staffel, episode, title, start_time, webChannel, foundIcon, eit, activeTimer) = entry xtime = time.strftime( self.WochenTag[time.localtime(int(start_time)).tm_wday] + ", %d.%m.%Y - %H:%M", time.localtime(int(start_time))) xtitle = "S%sE%s - %s" % (str(staffel).zfill(2), str(episode).zfill(2), title) if int(foundIcon) == 1: imageFound = "%simages/found.png" % SerienRecorder.serienRecMainPath else: imageFound = "%simages/black.png" % SerienRecorder.serienRecMainPath if activeTimer: SerieColor = None else: SerieColor = parseColor('red').argb() foregroundColor = parseColor('foreground').argb() return [ entry, (eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 5, 8 * skinFactor, 32 * skinFactor, 32 * skinFactor, loadPNG(imageFound)), (eListboxPythonMultiContent.TYPE_TEXT, 40, 3, 250 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, webChannel, SerieColor, SerieColor), (eListboxPythonMultiContent.TYPE_TEXT, 40, 29 * skinFactor, 250 * skinFactor, 18 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, xtime, foregroundColor, foregroundColor), (eListboxPythonMultiContent.TYPE_TEXT, 300 * skinFactor, 3, 500 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, serie, SerieColor, SerieColor), (eListboxPythonMultiContent.TYPE_TEXT, 300 * skinFactor, 29 * skinFactor, 500 * skinFactor, 18 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, re.sub("(?<= - )dump\Z", "(Manuell hinzugefügt !!)", xtitle), foregroundColor, foregroundColor) ] def keyOK(self): self.session.open(serienRecModifyAdded, False) def callDeleteSelectedTimer(self, answer): if answer: serien_name = self['menu_list'].getCurrent()[0][0] staffel = self['menu_list'].getCurrent()[0][1] episode = self['menu_list'].getCurrent()[0][2] serien_title = self['menu_list'].getCurrent()[0][3] serien_time = self['menu_list'].getCurrent()[0][4] serien_channel = self['menu_list'].getCurrent()[0][5] serien_eit = self['menu_list'].getCurrent()[0][7] self.removeTimer(serien_name, staffel, episode, serien_title, serien_time, serien_channel, serien_eit) else: return def removeTimer(self, serien_name, staffel, episode, serien_title, serien_time, serien_channel, serien_eit=0): if config.plugins.serienRec.TimerName.value == "1": # "<Serienname>" title = serien_name elif config.plugins.serienRec.TimerName.value == "2": # "SnnEmm - <Episodentitel>" title = "S%sE%s - %s" % (str(staffel).zfill(2), str(episode).zfill(2), serien_title) elif config.plugins.serienRec.TimerName.value == "3": # "<Serienname> - SnnEmm" title = "%s - S%sE%s" % (serien_name, str(staffel).zfill(2), str(episode).zfill(2)) else: # "<Serienname> - SnnEmm - <Episodentitel>" title = "%s - S%sE%s - %s" % (serien_name, str(staffel).zfill(2), str(episode).zfill(2), serien_title) from SerienRecorderTimer import serienRecBoxTimer removed = serienRecBoxTimer.removeTimerEntry(title, serien_time, serien_eit) if not removed: print "[SerienRecorder] enigma2 NOOOTTT removed" else: print "[SerienRecorder] enigma2 Timer removed." self.database.removeTimer(serien_name, staffel, episode, None, serien_time, serien_channel, (serien_eit if serien_eit > 0 else None)) self.changesMade = True self.readTimer(False) self['title'].instance.setForegroundColor(parseColor("red")) self['title'].setText("Timer '- %s -' entfernt." % serien_name) def keyRed(self): check = self['menu_list'].getCurrent() if check is None: print "[SerienRecorder] Serien Timer leer." return else: serien_name = self['menu_list'].getCurrent()[0][0] staffel = self['menu_list'].getCurrent()[0][1] episode = self['menu_list'].getCurrent()[0][2] serien_title = self['menu_list'].getCurrent()[0][3] serien_time = self['menu_list'].getCurrent()[0][4] serien_channel = self['menu_list'].getCurrent()[0][5] serien_eit = self['menu_list'].getCurrent()[0][7] print self['menu_list'].getCurrent()[0] if config.plugins.serienRec.confirmOnDelete.value: self.session.openWithCallback( self.callDeleteSelectedTimer, MessageBox, "Soll '%s - S%sE%s - %s' wirklich entfernt werden?" % (serien_name, str(staffel).zfill(2), str(episode).zfill(2), re.sub("\Adump\Z", "(Manuell hinzugefügt !!)", serien_title)), MessageBox.TYPE_YESNO, default=False) else: self.removeTimer(serien_name, staffel, episode, serien_title, serien_time, serien_channel, serien_eit) def keyYellow(self): if self.filter: self['text_yellow'].setText("Zeige nur neue Timer") self.filter = False else: self['text_yellow'].setText("Zeige auch alte Timer") self.filter = True self.readTimer() def keyBlue(self): if config.plugins.serienRec.confirmOnDelete.value: self.session.openWithCallback( self.removeNewTimerFromDB, MessageBox, "Sollen wirklich alle noch ausstehenden Timer von der Box und aus der Datenbank entfernt werden?", MessageBox.TYPE_YESNO, default=False) else: self.removeNewTimerFromDB(True) def removeNewTimerFromDB(self, answer): if answer: current_time = int(time.time()) timers = self.database.getAllTimer(current_time) for timer in timers: (serie, staffel, episode, title, start_time, stbRef, webChannel, eit, activeTimer) = timer self.removeTimer(serie, staffel, episode, title, start_time, webChannel, eit) self.readTimer(False) self['title'].instance.setForegroundColor(parseColor("red")) self['title'].setText( "Alle noch ausstehenden Timer wurden entfernt.") else: return def removeOldTimerFromDB(self, answer): if answer: self.database.removeAllOldTimer() self.database.rebuild() self.readTimer(False) self['title'].instance.setForegroundColor(parseColor("red")) self['title'].setText("Alle alten Timer wurden entfernt.") else: return def dropAllTimer(self): if config.plugins.serienRec.confirmOnDelete.value: self.session.openWithCallback( self.removeOldTimerFromDB, MessageBox, "Sollen wirklich alle alten Timer aus der Datenbank entfernt werden?", MessageBox.TYPE_YESNO, default=False) else: self.removeOldTimerFromDB(True) def cleanUp(self): numberOfOrphanTimers = self.database.countOrphanTimers() self.session.openWithCallback( self.removeOrphanTimerFromDB, MessageBox, "Es wurden %d Einträge in der Timer-Liste gefunden, für die kein Serien-Marker vorhanden ist, sollen diese Einträge gelöscht werden?" % numberOfOrphanTimers, MessageBox.TYPE_YESNO, default=False) def removeOrphanTimerFromDB(self, answer): if answer: self.database.removeOrphanTimers() self.database.rebuild() else: return def getCover(self): check = self['menu_list'].getCurrent() if check is None: return serien_name = self['menu_list'].getCurrent()[0][0] serien_id = None url = self.database.getMarkerURL(serien_name) if url: serien_id = url SerienRecorder.getCover(self, serien_name, serien_id) def keyLeft(self): self['menu_list'].pageUp() self.getCover() def keyRight(self): self['menu_list'].pageDown() self.getCover() def keyDown(self): self['menu_list'].down() self.getCover() def keyUp(self): self['menu_list'].up() self.getCover() def __onClose(self): self.stopDisplayTimer() def keyCancel(self): if config.plugins.serienRec.refreshViews.value: self.close(self.changesMade) else: self.close(False)
class serienRecShowConflicts(serienRecBaseScreen, Screen, HelpableScreen): def __init__(self, session): serienRecBaseScreen.__init__(self, session) Screen.__init__(self, session) HelpableScreen.__init__(self) self.skin = None self.conflictsListe = [] self.session = session self.database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) self["actions"] = HelpableActionMap(self, "SerienRecorderActions", { "cancel": (self.keyCancel, "zurück zur vorherigen Ansicht"), "left": (self.keyLeft, "zur vorherigen Seite blättern"), "right": (self.keyRight, "zur nächsten Seite blättern"), "up": (self.keyUp, "eine Zeile nach oben"), "down": (self.keyDown, "eine Zeile nach unten"), "red": (self.keyCancel, "zurück zur vorherigen Ansicht"), "blue": (self.keyBlue, "alle Einträge aus der Liste endgültig löschen"), "menu": (self.recSetup, "Menü für globale Einstellungen öffnen"), "0" : (self.readLogFile, "Log-File des letzten Suchlaufs anzeigen"), "3" : (self.showProposalDB, "Liste der Serien/Staffel-Starts anzeigen"), "7" : (self.showWishlist, "Merkzettel (vorgemerkte Folgen) anzeigen"), }, -1) self.helpList[0][2].sort() self["helpActions"] = ActionMap(["SerienRecorderActions" ,], { "displayHelp" : self.showHelp, "displayHelp_long" : self.showManual, }, 0) self.setupSkin() self.onLayoutFinish.append(self.readConflicts) self.onClose.append(self.__onClose) self.onLayoutFinish.append(self.setSkinProperties) def callHelpAction(self, *args): HelpableScreen.callHelpAction(self, *args) def setSkinProperties(self): super(self.__class__, self).setSkinProperties() self['text_red'].setText("Abbrechen") self['text_blue'].setText("Liste leeren") self.num_bt_text[1][1] = buttonText_na self.num_bt_text[4][0] = buttonText_na super(self.__class__, self).startDisplayTimer() def setupSkin(self): InitSkin(self) self.chooseMenuList = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self.chooseMenuList.l.setFont(0, gFont('Regular', 20 + int(config.plugins.serienRec.listFontsize.value))) self.chooseMenuList.l.setItemHeight(int(25 *skinFactor)) self['menu_list'] = self.chooseMenuList self['menu_list'].show() self['title'].setText("Timer-Konflikte") if not config.plugins.serienRec.showAllButtons.value: self['bt_red'].show() self['bt_blue'].show() self['bt_exit'].show() self['bt_info'].show() self['bt_menu'].show() self['text_red'].show() self['text_blue'].show() self['text_0'].show() self['text_1'].show() self['text_2'].show() self['text_3'].show() self['text_4'].show() def updateMenuKeys(self): updateMenuKeys(self) def setupClose(self, result): super(self.__class__, self).setupClose(result) if result[1]: self.readConflicts() def readConflicts(self): conflicts = self.database.getTimerConflicts() for conflict in conflicts: (zeile, start_time, webChannel) = conflict data = zeile.split('/') if data: self.conflictsListe.append(("%s" % data[0].strip())) self.conflictsListe.append((" @ %s (%s) in Konflikt mit:" % (webChannel, time.strftime("%d.%m.%Y - %H:%M", time.localtime(start_time))))) data = data[1:] for row2 in data: self.conflictsListe.append((" -> %s" % row2.strip())) self.conflictsListe.append(("-" * 100)) self.conflictsListe.append("") self.chooseMenuList.setList(map(self.buildList, self.conflictsListe)) @staticmethod def buildList(entry): (zeile) = entry return [entry, (eListboxPythonMultiContent.TYPE_TEXT, 00, 00, 850 * skinFactor, 20 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, zeile)] def keyLeft(self): self['menu_list'].pageUp() def keyRight(self): self['menu_list'].pageDown() def keyDown(self): self['menu_list'].down() def keyUp(self): self['menu_list'].up() def keyBlue(self): check = self['menu_list'].getCurrent() if check is None: print "[SerienRecorder] Conflict-List leer." return else: if config.plugins.serienRec.confirmOnDelete.value: self.session.openWithCallback(self.callDeleteMsg, MessageBox, "Soll die Liste wirklich geleert werden?", MessageBox.TYPE_YESNO, default=False) else: self.callDeleteMsg(True) def callDeleteMsg(self, answer): if answer: self.database.removeAllTimerConflicts() self.readConflicts() else: return def __onClose(self): self.stopDisplayTimer() def keyCancel(self): self.close()
class serienRecTimer: def __init__(self): self.countTimer = 0 self.countTimerUpdate = 0 self.countNotActiveTimer = 0 self.countTimerFromWishlist = 0 self.messageList = [] self.database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) self.tempDB = None self.konflikt = "" self.enableDirectoryCreation = False def setTempDB(self, database): self.tempDB = database def getCounts(self): return self.countTimer, self.countTimerUpdate, self.countNotActiveTimer, self.countTimerFromWishlist, self.messageList 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 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 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) 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 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 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 shouldCreateEventTimer(self, serien_name, staffel, episode, title): if self.database.getNumberOfTimers(serien_name, staffel, episode, title, False): return False result = True if config.plugins.serienRec.splitEventTimer.value != "2" and '/' in str(episode): # Event-Programmierung auflösen -> 01/1x02/1x03 splitedSeasonEpisodeList = [] if 'x' in str(episode): episode = str(staffel) + 'x' + str(episode) seasonEpisodeList = episode.split('/') for seasonEpisode in seasonEpisodeList: splitedSeasonEpisodeList.append(seasonEpisode.split('x')) else: seasonEpisodeList = episode.split('/') for seasonEpisode in seasonEpisodeList: seasonEpisode = str(staffel) + 'x' + str(seasonEpisode) splitedSeasonEpisodeList.append(seasonEpisode.split('x')) useTitles = True splitedTitleList = title.split('/') if len(splitedTitleList) != len(splitedSeasonEpisodeList): useTitles = False # Möglichst die Einzelfolgen bevorzugen und Event ignorieren alreadyExistsCount = 0 for idx,entry in enumerate(splitedSeasonEpisodeList): title = "dump" if useTitles: title = splitedTitleList[idx] alreadyExists = self.database.getNumberOfTimers(serien_name, entry[0], entry[1], title, False) if alreadyExists: alreadyExistsCount += 1 if alreadyExistsCount == len(splitedSeasonEpisodeList): result = False return result 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) @staticmethod def splitEvent(episode, staffel, title): splitedSeasonEpisodeList = [] if 'x' in str(episode): seasonEpisodeList = episode.split('/') for seasonEpisode in seasonEpisodeList: if not 'x' in seasonEpisode: seasonEpisode = str(staffel) + 'x' + str(seasonEpisode) splitedSeasonEpisodeList.append(seasonEpisode.split('x')) else: seasonEpisodeList = episode.split('/') for seasonEpisode in seasonEpisodeList: seasonEpisode = str(staffel) + 'x' + str(seasonEpisode) splitedSeasonEpisodeList.append(seasonEpisode.split('x')) useTitles = True splitedTitleList = title.split('/') if len(splitedTitleList) != len(splitedSeasonEpisodeList): useTitles = False return splitedSeasonEpisodeList, splitedTitleList, useTitles
def __init__(self, manuell): self.database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) self.manuell = manuell
class serienRecEpisodes(serienRecBaseScreen, Screen, HelpableScreen): def __init__(self, session, serien_name, serie_url, serien_cover): serienRecBaseScreen.__init__(self, session) Screen.__init__(self, session) HelpableScreen.__init__(self) self.ErrorMsg = '' self.database = SRDatabase(serienRecDataBaseFilePath) self.modus = "menu_list" self.session = session self.picload = ePicLoad() self.serien_name = serien_name self.serien_id = 0 self.serien_cover = serien_cover self.addedEpisodes = self.database.getTimerForSeries(self.serien_name) self.episodes_list_cache = {} self.aStaffel = None self.aFromEpisode = None self.aToEpisode = None #self.pages = [] self.page = 1 self.maxPages = 1 self.loading = False self.changesMade = False self["actions"] = HelpableActionMap(self, "SerienRecorderActions", { "ok" : (self.keyOK, "Informationen zur ausgewählten Episode anzeigen"), "cancel": (self.keyCancel, "Zurück zur Serien-Marker-Ansicht"), "left" : (self.keyLeft, "Zur vorherigen Seite blättern"), "right" : (self.keyRight, "Zur nächsten Seite blättern"), "up" : (self.keyUp, "Eine Zeile nach oben"), "down" : (self.keyDown, "Eine Zeile nach unten"), "red" : (self.keyRed, "Zurück zur Serien-Marker-Ansicht"), "green" : (self.keyGreen, "Diese Folge (nicht mehr) aufnehmen"), "yellow": (self.keyYellow, "Ausgewählte Folge auf den Merkzettel"), "blue" : (self.keyBlue, "Neue Einträge manuell hinzufügen"), "menu" : (self.recSetup, "Menü für globale Einstellungen öffnen"), "nextBouquet" : (self.nextPage, "Nächste Seite laden"), "prevBouquet" : (self.backPage, "Vorherige Seite laden"), "startTeletext" : (self.wunschliste, "Informationen zur ausgewählten Serie auf Wunschliste anzeigen"), "0" : (self.readLogFile, "Log-File des letzten Suchlaufs anzeigen"), "3" : (self.showProposalDB, "Liste der Serien/Staffel-Starts anzeigen"), "4" : (self.serieInfo, "Informationen zur ausgewählten Serie anzeigen"), "6" : (self.showConflicts, "Liste der Timer-Konflikte anzeigen"), "7" : (self.showWishlist, "Merkzettel (vorgemerkte Folgen) anzeigen"), }, -1) self.helpList[0][2].sort() self["helpActions"] = ActionMap(["SerienRecorderActions", ], { "displayHelp" : self.showHelp, "displayHelp_long" : self.showManual, }, 0) self.setupSkin() self.serien_id = serie_url self.timer_default = eTimer() if isDreamOS(): self.timer_default_conn = self.timer_default.timeout.connect(self.loadEpisodes) else: self.timer_default.callback.append(self.loadEpisodes) self.onLayoutFinish.append(self.setSkinProperties) self.onLayoutFinish.append(self.searchEpisodes) self.onClose.append(self.__onClose) def callHelpAction(self, *args): HelpableScreen.callHelpAction(self, *args) def setSkinProperties(self): super(self.__class__, self).setSkinProperties() self['text_red'].setText("Zurück") self['text_green'].setText("(De)aktivieren") self['text_ok'].setText("Beschreibung") self['text_yellow'].setText("Auf den Merkzettel") self['text_blue'].setText("Manuell hinzufügen") #self['headline'].instance.setHAlign(2) self['headline'].instance.setForegroundColor(parseColor('red')) self['headline'].instance.setFont(parseFont("Regular;16", ((1,1),(1,1)))) self.chooseMenuList.l.setItemHeight(int(28 * skinFactor)) self.num_bt_text[2][2] = buttonText_na self.num_bt_text[3][2] = buttonText_na super(self.__class__, self).startDisplayTimer() def setupSkin(self): super(self.__class__, self).setupSkin() self[self.modus].show() if config.plugins.serienRec.showCover.value: self['cover'].show() if not config.plugins.serienRec.showAllButtons.value: self['bt_epg'].hide() self['bt_info'].hide() self['bt_red'].show() self['bt_green'].show() self['bt_ok'].show() self['bt_yellow'].show() self['bt_blue'].show() self['bt_exit'].show() self['bt_text'].show() self['bt_menu'].show() self['text_red'].show() self['text_green'].show() self['text_ok'].show() self['text_yellow'].show() self['text_blue'].show() self['text_0'].show() self['text_1'].show() self['text_2'].show() self['text_3'].show() self['text_4'].show() def updateMenuKeys(self): updateMenuKeys(self) def setupClose(self, result): super(self.__class__, self).setupClose(result) def wunschliste(self): super(self.__class__, self).wunschliste(self.serien_id) def searchEpisodes(self): super(self.__class__, self).getCover(self.serien_name) self['title'].setText("Suche Episoden ' %s '" % self.serien_name) self.loading = True self.timer_default.start(0) def resultsEpisodes(self, data): self.maxPages = 1 self.episodes_list_cache[self.page] = [] for episode in data["episodes"]: if "title" in episode: title = episode["title"].encode("utf-8") else: title = "-" self.episodes_list_cache[self.page].append( [episode["season"], episode["episode"], episode["id"], title]) self.chooseMenuList.setList(map(self.buildList_episodes, self.episodes_list_cache[self.page])) numberOfEpisodes = data["numEpisodes"] self.loading = False self['title'].setText("%s Episoden für ' %s ' gefunden." % (numberOfEpisodes, self.serien_name)) self.showPages() def loadEpisodes(self): self.timer_default.stop() if self.page in self.episodes_list_cache: self.chooseMenuList.setList(map(self.buildList_episodes, self.episodes_list_cache[self.page])) else: getCover(self, self.serien_name, self.serien_id) try: episodes = SeriesServer().doGetEpisodes(int(self.serien_id), int(self.page)) self.resultsEpisodes(episodes) except: self['title'].setText("Fehler beim Abrufen der Episodenliste") def buildList_episodes(self, entry): (season, episode, info_id, title) = entry seasonEpisodeString = "S%sE%s" % (str(season).zfill(2), str(episode).zfill(2)) imageMinus = "%simages/red_dot.png" % serienRecMainPath imagePlus = "%simages/green_dot.png" % serienRecMainPath imageNone = "%simages/black.png" % serienRecMainPath middleImage = imageNone leftImage = imageMinus if len(self.addedEpisodes) > 0 and self.isAlreadyAdded(season, episode, title): leftImage = imagePlus color = parseColor('yellow').argb() if not str(season).isdigit(): color = parseColor('red').argb() return [entry, (eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 5, 8 * skinFactor, 16 * skinFactor, 16 * skinFactor, loadPNG(leftImage)), (eListboxPythonMultiContent.TYPE_TEXT, 40 * skinFactor, 3, 140 * skinFactor, 22 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, "%s" % seasonEpisodeString, color), (eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 150 * skinFactor, 17 * skinFactor, 22 * skinFactor, 48 * skinFactor, loadPNG(middleImage)), (eListboxPythonMultiContent.TYPE_TEXT, 200 * skinFactor, 3, 550 * skinFactor, 22 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, title), #(eListboxPythonMultiContent.TYPE_TEXT, 200 * skinFactor, 29 * skinFactor, 550 * skinFactor, 18 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, otitle, parseColor('yellow').argb()), ] def showPages(self): headline = "Diese Liste stammt von TheTVDB, daher kann die Nummerierung/Episodenbeschreibung abweichen." if self.maxPages > 1: headline += " Seite %s/%s" % (str(self.page), str(self.maxPages)) self['headline'].setText(headline) def isAlreadyAdded(self, season, episode, title=None): result = False #Title is only relevant if season and episode is 0 #this happen when Wunschliste has no episode and season information seasonEpisodeString = "S%sE%s" % (str(season).zfill(2), str(episode).zfill(2)) if seasonEpisodeString != "S00E00": title = None if not title: for addedEpisode in self.addedEpisodes[:]: if str(addedEpisode[0]).zfill(2) == str(season).zfill(2) and str(addedEpisode[1]).zfill(2) == str(episode).zfill(2): result = True #self.addedEpisodes.remove(addedEpisode) break else: for addedEpisode in self.addedEpisodes[:]: if (str(addedEpisode[0]).zfill(2) == str(season).zfill(2)) and (str(addedEpisode[1]).zfill(2) == str(episode).zfill(2)) and (addedEpisode[2] == title): result = True #self.addedEpisodes.remove(addedEpisode) break return result def removeFromDB(self, season, episode, title=None): seasonEpisodeString = "S%sE%s" % (str(season).zfill(2), str(episode).zfill(2)) if seasonEpisodeString != "S00E00": title = None self.database.removeTimer(self.serien_name, season, episode, title, None, None, None) def keyOK(self): if self.loading: return check = self['menu_list'].getCurrent() if not check: return sindex = self['menu_list'].getSelectedIndex() #if len(self.episodes_list_cache) >= self.page: if self.page in self.episodes_list_cache: if len(self.episodes_list_cache[self.page]) != 0: if self.episodes_list_cache[self.page][sindex][2]: self.session.open(serienRecShowEpisodeInfo, self.serien_name, self.serien_id, self.episodes_list_cache[self.page][sindex][3], self.episodes_list_cache[self.page][sindex][2]) #self.session.open(MessageBox, "Diese Funktion steht in dieser Version noch nicht zur Verfügung!", MessageBox.TYPE_INFO, timeout=10) def keyGreen(self): if self.loading: return check = self['menu_list'].getCurrent() if not check: return sindex = self['menu_list'].getSelectedIndex() #if len(self.episodes_list_cache) >= self.page: if self.page in self.episodes_list_cache: current_episodes_list = self.episodes_list_cache[self.page] if len(current_episodes_list) != 0: isAlreadyAdded = self.isAlreadyAdded(current_episodes_list[sindex][0], current_episodes_list[sindex][1], current_episodes_list[sindex][3]) if isAlreadyAdded: self.removeFromDB(current_episodes_list[sindex][0], current_episodes_list[sindex][1], current_episodes_list[sindex][3]) else: self.database.addToTimerList(self.serien_name, current_episodes_list[sindex][1], current_episodes_list[sindex][1], current_episodes_list[sindex][0], current_episodes_list[sindex][3], int(time.time()), "", "", 0, 1) self.addedEpisodes = self.database.getTimerForSeries(self.serien_name) self.chooseMenuList.setList(map(self.buildList_episodes, current_episodes_list)) def keyYellow(self): if self.loading: return check = self['menu_list'].getCurrent() if not check: return sindex = self['menu_list'].getSelectedIndex() #if len(self.episodes_list_cache) >= self.page: if self.page in self.episodes_list_cache: if len(self.episodes_list_cache[self.page]) != 0: if self.database.addBookmark(self.serien_name, self.episodes_list_cache[self.page][sindex][1], self.episodes_list_cache[self.page][sindex][1], self.episodes_list_cache[self.page][sindex][0], config.plugins.serienRec.NoOfRecords.value): self.session.open(MessageBox, "Die Episode wurde zum Merkzettel hinzugefügt", MessageBox.TYPE_INFO, timeout = 10) def nextPage(self): if self.loading: return if self.page <= self.maxPages: if self.page == self.maxPages: self.page = 1 else: self.page += 1 self.showPages() self.chooseMenuList.setList(map(self.buildList_episodes, [])) self.searchEpisodes() def backPage(self): if self.loading: return if self.page >= 1 and self.maxPages > 1: if self.page == 1: self.page = self.maxPages else: self.page -= 1 self.showPages() self.chooseMenuList.setList(map(self.buildList_episodes, [])) self.searchEpisodes() def answerStaffel(self, aStaffel): self.aStaffel = aStaffel if not self.aStaffel or self.aStaffel == "": return self.session.openWithCallback(self.answerFromEpisode, NTIVirtualKeyBoard, title = "von Episode:") def answerFromEpisode(self, aFromEpisode): self.aFromEpisode = aFromEpisode if not self.aFromEpisode or self.aFromEpisode == "": return self.session.openWithCallback(self.answerToEpisode, NTIVirtualKeyBoard, title = "bis Episode:") def answerToEpisode(self, aToEpisode): self.aToEpisode = aToEpisode if self.aToEpisode == "": self.aToEpisode = self.aFromEpisode if not self.aToEpisode: # or self.aFromEpisode is None or self.aStaffel is None: return else: print "[SerienRecorder] Staffel: %s" % self.aStaffel print "[SerienRecorder] von Episode: %s" % self.aFromEpisode print "[SerienRecorder] bis Episode: %s" % self.aToEpisode if self.database.addToTimerList(self.serien_name, self.aFromEpisode, self.aToEpisode, self.aStaffel, "dump", int(time.time()), "", "", 0, 1): self.chooseMenuList.setList(map(self.buildList_episodes, self.episodes_list_cache[self.page])) def keyBlue(self): self.aStaffel = None self.aFromEpisode = None self.aToEpisode = None self.session.openWithCallback(self.answerStaffel, NTIVirtualKeyBoard, title = "%s: Staffel eingeben:" % self.serien_name) def __onClose(self): self.stopDisplayTimer()
class serienRecCheckForRecording: instance = None epgrefresh_instance = None 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) @staticmethod def getNextAutoCheckTimer(lt): acttime = (lt.tm_hour * 60 + lt.tm_min) deltime = (config.plugins.serienRec.deltime.value[0] * 60 + config.plugins.serienRec.deltime.value[1]) if acttime < deltime: deltatime = deltime - acttime else: deltatime = abs(1440 - acttime + deltime) return deltatime 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 getMarkerCover(self): self.database = SRDatabase(serienRecDataBaseFilePath) markers = self.database.getAllMarkers(False) for marker in markers: (ID, Serie, Info, Url, AufnahmeVerzeichnis, AlleStaffelnAb, alleSender, Vorlaufzeit, Nachlaufzeit, AnzahlAufnahmen, preferredChannel, useAlternativeChannel, AbEpisode, TimerForSpecials, ErlaubteSTB, ErlaubteStaffelCount) = marker getCover(None, Serie, ID, True) 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 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 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 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 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 askForDSB(self): if not self.manuell: if config.plugins.serienRec.afterAutocheck.value != "0": if config.plugins.serienRec.DSBTimeout.value > 0 and not Screens.Standby.inStandby: print "[SerienRecorder] Try to display shutdown notification..." try: notificationText = "Soll der SerienRecorder die Box in den Ruhemodus (Standby) schalten?" if config.plugins.serienRec.afterAutocheck.value == "2": notificationText = "Soll der SerienRecorder die Box ausschalten (Deep-Standby)?" Notifications.AddNotificationWithCallback(self.gotoDeepStandby, MessageBox, text=notificationText, type=MessageBox.TYPE_YESNO, timeout=config.plugins.serienRec.DSBTimeout.value, default=True) except Exception as e: print "[SerienRecorder] Could not display shutdown notification - shutdown box without notification... (%s)" % str(e) self.gotoDeepStandby(True) else: self.gotoDeepStandby(True) 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 checkSender(self, channel): if channel.lower() in self.senderListe: (webChannel, stbChannel, stbRef, altstbChannel, altstbRef, status) = self.senderListe[channel.lower()] else: webChannel = channel stbChannel = "" stbRef = "" altstbChannel = "" altstbRef = "" status = "0" return webChannel, stbChannel, stbRef, altstbChannel, altstbRef, status @staticmethod def dataError(error): print "[SerienRecorder] Es ist ein Fehler aufgetreten - die Daten konnten nicht abgerufen/verarbeitet werden: (%s)" % error
class serienRecSeriesPlanner: def __init__(self, manuell): self.database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) self.manuell = manuell 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 processPlanerData(self, data, markers, daypage): if not data or len(data) == 0: pass daylist = [[]] headDate = [data["date"]] timers = [] # txt = headDate[0].split(",") # (day, month, year) = txt[1].split(".") # UTCDatum = TimeHelpers.getRealUnixTime(0, 0, day, month, year) if (not self.manuell) and config.plugins.serienRec.planerCacheEnabled.value: timers = self.database.getTimer(daypage) for event in data["events"]: aufnahme = False serieAdded = 0 start_h = event["time"][:+2] start_m = event["time"][+3:] start_time = TimeHelpers.getUnixTimeWithDayOffset(start_h, start_m, daypage) serien_name = event["name"].encode("utf-8") serien_name_lower = serien_name.lower() sender = event["channel"] title = event["title"].encode("utf-8") staffel = event["season"] episode = event["episode"] serien_id = event["id"] if (not self.manuell) and config.plugins.serienRec.planerCacheEnabled.value: serienTimers = [timer for timer in timers if timer[0] == serien_name_lower] serienTimersOnChannel = [serienTimer for serienTimer in serienTimers if serienTimer[2] == sender.lower()] for serienTimerOnChannel in serienTimersOnChannel: if (int(serienTimerOnChannel[1]) >= (int(start_time) - 300)) and ( int(serienTimerOnChannel[1]) < (int(start_time) + 300)): aufnahme = True # 0 = no marker, 1 = active marker, 2 = deactive marker if serien_name_lower in markers: serieAdded = 1 if markers[serien_name_lower] else 2 staffel = str(staffel).zfill(2) episode = str(episode).zfill(2) ############################## # # CHECK # # ueberprueft anhand des Seriennamen, Season, Episode ob die serie bereits auf der HDD existiert # seasonEpisodeString = "S%sE%s" % (str(staffel).zfill(2), str(episode).zfill(2)) bereits_vorhanden = False if config.plugins.serienRec.sucheAufnahme.value: (dirname, dirname_serie) = getDirname(self.database, serien_name, staffel) if str(episode).isdigit(): if int(episode) == 0: bereits_vorhanden = STBHelpers.countEpisodeOnHDD(dirname, seasonEpisodeString, serien_name, False, title) > 0 and True or False else: bereits_vorhanden = STBHelpers.countEpisodeOnHDD(dirname, seasonEpisodeString, serien_name, False) > 0 and True or False else: bereits_vorhanden = STBHelpers.countEpisodeOnHDD(dirname, seasonEpisodeString, serien_name, False) > 0 and True or False title = "%s - %s" % (seasonEpisodeString, title) regional = False paytv = False neu = event["new"] prime = False transmissionTime = event["time"] url = '' daylist[0].append((regional, paytv, neu, prime, transmissionTime, url, serien_name, sender, staffel, episode, title, aufnahme, serieAdded, bereits_vorhanden, serien_id)) if (not self.manuell) and config.plugins.serienRec.planerCacheEnabled.value and headDate: d = headDate[0].split(',') d.reverse() key = d[0].strip() cache = self.loadPlanerData(1) cache.update({key: (headDate, daylist)}) def postProcessPlanerData(self): if (not self.manuell) and config.plugins.serienRec.planerCacheEnabled.value: cache = self.loadPlanerData(1) self.writePlanerData(1, cache) @staticmethod def writePlanerData(planerType, cache): if not os.path.exists("%stmp/" % SerienRecorder.serienRecMainPath): try: os.makedirs("%stmp/" % SerienRecorder.serienRecMainPath) except: pass if os.path.isdir("%stmp/" % SerienRecorder.serienRecMainPath): try: os.chmod("%stmp/planer_%s" % (SerienRecorder.serienRecMainPath, str(planerType)), 0o666) except: pass f = open("%stmp/planer_%s" % (SerienRecorder.serienRecMainPath, str(planerType)), "wb") try: p = pickle.Pickler(f, 2) p.dump(cache) except: pass f.close() try: os.chmod("%stmp/planer_%s" % (SerienRecorder.serienRecMainPath, str(planerType)), 0o666) except: pass @staticmethod def loadPlanerData(planerType): cache = {} planerFile = "%stmp/planer_%s" % (SerienRecorder.serienRecMainPath, str(planerType)) if fileExists(planerFile): f = open(planerFile, "rb") try: u = pickle.Unpickler(f) cache = u.load() except: pass f.close() try: heute = time.strptime(time.strftime('%d.%m.%Y', datetime.datetime.now().timetuple()), '%d.%m.%Y') l = [] for key in cache: if time.strptime(key, '%d.%m.%Y') < heute: l.append(key) for key in l: del cache[key] except: pass if planerType == 1: serienRecSeriesPlanner.optimizePlanerData(cache) return cache @staticmethod def optimizePlanerData(cache): if time.strftime('%H.%M', datetime.datetime.now().timetuple()) < '01.00': t_jetzt = datetime.datetime.now().timetuple() else: t_jetzt = (datetime.datetime.now() - datetime.timedelta(0, 3600)).timetuple() jetzt = time.strftime('%H.%M', t_jetzt) heute = time.strftime('%d.%m.%Y', t_jetzt) if heute in cache: try: for a in cache[heute][1]: l = [] for b in a: if b[4] < jetzt: l.append(b) else: break for b in l: a.remove(b) except: pass
class serienRecWishlistScreen(serienRecBaseScreen, Screen, HelpableScreen): def __init__(self, session): serienRecBaseScreen.__init__(self, session) Screen.__init__(self, session) HelpableScreen.__init__(self) self.session = session self.picload = ePicLoad() self.database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) self.chooseMenuList_popup = MenuList( [], enableWrapAround=True, content=eListboxPythonMultiContent) self["actions"] = HelpableActionMap( self, "SerienRecorderActions", { "ok": (self.keyOK, "für die ausgewählte Serien neue Einträge hinzufügen"), "cancel": (self.keyCancel, "zurück zur vorherigen Ansicht"), "left": (self.keyLeft, "zur vorherigen Seite blättern"), "right": (self.keyRight, "zur nächsten Seite blättern"), "up": (self.keyUp, "eine Zeile nach oben"), "down": (self.keyDown, "eine Zeile nach unten"), "red": (self.keyRed, "ausgewählten Eintrag löschen"), "green": (self.keyGreen, "alle Änderungen speichern und zurück zur vorherigen Ansicht" ), "yellow": (self.keyYellow, "umschalten Sortierung ein/aus"), "blue": (self.keyBlue, "alle Einträge aus der Liste endgültig löschen"), "menu": (self.recSetup, "Menü für globale Einstellungen öffnen"), "0": (self.readLogFile, "Log-File des letzten Suchlaufs anzeigen"), "3": (self.showProposalDB, "Liste der Serien/Staffel-Starts anzeigen"), "4": (self.serieInfo, "Informationen zur ausgewählten Serie anzeigen"), "6": (self.showConflicts, "Liste der Timer-Konflikte anzeigen"), }, -1) self.helpList[0][2].sort() self["helpActions"] = ActionMap([ "SerienRecorderActions", ], { "displayHelp": self.showHelp, "displayHelp_long": self.showManual, }, 0) self.setupSkin() self.delAdded = False self.wishlist = [] self.wishlist_tmp = [] self.dbData = [] self.modus = "menu_list" self.aSerie = "" self.aStaffel = 0 self.aFromEpisode = 0 self.aToEpisode = 0 self.onLayoutFinish.append(self.readWishlist) self.onClose.append(self.__onClose) self.onLayoutFinish.append(self.setSkinProperties) def callHelpAction(self, *args): HelpableScreen.callHelpAction(self, *args) def setSkinProperties(self): super(self.__class__, self).setSkinProperties() self['text_red'].setText("Eintrag löschen") self['text_green'].setText("Speichern") self['text_ok'].setText("Eintrag anlegen") if config.plugins.serienRec.wishListSorted.value: self['text_yellow'].setText("unsortierte Liste") else: self['text_yellow'].setText("Sortieren") self['text_blue'].setText("Liste leeren") self.num_bt_text[2][1] = buttonText_na super(self.__class__, self).startDisplayTimer() def setupSkin(self): self.skin = None InitSkin(self) # normal self.chooseMenuList = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self.chooseMenuList.l.setFont( 0, gFont('Regular', 20 + int(config.plugins.serienRec.listFontsize.value))) self.chooseMenuList.l.setItemHeight(int(25 * skinFactor)) self['menu_list'] = self.chooseMenuList self['menu_list'].show() # popup self.chooseMenuList_popup = MenuList( [], enableWrapAround=True, content=eListboxPythonMultiContent) self.chooseMenuList_popup.l.setFont( 0, gFont('Regular', 20 + int(config.plugins.serienRec.listFontsize.value))) self.chooseMenuList_popup.l.setItemHeight(int(25 * skinFactor)) self['popup_list'] = self.chooseMenuList_popup self['popup_list'].hide() self['title'].setText("Diese Episoden sind zur Aufnahme vorgemerkt") if config.plugins.serienRec.showCover.value: self['cover'].show() if not config.plugins.serienRec.showAllButtons.value: self['bt_red'].show() self['bt_green'].show() self['bt_ok'].show() self['bt_yellow'].show() self['bt_blue'].show() self['bt_exit'].show() #self['bt_text'].show() self['bt_info'].show() self['bt_menu'].show() self['text_red'].show() self['text_green'].show() self['text_ok'].show() self['text_yellow'].show() self['text_blue'].show() self['text_0'].show() self['text_1'].show() self['text_2'].show() self['text_3'].show() self['text_4'].show() def updateMenuKeys(self): updateMenuKeys(self) def serieInfo(self): if self.modus == "menu_list": check = self['menu_list'].getCurrent() if check is None: return serien_name = self['menu_list'].getCurrent()[0][1] else: check = self['popup_list'].getCurrent() if check is None: return serien_name = self['popup_list'].getCurrent()[0][0] serien_id = None url = self.database.getMarkerURL(serien_name) if url: serien_id = url if serien_id: from SerienRecorderSeriesInfoScreen import serienRecShowInfo self.session.open(serienRecShowInfo, serien_name, serien_id) def setupClose(self, result): super(self.__class__, self).setupClose(result) if result[1]: self.readWishlist() def readWishlist(self): self.wishlist = [] bookmarks = self.database.getBookmarks() for bookmark in bookmarks: (Serie, Staffel, Episode, numberOfRecordings) = bookmark zeile = "%s S%sE%s" % (Serie, str(Staffel).zfill(2), str(Episode).zfill(2)) self.wishlist.append((zeile, Serie, Staffel, Episode)) self.wishlist_tmp = self.wishlist[:] if config.plugins.serienRec.wishListSorted.value: self.wishlist_tmp.sort() self.chooseMenuList.setList(map(self.buildList, self.wishlist_tmp)) self.getCover() @staticmethod def buildList(entry): (zeile, Serie, Staffel, Episode) = entry return [ entry, (eListboxPythonMultiContent.TYPE_TEXT, 20, 00, 1280 * skinFactor, 25 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, zeile) ] @staticmethod def buildList_popup(entry): (Serie, ) = entry return [ entry, (eListboxPythonMultiContent.TYPE_TEXT, 5, 0, 560 * skinFactor, 25 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, Serie) ] def answerStaffel(self, aStaffel): self.aStaffel = aStaffel if self.aStaffel is None or self.aStaffel == "": return self.session.openWithCallback(self.answerFromEpisode, NTIVirtualKeyBoard, title="von Episode:") def answerFromEpisode(self, aFromEpisode): self.aFromEpisode = aFromEpisode if self.aFromEpisode is None or self.aFromEpisode == "": return self.session.openWithCallback(self.answerToEpisode, NTIVirtualKeyBoard, title="bis Episode:") def answerToEpisode(self, aToEpisode): self.aToEpisode = aToEpisode print "[SerienRecorder] Staffel: %s" % self.aStaffel print "[SerienRecorder] von Episode: %s" % self.aFromEpisode print "[SerienRecorder] bis Episode: %s" % self.aToEpisode if self.aToEpisode is None or self.aFromEpisode is None or self.aStaffel is None or self.aToEpisode == "": return else: self.database.addBookmark( self.aSerie, self.aFromEpisode, self.aToEpisode, self.aStaffel, int(config.plugins.serienRec.NoOfRecords.value)) self.readWishlist() def keyOK(self): if self.modus == "menu_list": self.modus = "popup_list" self['popup_list'].show() self['popup_bg'].show() self['menu_list'].hide() l = self.database.getMarkerNames() self.chooseMenuList_popup.setList(map(self.buildList_popup, l)) self['popup_list'].moveToIndex(0) else: self.modus = "menu_list" self['menu_list'].show() self['popup_list'].hide() self['popup_bg'].hide() if self['popup_list'].getCurrent() is None: print "[SerienRecorder] Marker-Liste leer." return self.aSerie = self['popup_list'].getCurrent()[0][0] self.aStaffel = 0 self.aFromEpisode = 0 self.aToEpisode = 0 self.session.openWithCallback(self.answerStaffel, NTIVirtualKeyBoard, title="%s: Staffel eingeben:" % self.aSerie) def keyRed(self): check = self['menu_list'].getCurrent() if check is None: print "[SerienRecorder] Merkzettel ist leer." return else: zeile = self['menu_list'].getCurrent()[0] (title, serie, staffel, episode) = zeile self.dbData.append( (serie.lower(), str(staffel).lower(), episode.lower())) self.wishlist_tmp.remove(zeile) self.wishlist.remove(zeile) self.chooseMenuList.setList(map(self.buildList, self.wishlist_tmp)) self.delAdded = True def keyGreen(self): if self.delAdded: self.database.removeBookmarks(self.dbData) self.close() def keyYellow(self): if len(self.wishlist_tmp) != 0: if config.plugins.serienRec.wishListSorted.value: self.wishlist_tmp = self.wishlist[:] self['text_yellow'].setText("Sortieren") config.plugins.serienRec.wishListSorted.setValue(False) else: self.wishlist_tmp.sort() self['text_yellow'].setText("unsortierte Liste") config.plugins.serienRec.wishListSorted.setValue(True) config.plugins.serienRec.wishListSorted.save() SerienRecorder.configfile.save() self.chooseMenuList.setList(map(self.buildList, self.wishlist_tmp)) self.getCover() def keyBlue(self): check = self['menu_list'].getCurrent() if check is None: print "[SerienRecorder] Merkzettel ist leer." return else: if config.plugins.serienRec.confirmOnDelete.value: self.session.openWithCallback( self.callClearListMsg, MessageBox, "Soll die Liste wirklich geleert werden?", MessageBox.TYPE_YESNO, default=False) else: self.callClearListMsg(True) def callClearListMsg(self, answer): if answer: self.database.removeAllBookmarks() self.readWishlist() else: return def getCover(self): if self.modus == "menu_list": check = self['menu_list'].getCurrent() if check is None: return serien_name = self['menu_list'].getCurrent()[0][1] else: check = self['popup_list'].getCurrent() if check is None: return serien_name = self['popup_list'].getCurrent()[0][0] serien_id = None url = self.database.getMarkerURL(serien_name) if url: serien_id = url SerienRecorder.getCover(self, serien_name, serien_id) def keyLeft(self): self[self.modus].pageUp() self.getCover() def keyRight(self): self[self.modus].pageDown() self.getCover() def keyDown(self): self[self.modus].down() self.getCover() def keyUp(self): self[self.modus].up() self.getCover() def __onClose(self): self.stopDisplayTimer() def callDeleteMsg(self, answer): if answer: self.keyGreen() self.close() def keyCancel(self): if self.delAdded: self.session.openWithCallback( self.callDeleteMsg, MessageBox, "Sollen die Änderungen gespeichert werden?", MessageBox.TYPE_YESNO, default=True) else: self.close()
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
class serienRecMainScreen(serienRecBaseScreen, Screen, HelpableScreen): def __init__(self, session): serienRecBaseScreen.__init__(self, session) Screen.__init__(self, session) HelpableScreen.__init__(self) self.session = session self.picload = ePicLoad() self.picloader = None self.ErrorMsg = "unbekannt" self.skin = None self.chooseMenuList = None self.chooseMenuList_popup = None self.popup_list = [] self.piconLoader = PiconLoader() self.database = None self.singleTimer_conn = None self.displayTimer_conn = None self["actions"] = HelpableActionMap( self, "SerienRecorderActions", { "ok": (self.keyOK, "Marker für die ausgewählte Serie hinzufügen"), "cancel": (self.keyCancel, "SerienRecorder beenden"), "left": (self.keyLeft, "zur vorherigen Seite blättern"), "right": (self.keyRight, "zur nächsten Seite blättern"), "up": (self.keyUp, "eine Zeile nach oben"), "down": (self.keyDown, "eine Zeile nach unten"), "red": (self.keyRed, "Anzeige-Modus auswählen"), "green": (self.keyGreen, "Ansicht Sender-Zuordnung öffnen"), "yellow": (self.keyYellow, "Ansicht Serien-Marker öffnen"), "blue": (self.keyBlue, "Ansicht Timer-Liste öffnen"), "info": (self.keyCheck, "Suchlauf für Timer starten"), "menu": (self.recSetup, "Menü für globale Einstellungen öffnen"), "nextBouquet": (self.nextPage, "Serienplaner des nächsten Tages laden"), "prevBouquet": (self.backPage, "Serienplaner des vorherigen Tages laden"), "startTeletext": (self.wunschliste, "Informationen zur ausgewählten Serie auf Wunschliste anzeigen" ), "0": (self.readLogFile, "Log-File des letzten Suchlaufs anzeigen"), "1": (self.searchSeries, "Serie manuell suchen"), "2": (self.changeTVDBID, "TVDB-ID ändern"), "3": (self.showProposalDB, "Liste der Serien/Staffel-Starts anzeigen"), "4": (self.serieInfo, "Informationen zur ausgewählten Serie anzeigen"), "5": (self.imapTest, "IMAP Test"), "6": (self.showConflicts, "Liste der Timer-Konflikte anzeigen"), "7": (self.showWishlist, "Merkzettel (vorgemerkte Folgen) anzeigen"), "8": (self.reloadSerienplaner, "Serienplaner neu laden"), }, -1) self.helpList[0][2].sort() self["helpActions"] = ActionMap([ "SerienRecorderActions", ], { "displayHelp": self.showHelp, "displayHelp_long": self.showManual, }, 0) SerienRecorder.ReadConfigFile() if not os.path.exists(config.plugins.serienRec.piconPath.value): config.plugins.serienRec.showPicons.value = False self.setupSkin() if config.plugins.serienRec.updateInterval.value == 24: config.plugins.serienRec.timeUpdate.value = True elif config.plugins.serienRec.updateInterval.value == 0: config.plugins.serienRec.timeUpdate.value = False else: config.plugins.serienRec.timeUpdate.value = False global showMainScreen if config.plugins.serienRec.firstscreen.value == "0": showMainScreen = True else: showMainScreen = False self.pRegional = 0 self.pPaytv = 1 self.pPrime = 1 self.page = 0 self.modus = "list" self.loading = True self.daylist = [[]] self.displayTimer = None self.displayMode = 1 self.serviceRefs = None self.onLayoutFinish.append(self.setSkinProperties) self.onClose.append(self.__onClose) self.onFirstExecBegin.append(self.showSplashScreen) self.onFirstExecBegin.append(self.checkForUpdate) if config.plugins.serienRec.showStartupInfoText.value: if fileExists("%sStartupInfoText" % SerienRecorder.serienRecMainPath): self.onFirstExecBegin.append(self.showInfoText) else: self.onFirstExecBegin.append(self.startScreen) else: self.onFirstExecBegin.append(self.startScreen) def imapTest(self): from SerienRecorderTVPlaner import imaptest imaptest(self.session) def showInfoText(self): from SerienRecorderStartupInfoScreen import ShowStartupInfo self.session.openWithCallback(self.startScreen, ShowStartupInfo) def showSplashScreen(self): from SerienRecorderSplashScreen import ShowSplashScreen self.session.openWithCallback( self.checkForUpdate, ShowSplashScreen, config.plugins.serienRec.showversion.value) def checkForUpdate(self): if config.plugins.serienRec.Autoupdate.value: from SerienRecorderUpdateScreen import checkGitHubUpdate checkGitHubUpdate(self.session).checkForUpdate() self.startScreen() def callHelpAction(self, *args): HelpableScreen.callHelpAction(self, *args) def setSkinProperties(self): super(self.__class__, self).setSkinProperties() self['text_red'].setText("Anzeige-Modus") self['text_green'].setText("Sender zuordnen") self['text_ok'].setText("Marker hinzufügen") self['text_yellow'].setText("Serien Marker") self['text_blue'].setText("Timer-Liste") self.num_bt_text[0][1] = "IMAP-Test" self.num_bt_text[1][0] = "Serie suchen" self.num_bt_text[2][0] = "TVDB-ID ändern" self.num_bt_text[2][2] = "Timer suchen" self.num_bt_text[3][1] = "Neu laden" super(self.__class__, self).startDisplayTimer() def setupSkin(self): self.skin = None InitSkin(self) self.chooseMenuList = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self.chooseMenuList.l.setFont( 0, gFont('Regular', 20 + int(config.plugins.serienRec.listFontsize.value))) self.chooseMenuList.l.setItemHeight(int(50 * skinFactor)) self['menu_list'] = self.chooseMenuList self['menu_list'].show() # popup self.chooseMenuList_popup = MenuList( [], enableWrapAround=True, content=eListboxPythonMultiContent) self.chooseMenuList_popup.l.setFont( 0, gFont('Regular', 20 + int(config.plugins.serienRec.listFontsize.value))) self.chooseMenuList_popup.l.setItemHeight(int(30 * skinFactor)) self['popup_list'] = self.chooseMenuList_popup self['popup_list'].hide() self['title'].setText("Lade infos from Web...") if config.plugins.serienRec.showCover.value: self['cover'].show() if not config.plugins.serienRec.showAllButtons.value: self['bt_red'].show() self['bt_green'].show() self['bt_ok'].show() self['bt_yellow'].show() self['bt_blue'].show() self['bt_exit'].show() self['bt_text'].show() self['bt_epg'].show() self['bt_info'].show() self['bt_menu'].show() self['text_red'].show() self['text_green'].show() self['text_ok'].show() self['text_yellow'].show() self['text_blue'].show() self['text_0'].show() self['text_1'].show() self['text_2'].show() self['text_3'].show() self['text_4'].show() def updateMenuKeys(self): updateMenuKeys(self) def test(self): i = 0 def changeTVDBID(self): from SerienRecorderScreenHelpers import EditTVDBID (serien_name, serien_id) = self.getSeriesNameID() editTVDBID = EditTVDBID(self, self.session, serien_name, serien_id) editTVDBID.changeTVDBID() def reloadSerienplaner(self): # lt = datetime.datetime.now() # lt += datetime.timedelta(days=self.page) # key = time.strftime('%d.%m.%Y', lt.timetuple()) # cache = serienRecMainScreen.loadPlanerData(config.plugins.serienRec.screenplaner.value) # if key in cache: # del cache[key] self.readPlanerData(True) def readLogFile(self): from SerienRecorderLogScreen import serienRecReadLog self.session.open(serienRecReadLog) def showProposalDB(self): from SerienRecorderSeasonBeginsScreen import serienRecShowSeasonBegins self.session.openWithCallback(self.readPlanerData, serienRecShowSeasonBegins) def searchSeries(self): if self.modus == "list": self.session.openWithCallback(self.wSearch, NTIVirtualKeyBoard, title="Serien Titel eingeben:") def wSearch(self, serien_name): if serien_name: from SerienRecorderSearchResultScreen import serienRecSearchResultScreen self.session.openWithCallback(self.handleSeriesSearchEnd, serienRecSearchResultScreen, serien_name) def handleSeriesSearchEnd(self, serien_name=None): if serien_name: from SerienRecorderMarkerScreen import serienRecMarker self.session.openWithCallback(self.readPlanerData, serienRecMarker, serien_name) else: self.readPlanerData(False) def serieInfo(self): if self.loading: return check = self['menu_list'].getCurrent() if check is None: return (serien_name, serien_id) = self.getSeriesNameID() from SerienRecorderSeriesInfoScreen import serienRecShowInfo self.session.open(serienRecShowInfo, serien_name, serien_id) def wunschliste(self): (serien_name, serien_id) = self.getSeriesNameID() super(self.__class__, self).wunschliste(serien_id) def setHeadline(self): if int(config.plugins.serienRec.screenplaner.value) == 1: self['headline'].setText("Serien-Planer (Serien Tagesübersicht)") self['text_red'].setText("Top 30") elif int(config.plugins.serienRec.screenplaner.value) == 2: self['headline'].setText("Top 30 SerienRecorder Serien") self['text_red'].setText("Tagesübersicht") self['headline'].instance.setForegroundColor(parseColor("red")) def recSetup(self): from SerienRecorderSetupScreen import serienRecSetup self.session.openWithCallback(self.setupClose, serienRecSetup) def setupClose(self, result): super(self.__class__, self).setupClose(result) if result[1]: self.readPlanerData() 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 handleChannelListUpdate(self, showChannelEdit=False): if showChannelEdit: from SerienRecorderChannelScreen import serienRecMainChannelEdit self.session.openWithCallback(self.switchStartScreen, serienRecMainChannelEdit) else: self.switchStartScreen() def switchStartScreen(self, unused=None): if not showMainScreen: from SerienRecorderMarkerScreen import serienRecMarker self.session.openWithCallback(self.readPlanerData, serienRecMarker) else: self.readPlanerData(False) 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 processPlanerData(self, data, useCache=False): if not data or len(data) == 0: self['title'].setText("Fehler beim Abrufen der SerienPlaner-Daten") return if useCache: (headDate, self.daylist) = data else: self.daylist = [[]] headDate = [data["date"]] markers = self.database.getAllMarkerStatusForBoxID( config.plugins.serienRec.BoxID.value) timers = self.database.getTimer(self.page) for event in data["events"]: aufnahme = False serieAdded = 0 start_h = event["time"][:+2] start_m = event["time"][+3:] start_time = TimeHelpers.getUnixTimeWithDayOffset( start_h, start_m, self.page) serien_name = event["name"].encode("utf-8") serien_name_lower = serien_name.lower() serien_id = int(event["id"]) sender = event["channel"] title = event["title"].encode("utf-8") staffel = event["season"] episode = event["episode"] self.ErrorMsg = "%s - S%sE%s - %s (%s)" % \ (serien_name, str(staffel).zfill(2), str(episode).zfill(2), title, sender) serienTimers = [ timer for timer in timers if timer[0] == serien_name_lower ] serienTimersOnChannel = [ serienTimer for serienTimer in serienTimers if serienTimer[2] == sender.lower() ] for serienTimerOnChannel in serienTimersOnChannel: if (int(serienTimerOnChannel[1]) >= (int(start_time) - 300)) and (int( serienTimerOnChannel[1]) < (int(start_time) + 300)): aufnahme = True # 0 = no marker, 1 = active marker, 2 = deactive marker if serien_id in markers: serieAdded = 1 if markers[serien_id] else 2 staffel = str(staffel).zfill(2) episode = str(episode).zfill(2) ############################## # # CHECK # # ueberprueft anhand des Seriennamen, Season, Episode ob die serie bereits auf der HDD existiert # seasonEpisodeString = "S%sE%s" % (str(staffel).zfill(2), str(episode).zfill(2)) bereits_vorhanden = False if config.plugins.serienRec.sucheAufnahme.value: (dirname, dirname_serie) = getDirname(self.database, serien_name, staffel) if str(episode).isdigit(): if int(episode) == 0: bereits_vorhanden = STBHelpers.countEpisodeOnHDD( dirname, seasonEpisodeString, serien_name, False, title) > 0 and True or False else: bereits_vorhanden = STBHelpers.countEpisodeOnHDD( dirname, seasonEpisodeString, serien_name, False) > 0 and True or False else: bereits_vorhanden = STBHelpers.countEpisodeOnHDD( dirname, seasonEpisodeString, serien_name, False) > 0 and True or False title = "%s - %s" % (seasonEpisodeString, title) regional = False paytv = False neu = event["new"] prime = False transmissionTime = event["time"] url = '' self.daylist[0].append( (regional, paytv, neu, prime, transmissionTime, url, serien_name, sender, staffel, episode, title, aufnahme, serieAdded, bereits_vorhanden, serien_id)) print "[SerienRecorder] Es wurden %s Serie(n) gefunden" % len( self.daylist[0]) if headDate: d = headDate[0].split(',') d.reverse() key = d[0].strip() cache = serienRecSeriesPlanner.loadPlanerData(1) cache.update({key: (headDate, self.daylist)}) if config.plugins.serienRec.planerCacheEnabled.value: serienRecSeriesPlanner.writePlanerData(1, cache) self.loading = False if len(self.daylist[0]) != 0: if headDate: self['title'].setText( "Es wurden für - %s - %s Serie(n) gefunden." % (headDate[0], len(self.daylist[0]))) self['title'].instance.setForegroundColor( parseColor("foreground")) else: self['title'].setText( "Es wurden für heute %s Serie(n) gefunden." % len(self.daylist[0])) self['title'].instance.setForegroundColor( parseColor("foreground")) self.chooseMenuList.setList( map(self.buildPlanerList, self.daylist[0])) self.ErrorMsg = "'getCover()'" self.getCover() else: if int(self.page) < 1 and not int(self.page) == 0: self.page -= 1 self['title'].setText("Es wurden für heute %s Serie(n) gefunden." % len(self.daylist[0])) self['title'].instance.setForegroundColor(parseColor("foreground")) print "[SerienRecorder] Wunschliste Serien-Planer -> LISTE IST LEER !!!!" self.chooseMenuList.setList( map(self.buildPlanerList, self.daylist[0])) def processTopThirty(self, data, useCache=False): if not data or len(data) == 0: self['title'].setText("Fehler beim Abrufen der SerienPlaner-Daten") return if useCache: (headDate, self.daylist) = data else: self.daylist = [[]] headDate = [data["date"]] markers = self.database.getAllMarkerStatusForBoxID( config.plugins.serienRec.BoxID.value) rank = 0 for serie in data["series"]: serien_name = serie["name"].encode("utf-8") serien_id = int(serie["id"]) average = serie["average"] # 0 = no marker, 1 = active marker, 2 = deactive marker serieAdded = 0 if serien_id in markers: serieAdded = 1 if markers[serien_id] else 2 rank += 1 self.daylist[0].append( (serien_name, average, serien_id, serieAdded, rank)) if headDate: d = headDate[0].split(',') d.reverse() key = d[0].strip() cache = serienRecSeriesPlanner.loadPlanerData(2) cache.update({key: (headDate, self.daylist)}) if config.plugins.serienRec.planerCacheEnabled.value: serienRecSeriesPlanner.writePlanerData(2, cache) self.loading = False self['title'].setText("") self.chooseMenuList.setList( map(self.buildTopThirtyList, self.daylist[0])) self.ErrorMsg = "'getCover()'" self.getCover() def buildPlanerList(self, entry): (regional, paytv, neu, prime, transmissionTime, url, serien_name, sender, staffel, episode, title, aufnahme, serieAdded, bereits_vorhanden, serien_id) = entry imageNone = "%simages/black.png" % SerienRecorder.serienRecMainPath imageNeu = "%simages/neu.png" % SerienRecorder.serienRecMainPath imageTimer = "%simages/timer.png" % SerienRecorder.serienRecMainPath imageHDD = "%simages/hdd_icon.png" % SerienRecorder.serienRecMainPath if serieAdded == 1: seriesColor = parseColor('green').argb() elif serieAdded == 2: seriesColor = parseColor('red').argb() else: seriesColor = None if aufnahme: seriesColor = parseColor('blue').argb() titleColor = timeColor = parseColor('foreground').argb() if int(neu) == 0: imageNeu = imageNone if bereits_vorhanden: imageHDDTimer = imageHDD elif aufnahme: imageHDDTimer = imageTimer else: imageHDDTimer = imageNone if config.plugins.serienRec.showPicons.value != "0": picon = loadPNG(imageNone) if sender and self.serviceRefs.get(sender): # Get picon by reference or name piconPath = self.piconLoader.getPicon( self.serviceRefs.get(sender)[0] if config.plugins. serienRec.showPicons.value == "1" else self.serviceRefs.get(sender)[1]) if piconPath: self.picloader = PicLoader(80 * skinFactor, 40 * skinFactor) picon = self.picloader.load(piconPath) self.picloader.destroy() return [ entry, (eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 5, 5 * skinFactor, 80 * skinFactor, 40 * skinFactor, picon), (eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 330 * skinFactor, 7 * skinFactor, 30 * skinFactor, 22 * skinFactor, loadPNG(imageNeu)), (eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 330 * skinFactor, 30 * skinFactor, 30 * skinFactor, 22 * skinFactor, loadPNG(imageHDDTimer)), (eListboxPythonMultiContent.TYPE_TEXT, 100 * skinFactor, 3, 200 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, sender), (eListboxPythonMultiContent.TYPE_TEXT, 100 * skinFactor, 29 * skinFactor, 150 * skinFactor, 18 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, transmissionTime, timeColor, timeColor), (eListboxPythonMultiContent.TYPE_TEXT, 365 * skinFactor, 3, 500 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, serien_name, seriesColor, seriesColor), (eListboxPythonMultiContent.TYPE_TEXT, 365 * skinFactor, 29 * skinFactor, 500 * skinFactor, 18 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, title, titleColor, titleColor) ] else: return [ entry, (eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 5, 7, 30 * skinFactor, 22 * skinFactor, loadPNG(imageNeu)), (eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 5, 30 * skinFactor, 30 * skinFactor, 22 * skinFactor, loadPNG(imageHDDTimer)), (eListboxPythonMultiContent.TYPE_TEXT, 40 * skinFactor, 3, 280 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, sender), (eListboxPythonMultiContent.TYPE_TEXT, 40 * skinFactor, 29 * skinFactor, 150 * skinFactor, 18 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, transmissionTime, timeColor, timeColor), (eListboxPythonMultiContent.TYPE_TEXT, 340 * skinFactor, 3, 520 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, serien_name, seriesColor, seriesColor), (eListboxPythonMultiContent.TYPE_TEXT, 340 * skinFactor, 29 * skinFactor, 520 * skinFactor, 18 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, title, titleColor, titleColor) ] @staticmethod def buildTopThirtyList(entry): (serien_name, average, serien_id, serieAdded, rank) = entry if serieAdded == 1: seriesColor = parseColor('green').argb() elif serieAdded == 2: seriesColor = parseColor('red').argb() else: seriesColor = None title = "%d Abrufe/Tag" % average titleColor = parseColor('foreground').argb() rank = "%d." % rank return [ entry, (eListboxPythonMultiContent.TYPE_TEXT, 5 * skinFactor, 3, 40 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_RIGHT | RT_VALIGN_CENTER, rank, titleColor, titleColor), (eListboxPythonMultiContent.TYPE_TEXT, 70 * skinFactor, 3, 520 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, serien_name, seriesColor, seriesColor), (eListboxPythonMultiContent.TYPE_TEXT, 70 * skinFactor, 29 * skinFactor, 520 * skinFactor, 18 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, title, titleColor, titleColor) ] 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 getCover(self): if self.loading: return check = self['menu_list'].getCurrent() if check is None: return (serien_name, serien_id) = self.getSeriesNameID() self.ErrorMsg = "'getCover()'" SerienRecorder.getCover(self, serien_name, serien_id) def keyRed(self): if self.modus == "list": if config.plugins.serienRec.screenplaner.value == 1: config.plugins.serienRec.screenplaner.value = 2 else: config.plugins.serienRec.screenplaner.value = 1 config.plugins.serienRec.screenplaner.save() SerienRecorder.configfile.save() self.readPlanerData(False) def getSeriesNameID(self): if config.plugins.serienRec.screenplaner.value == 1: serien_name = self['menu_list'].getCurrent()[0][6] serien_id = self['menu_list'].getCurrent()[0][14] else: serien_name = self['menu_list'].getCurrent()[0][0] serien_id = self['menu_list'].getCurrent()[0][2] return serien_name, serien_id def keyGreen(self): from SerienRecorderChannelScreen import serienRecMainChannelEdit self.session.openWithCallback(self.readPlanerData, serienRecMainChannelEdit) def keyYellow(self): from SerienRecorderMarkerScreen import serienRecMarker self.session.openWithCallback(self.readPlanerData, serienRecMarker) def keyBlue(self): from SerienRecorderTimerListScreen import serienRecTimerListScreen self.session.openWithCallback(self.readPlanerData, serienRecTimerListScreen) def keyCheck(self): if config.plugins.serienRec.tvplaner.value: self.session.openWithCallback( self.executeAutoCheck, MessageBox, "Bei 'ja' wird der Suchlauf für TV-Planer Timer gestartet, bei 'nein' wird ein voller Suchlauf durchgeführt.", MessageBox.TYPE_YESNO) else: self.executeAutoCheck(False) def executeAutoCheck(self, withTVPlaner): from SerienRecorderAutoCheckScreen import serienRecRunAutoCheckScreen self.session.openWithCallback(self.readPlanerData, serienRecRunAutoCheckScreen, withTVPlaner) def keyLeft(self): if self.modus == "list": self['menu_list'].pageUp() self.getCover() def keyRight(self): if self.modus == "list": self['menu_list'].pageDown() self.getCover() def keyDown(self): if self.modus == "list": self['menu_list'].down() self.getCover() def keyUp(self): if self.modus == "list": self['menu_list'].up() self.getCover() def nextPage(self): if config.plugins.serienRec.screenplaner.value == 1 and self.page < 4: self.page += 1 self.chooseMenuList.setList(map(self.buildPlanerList, [])) self.readPlanerData(False) def backPage(self): if config.plugins.serienRec.screenplaner.value == 1 and not self.page < 1: self.page -= 1 self.chooseMenuList.setList(map(self.buildPlanerList, [])) self.readPlanerData(False) def __onClose(self): self.stopDisplayTimer() def keyCancel(self): if self.modus == "list": self.stopDisplayTimer() self.close()
def getMarkerCover(self): self.database = SRDatabase(serienRecDataBaseFilePath) markers = self.database.getAllMarkers(False) for marker in markers: (ID, Serie, Info, Url, AufnahmeVerzeichnis, AlleStaffelnAb, alleSender, Vorlaufzeit, Nachlaufzeit, AnzahlAufnahmen, preferredChannel, useAlternativeChannel, AbEpisode, TimerForSpecials, ErlaubteSTB, ErlaubteStaffelCount) = marker getCover(None, Serie, ID, True)
class serienRecMainChannelEdit(serienRecBaseScreen, Screen, HelpableScreen): def __init__(self, session): serienRecBaseScreen.__init__(self, session) Screen.__init__(self, session) HelpableScreen.__init__(self) self.session = session self.serienRecChannelList = [] self.stbChannelList = [] self.selected_sender = None self.skin = None self.displayMode = 2 self.chooseMenuList = None self.chooseMenuList_popup = None self.chooseMenuList_popup2 = None from SerienRecorder import serienRecDataBaseFilePath from SerienRecorderDatabase import SRDatabase self.database = SRDatabase(serienRecDataBaseFilePath) from difflib import SequenceMatcher self.sequenceMatcher = SequenceMatcher(" ".__eq__, "", "") self["actions"] = HelpableActionMap( self, "SerienRecorderActions", { "ok": (self.keyOK, "Popup-Fenster zur Auswahl des STB-Sender öffnen"), "cancel": (self.keyCancel, "zurück zur Serienplaner-Ansicht"), "red": (self.keyRed, "umschalten ausgewählter Sender für Timererstellung aktiviert/deaktiviert" ), "red_long": (self.keyRedLong, "ausgewählten Sender aus der Channelliste endgültig löschen"), "green": (self.keyGreen, "Sender-Zuordnung aktualisieren"), "blue": (self.keyBlue, "Automatische Sender-Zuordnung"), "menu": (self.channelSetup, "Menü für Sender-Einstellungen öffnen"), "menu_long": (self.recSetup, "Menü für globale Einstellungen öffnen"), "left": (self.keyLeft, "zur vorherigen Seite blättern"), "right": (self.keyRight, "zur nächsten Seite blättern"), "up": (self.keyUp, "eine Zeile nach oben"), "down": (self.keyDown, "eine Zeile nach unten"), "0": (self.readLogFile, "Log-File des letzten Suchlaufs anzeigen"), "3": (self.showProposalDB, "Liste der Serien/Staffel-Starts anzeigen"), "6": (self.showConflicts, "Liste der Timer-Konflikte anzeigen"), "7": (self.showWishlist, "Merkzettel (vorgemerkte Folgen) anzeigen"), "8": (self.checkChannels, "Sender prüfen"), "9": (self.resetChannelList, "Alle Zuordnungen löschen"), }, -1) self.helpList[0][2].sort() self["helpActions"] = ActionMap([ "SerienRecorderActions", ], { "displayHelp": self.showHelp, "displayHelp_long": self.showManual, }, 0) self.setupSkin() self.modus = "list" self.changesMade = False self.timer_default = eTimer() if isDreamOS(): self.timer_default_conn = self.timer_default.timeout.connect( self.showChannels) else: self.timer_default.callback.append(self.showChannels) self.onLayoutFinish.append(self.__onLayoutFinished) self.onClose.append(self.__onClose) self.onLayoutFinish.append(self.setSkinProperties) def callHelpAction(self, *args): HelpableScreen.callHelpAction(self, *args) def setSkinProperties(self): super(self.__class__, self).setSkinProperties() self['text_green'].setText("Aktualisieren") self['text_ok'].setText("Sender auswählen") self.num_bt_text[3][1] = "Sender prüfen" self.num_bt_text[4][1] = "Alle löschen" if longButtonText: self.num_bt_text[4][0] = "" self['text_red'].setText("An/Aus (lang: Löschen)") self.num_bt_text[4][2] = "Setup Sender (lang: global)" else: self.num_bt_text[4][0] = buttonText_na self['text_red'].setText("(De)aktivieren/Löschen") self.num_bt_text[4][2] = "Setup Sender/global" self['text_blue'].setText("Auto-Zuordnung") self.num_bt_text[2][2] = buttonText_na self.num_bt_text[3][2] = buttonText_na super(self.__class__, self).startDisplayTimer() def setupSkin(self): self.skin = None InitSkin(self) # normal self.chooseMenuList = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self.chooseMenuList.l.setFont( 0, gFont('Regular', 20 + int(config.plugins.serienRec.listFontsize.value))) self.chooseMenuList.l.setItemHeight(int(25 * skinFactor)) self['list'] = self.chooseMenuList self['list'].show() # popup self.chooseMenuList_popup = MenuList( [], enableWrapAround=True, content=eListboxPythonMultiContent) self.chooseMenuList_popup.l.setFont( 0, gFont('Regular', 20 + int(config.plugins.serienRec.listFontsize.value))) self.chooseMenuList_popup.l.setItemHeight(int(25 * skinFactor)) self['popup_list'] = self.chooseMenuList_popup self['popup_list'].hide() # popup2 self.chooseMenuList_popup2 = MenuList( [], enableWrapAround=True, content=eListboxPythonMultiContent) self.chooseMenuList_popup2.l.setFont( 0, gFont('Regular', 20 + int(config.plugins.serienRec.listFontsize.value))) self.chooseMenuList_popup2.l.setItemHeight(int(25 * skinFactor)) self['popup_list2'] = self.chooseMenuList_popup2 self['popup_list2'].hide() self['title'].setText("Lade Wunschliste-Sender...") self['Web_Channel'].setText("Wunschliste") self['STB_Channel'].setText("STB-Sender") self['alt_STB_Channel'].setText("alt. STB-Sender") self['Web_Channel'].show() self['STB_Channel'].show() self['alt_STB_Channel'].show() self['separator'].show() if not config.plugins.serienRec.showAllButtons.value: self['bt_red'].show() self['bt_green'].show() self['bt_blue'].show() self['bt_ok'].show() self['bt_exit'].show() #self['bt_text'].show() self['bt_epg'].hide() self['bt_info'].show() self['bt_menu'].show() self['text_red'].show() self['text_green'].show() self['text_blue'].show() self['text_ok'].show() self['text_0'].show() self['text_1'].show() self['text_2'].show() self['text_3'].show() self['text_4'].show() def updateMenuKeys(self): updateMenuKeys(self) def channelSetup(self): webSender = self['list'].getCurrent()[0][0] self.session.open(serienRecChannelSetup, webSender) def setupClose(self, result): super(self.__class__, self).setupClose(result) if result[1]: self.showChannels() def __onLayoutFinished(self): self['title'].setText("Lade Wunschliste-Sender...") self.timer_default.start(0) 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 showChannels(self): self.timer_default.stop() self.serienRecChannelList = [] channels = self.database.getChannels(True) for channel in channels: (webSender, servicename, serviceref, altservicename, altserviceref, status) = channel self.serienRecChannelList.append( (webSender, servicename, altservicename, status)) if len(self.serienRecChannelList) != 0: self['title'].setText("Sender zuordnen") self.chooseMenuList.setList( map(self.buildList, self.serienRecChannelList)) else: self.channelReset(True) def readWebChannels(self): print "[SerienRecorder] call webpage." self['title'].setText("Lade Wunschliste-Sender...") try: self.createWebChannels(SeriesServer().doGetWebChannels(), False) except: self['title'].setText("Fehler beim Laden der Wunschliste-Sender") 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") @staticmethod def getMissingWebChannels(webChannels, dbChannels): added = [] removed = [] dbWebChannels = [x[0] for x in dbChannels] # append missing (new) channels for webChannel in webChannels: if webChannel not in [ dbWebChannel for dbWebChannel in dbWebChannels ]: added.append(webChannel.encode('utf-8')) # append removed channels for dbWebChannel in dbWebChannels: if dbWebChannel not in [webChannel for webChannel in webChannels]: removed.append(dbWebChannel) return added, removed @staticmethod def getUnassignedWebChannels(dbChannels): result = [] #append unassigned for x in dbChannels: if not x[1]: result.append(x[0]) return result def findWebChannelInSTBChannels(self, webChannel): result = (None, None) channelFound = False # First try to find the HD version webChannelHD = webChannel + " HD" for servicename, serviceref in self.stbChannelList: self.sequenceMatcher.set_seqs(webChannelHD.lower(), servicename.lower()) ratio = self.sequenceMatcher.ratio() if ratio >= 0.98: result = (servicename, serviceref) channelFound = True break if not channelFound: for servicename, serviceref in self.stbChannelList: self.sequenceMatcher.set_seqs(webChannel.lower(), servicename.lower()) ratio = self.sequenceMatcher.ratio() if ratio >= 0.98: result = (servicename, serviceref) break return result @staticmethod def buildList(entry): from SerienRecorder import serienRecMainPath (webSender, stbSender, altstbSender, status) = entry if int(status) == 0: imageStatus = "%simages/minus.png" % serienRecMainPath else: imageStatus = "%simages/plus.png" % serienRecMainPath return [ entry, (eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 10, 7 * skinFactor, 16 * skinFactor, 16 * skinFactor, loadPNG(imageStatus)), (eListboxPythonMultiContent.TYPE_TEXT, 40 * skinFactor, 0, 300 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, webSender), (eListboxPythonMultiContent.TYPE_TEXT, 350 * skinFactor, 0, 250 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, stbSender), (eListboxPythonMultiContent.TYPE_TEXT, 600 * skinFactor, 0, 250 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, altstbSender, parseColor('yellow').argb()) ] @staticmethod def buildList_popup(entry): (servicename, serviceref) = entry return [ entry, (eListboxPythonMultiContent.TYPE_TEXT, 5, 1, 250 * skinFactor, 25 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, servicename) ] def keyOK(self): if self['list'].getCurrent() is None: print "[SerienRecorder] Sender-Liste leer." return if self.modus == "list": self.modus = "popup_list" self['popup_list'].show() self['popup_bg'].show() if config.plugins.serienRec.selectBouquets.value: self.stbChannelList = STBHelpers.buildSTBChannelList( config.plugins.serienRec.MainBouquet.value) else: self.stbChannelList = STBHelpers.buildSTBChannelList() self.stbChannelList.insert(0, ("", "")) self.chooseMenuList_popup.setList( map(self.buildList_popup, self.stbChannelList)) idx = 0 (stbChannel, altstbChannel) = self.database.getSTBChannel( self['list'].getCurrent()[0][0]) if stbChannel: try: idx = zip(*self.stbChannelList)[0].index(stbChannel) except: pass self['popup_list'].moveToIndex(idx) self['title'].setText("Standard STB-Sender für %s:" % self['list'].getCurrent()[0][0]) elif config.plugins.serienRec.selectBouquets.value: if self.modus == "popup_list": self.modus = "popup_list2" self['popup_list'].hide() self['popup_list2'].show() self['popup_bg'].show() self.stbChannelList = STBHelpers.buildSTBChannelList( config.plugins.serienRec.AlternativeBouquet.value) self.stbChannelList.insert(0, ("", "")) self.chooseMenuList_popup2.setList( map(self.buildList_popup, self.stbChannelList)) idx = 0 (stbChannel, altstbChannel) = self.database.getSTBChannel( self['list'].getCurrent()[0][0]) if stbChannel: try: idx = zip(*self.stbChannelList)[0].index(altstbChannel) except: pass self['popup_list2'].moveToIndex(idx) self['title'].setText("alternativer STB-Sender für %s:" % self['list'].getCurrent()[0][0]) else: self.modus = "list" self['popup_list'].hide() self['popup_list2'].hide() self['popup_bg'].hide() check = self['list'].getCurrent() if check is None: print "[SerienRecorder] Sender-Liste leer (list)." return check = self['popup_list'].getCurrent() if check is None: print "[SerienRecorder] Sender-Liste leer (popup_list)." return chlistSender = self['list'].getCurrent()[0][0] stbSender = self['popup_list'].getCurrent()[0][0] stbRef = self['popup_list'].getCurrent()[0][1] altstbSender = self['popup_list2'].getCurrent()[0][0] altstbRef = self['popup_list2'].getCurrent()[0][1] print "[SerienRecorder] select:", chlistSender, stbSender, stbRef, altstbSender, altstbRef channels = [] if stbSender != "" or altstbSender != "": channels.append( (stbSender, stbRef, altstbSender, altstbRef, 1, chlistSender.lower())) else: channels.append( (stbSender, stbRef, altstbSender, altstbRef, 0, chlistSender.lower())) self.database.updateChannels(channels, True) self.changesMade = True self['title'].setText("Sender zuordnen") self.showChannels() else: self.modus = "list" self['popup_list'].hide() self['popup_list2'].hide() self['popup_bg'].hide() if self['list'].getCurrent() is None: print "[SerienRecorder] Sender-Liste leer (list)." return if self['popup_list'].getCurrent() is None: print "[SerienRecorder] Sender-Liste leer (popup_list)." return chlistSender = self['list'].getCurrent()[0][0] stbSender = self['popup_list'].getCurrent()[0][0] stbRef = self['popup_list'].getCurrent()[0][1] print "[SerienRecorder] select:", chlistSender, stbSender, stbRef channels = [] if stbSender != "": channels.append((stbSender, stbRef, 1, chlistSender.lower())) else: channels.append((stbSender, stbRef, 0, chlistSender.lower())) self.database.updateChannels(channels) self.changesMade = True self['title'].setText("Sender zuordnen") self.showChannels() def keyRed(self): if self['list'].getCurrent() is None: print "[SerienRecorder] Sender-Liste leer." return if self.modus == "list": chlistSender = self['list'].getCurrent()[0][0] sender_status = self['list'].getCurrent()[0][2] print sender_status self.database.changeChannelStatus(chlistSender) self['title'].instance.setForegroundColor(parseColor("red")) self['title'].setText("") self['title'].setText("Sender '- %s -' wurde geändert." % chlistSender) self.changesMade = True self['title'].instance.setForegroundColor(parseColor("foreground")) self.showChannels() def keyGreen(self): self.session.openWithCallback(self.channelReset, MessageBox, "Senderliste aktualisieren?", MessageBox.TYPE_YESNO) 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 keyBlue(self): self.session.openWithCallback( self.autoMatch, MessageBox, "Es wird versucht, für alle nicht zugeordneten Wunschliste-Sender, einen passenden STB-Sender zu finden, dabei werden zunächst HD Sender bevorzugt.\n\nDies kann, je nach Umfang der Senderliste, einige Zeit (u.U. einige Minuten) dauern - bitte haben Sie Geduld!\n\nAutomatische Zuordnung jetzt durchführen?", MessageBox.TYPE_YESNO) def autoMatch(self, execute): if execute: if config.plugins.serienRec.selectBouquets.value: self.stbChannelList = STBHelpers.buildSTBChannelList( config.plugins.serienRec.MainBouquet.value) else: self.stbChannelList = STBHelpers.buildSTBChannelList() self['title'].setText("Versuche automatische Zuordnung...") try: self.createWebChannels(SeriesServer().doGetWebChannels(), True) except: self['title'].setText( "Fehler beim Laden der Wunschliste-Sender") def keyRedLong(self): check = self['list'].getCurrent() if check is None: print "[SerienRecorder] Serien Marker leer." return else: self.selected_sender = self['list'].getCurrent()[0][0] if config.plugins.serienRec.confirmOnDelete.value: self.session.openWithCallback( self.channelDelete, MessageBox, "Soll '%s' wirklich entfernt werden?" % self.selected_sender, MessageBox.TYPE_YESNO, default=False) else: self.channelDelete(True) def channelDelete(self, answer): if not answer: return self.database.removeChannel(self.selected_sender) self.changesMade = True self['title'].instance.setForegroundColor(parseColor("red")) self['title'].setText("Sender '- %s -' entfernt." % self.selected_sender) self.showChannels() def resetChannelList(self): if config.plugins.serienRec.confirmOnDelete.value: self.session.openWithCallback( self.channelDeleteAll, MessageBox, "Sollen wirklich alle Senderzuordnungen entfernt werden?", MessageBox.TYPE_YESNO, default=False) else: self.channelDeleteAll(True) def channelDeleteAll(self, answer): if not answer: return self.database.removeAllChannels() self.changesMade = True self['title'].instance.setForegroundColor(parseColor("red")) self['title'].setText("Alle Senderzuordnungen entfernt.") self.showChannels() def keyLeft(self): self[self.modus].pageUp() def keyRight(self): self[self.modus].pageDown() def keyDown(self): self[self.modus].down() def keyUp(self): self[self.modus].up() def __onClose(self): self.stopDisplayTimer() def keyCancel(self): if self.modus == "popup_list": self.modus = "list" self['popup_list'].hide() self['popup_bg'].hide() elif self.modus == "popup_list2": self.modus = "list" self['popup_list2'].hide() self['popup_bg'].hide() else: if config.plugins.serienRec.refreshViews.value: self.close(self.changesMade) else: self.close(False)
class serienRecWishlistScreen(serienRecBaseScreen, Screen, HelpableScreen): def __init__(self, session): serienRecBaseScreen.__init__(self, session) Screen.__init__(self, session) HelpableScreen.__init__(self) self.session = session self.picload = ePicLoad() self.database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) self.chooseMenuList_popup = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self["actions"] = HelpableActionMap(self, "SerienRecorderActions", { "ok" : (self.keyOK, "für die ausgewählte Serien neue Einträge hinzufügen"), "cancel": (self.keyCancel, "zurück zur vorherigen Ansicht"), "left" : (self.keyLeft, "zur vorherigen Seite blättern"), "right" : (self.keyRight, "zur nächsten Seite blättern"), "up" : (self.keyUp, "eine Zeile nach oben"), "down" : (self.keyDown, "eine Zeile nach unten"), "red" : (self.keyRed, "ausgewählten Eintrag löschen"), "green" : (self.keyGreen, "alle Änderungen speichern und zurück zur vorherigen Ansicht"), "yellow": (self.keyYellow, "umschalten Sortierung ein/aus"), "blue" : (self.keyBlue, "alle Einträge aus der Liste endgültig löschen"), "menu" : (self.recSetup, "Menü für globale Einstellungen öffnen"), "0" : (self.readLogFile, "Log-File des letzten Suchlaufs anzeigen"), "3" : (self.showProposalDB, "Liste der Serien/Staffel-Starts anzeigen"), "4" : (self.serieInfo, "Informationen zur ausgewählten Serie anzeigen"), "6" : (self.showConflicts, "Liste der Timer-Konflikte anzeigen"), }, -1) self.helpList[0][2].sort() self["helpActions"] = ActionMap(["SerienRecorderActions" ,], { "displayHelp" : self.showHelp, "displayHelp_long" : self.showManual, }, 0) self.setupSkin() self.delAdded = False self.wishlist = [] self.wishlist_tmp = [] self.dbData = [] self.modus = "menu_list" self.aSerie = "" self.aStaffel = 0 self.aFromEpisode = 0 self.aToEpisode = 0 self.onLayoutFinish.append(self.readWishlist) self.onClose.append(self.__onClose) self.onLayoutFinish.append(self.setSkinProperties) def callHelpAction(self, *args): HelpableScreen.callHelpAction(self, *args) def setSkinProperties(self): super(self.__class__, self).setSkinProperties() self['text_red'].setText("Eintrag löschen") self['text_green'].setText("Speichern") self['text_ok'].setText("Eintrag anlegen") if config.plugins.serienRec.wishListSorted.value: self['text_yellow'].setText("unsortierte Liste") else: self['text_yellow'].setText("Sortieren") self['text_blue'].setText("Liste leeren") self.num_bt_text[2][1] = buttonText_na super(self.__class__, self).startDisplayTimer() def setupSkin(self): self.skin = None InitSkin(self) # normal self.chooseMenuList = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self.chooseMenuList.l.setFont(0, gFont('Regular', 20 + int(config.plugins.serienRec.listFontsize.value))) self.chooseMenuList.l.setItemHeight(int(25 *skinFactor)) self['menu_list'] = self.chooseMenuList self['menu_list'].show() # popup self.chooseMenuList_popup = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self.chooseMenuList_popup.l.setFont(0, gFont('Regular', 20 + int(config.plugins.serienRec.listFontsize.value))) self.chooseMenuList_popup.l.setItemHeight(int(25 *skinFactor)) self['popup_list'] = self.chooseMenuList_popup self['popup_list'].hide() self['title'].setText("Diese Episoden sind zur Aufnahme vorgemerkt") if config.plugins.serienRec.showCover.value: self['cover'].show() if not config.plugins.serienRec.showAllButtons.value: self['bt_red'].show() self['bt_green'].show() self['bt_ok'].show() self['bt_yellow'].show() self['bt_blue'].show() self['bt_exit'].show() #self['bt_text'].show() self['bt_info'].show() self['bt_menu'].show() self['text_red'].show() self['text_green'].show() self['text_ok'].show() self['text_yellow'].show() self['text_blue'].show() self['text_0'].show() self['text_1'].show() self['text_2'].show() self['text_3'].show() self['text_4'].show() def updateMenuKeys(self): updateMenuKeys(self) def serieInfo(self): if self.modus == "menu_list": check = self['menu_list'].getCurrent() if check is None: return serien_name = self['menu_list'].getCurrent()[0][1] else: check = self['popup_list'].getCurrent() if check is None: return serien_name = self['popup_list'].getCurrent()[0][0] serien_id = None url = self.database.getMarkerURL(serien_name) if url: serien_id = url if serien_id: from SerienRecorderSeriesInfoScreen import serienRecShowInfo self.session.open(serienRecShowInfo, serien_name, serien_id) def setupClose(self, result): super(self.__class__, self).setupClose(result) if result[1]: self.readWishlist() def readWishlist(self): self.wishlist = [] bookmarks = self.database.getBookmarks() for bookmark in bookmarks: (Serie, Staffel, Episode, numberOfRecordings) = bookmark zeile = "%s S%sE%s" % (Serie, str(Staffel).zfill(2), str(Episode).zfill(2)) self.wishlist.append((zeile, Serie, Staffel, Episode)) self.wishlist_tmp = self.wishlist[:] if config.plugins.serienRec.wishListSorted.value: self.wishlist_tmp.sort() self.chooseMenuList.setList(map(self.buildList, self.wishlist_tmp)) self.getCover() @staticmethod def buildList(entry): (zeile, Serie, Staffel, Episode) = entry return [entry, (eListboxPythonMultiContent.TYPE_TEXT, 20, 00, 1280 * skinFactor, 25 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, zeile) ] @staticmethod def buildList_popup(entry): (Serie,) = entry return [entry, (eListboxPythonMultiContent.TYPE_TEXT, 5, 0, 560 * skinFactor, 25 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, Serie) ] def answerStaffel(self, aStaffel): self.aStaffel = aStaffel if self.aStaffel is None or self.aStaffel == "": return self.session.openWithCallback(self.answerFromEpisode, NTIVirtualKeyBoard, title = "von Episode:") def answerFromEpisode(self, aFromEpisode): self.aFromEpisode = aFromEpisode if self.aFromEpisode is None or self.aFromEpisode == "": return self.session.openWithCallback(self.answerToEpisode, NTIVirtualKeyBoard, title = "bis Episode:") def answerToEpisode(self, aToEpisode): self.aToEpisode = aToEpisode print "[SerienRecorder] Staffel: %s" % self.aStaffel print "[SerienRecorder] von Episode: %s" % self.aFromEpisode print "[SerienRecorder] bis Episode: %s" % self.aToEpisode if self.aToEpisode is None or self.aFromEpisode is None or self.aStaffel is None or self.aToEpisode == "": return else: self.database.addBookmark(self.aSerie, self.aFromEpisode, self.aToEpisode, self.aStaffel, int(config.plugins.serienRec.NoOfRecords.value)) self.readWishlist() def keyOK(self): if self.modus == "menu_list": self.modus = "popup_list" self['popup_list'].show() self['popup_bg'].show() self['menu_list'].hide() l = self.database.getMarkerNames() self.chooseMenuList_popup.setList(map(self.buildList_popup, l)) self['popup_list'].moveToIndex(0) else: self.modus = "menu_list" self['menu_list'].show() self['popup_list'].hide() self['popup_bg'].hide() if self['popup_list'].getCurrent() is None: print "[SerienRecorder] Marker-Liste leer." return self.aSerie = self['popup_list'].getCurrent()[0][0] self.aStaffel = 0 self.aFromEpisode = 0 self.aToEpisode = 0 self.session.openWithCallback(self.answerStaffel, NTIVirtualKeyBoard, title = "%s: Staffel eingeben:" % self.aSerie) def keyRed(self): check = self['menu_list'].getCurrent() if check is None: print "[SerienRecorder] Merkzettel ist leer." return else: zeile = self['menu_list'].getCurrent()[0] (title, serie, staffel, episode) = zeile self.dbData.append((serie.lower(), str(staffel).lower(), episode.lower())) self.wishlist_tmp.remove(zeile) self.wishlist.remove(zeile) self.chooseMenuList.setList(map(self.buildList, self.wishlist_tmp)) self.delAdded = True def keyGreen(self): if self.delAdded: self.database.removeBookmarks(self.dbData) self.close() def keyYellow(self): if len(self.wishlist_tmp) != 0: if config.plugins.serienRec.wishListSorted.value: self.wishlist_tmp = self.wishlist[:] self['text_yellow'].setText("Sortieren") config.plugins.serienRec.wishListSorted.setValue(False) else: self.wishlist_tmp.sort() self['text_yellow'].setText("unsortierte Liste") config.plugins.serienRec.wishListSorted.setValue(True) config.plugins.serienRec.wishListSorted.save() SerienRecorder.configfile.save() self.chooseMenuList.setList(map(self.buildList, self.wishlist_tmp)) self.getCover() def keyBlue(self): check = self['menu_list'].getCurrent() if check is None: print "[SerienRecorder] Merkzettel ist leer." return else: if config.plugins.serienRec.confirmOnDelete.value: self.session.openWithCallback(self.callClearListMsg, MessageBox, "Soll die Liste wirklich geleert werden?", MessageBox.TYPE_YESNO, default = False) else: self.callClearListMsg(True) def callClearListMsg(self, answer): if answer: self.database.removeAllBookmarks() self.readWishlist() else: return def getCover(self): if self.modus == "menu_list": check = self['menu_list'].getCurrent() if check is None: return serien_name = self['menu_list'].getCurrent()[0][1] else: check = self['popup_list'].getCurrent() if check is None: return serien_name = self['popup_list'].getCurrent()[0][0] serien_id = None url = self.database.getMarkerURL(serien_name) if url: serien_id = url SerienRecorder.getCover(self, serien_name, serien_id) def keyLeft(self): self[self.modus].pageUp() self.getCover() def keyRight(self): self[self.modus].pageDown() self.getCover() def keyDown(self): self[self.modus].down() self.getCover() def keyUp(self): self[self.modus].up() self.getCover() def __onClose(self): self.stopDisplayTimer() def callDeleteMsg(self, answer): if answer: self.keyGreen() self.close() def keyCancel(self): if self.delAdded: self.session.openWithCallback(self.callDeleteMsg, MessageBox, "Sollen die Änderungen gespeichert werden?", MessageBox.TYPE_YESNO, default = True) else: self.close()
def __init__(self, session): serienRecBaseScreen.__init__(self, session) Screen.__init__(self, session) HelpableScreen.__init__(self) self.session = session self.serienRecChannelList = [] self.stbChannelList = [] self.selected_sender = None self.skin = None self.displayMode = 2 self.chooseMenuList = None self.chooseMenuList_popup = None self.chooseMenuList_popup2 = None from SerienRecorder import serienRecDataBaseFilePath from SerienRecorderDatabase import SRDatabase self.database = SRDatabase(serienRecDataBaseFilePath) from difflib import SequenceMatcher self.sequenceMatcher = SequenceMatcher(" ".__eq__, "", "") self["actions"] = HelpableActionMap( self, "SerienRecorderActions", { "ok": (self.keyOK, "Popup-Fenster zur Auswahl des STB-Sender öffnen"), "cancel": (self.keyCancel, "zurück zur Serienplaner-Ansicht"), "red": (self.keyRed, "umschalten ausgewählter Sender für Timererstellung aktiviert/deaktiviert" ), "red_long": (self.keyRedLong, "ausgewählten Sender aus der Channelliste endgültig löschen"), "green": (self.keyGreen, "Sender-Zuordnung aktualisieren"), "blue": (self.keyBlue, "Automatische Sender-Zuordnung"), "menu": (self.channelSetup, "Menü für Sender-Einstellungen öffnen"), "menu_long": (self.recSetup, "Menü für globale Einstellungen öffnen"), "left": (self.keyLeft, "zur vorherigen Seite blättern"), "right": (self.keyRight, "zur nächsten Seite blättern"), "up": (self.keyUp, "eine Zeile nach oben"), "down": (self.keyDown, "eine Zeile nach unten"), "0": (self.readLogFile, "Log-File des letzten Suchlaufs anzeigen"), "3": (self.showProposalDB, "Liste der Serien/Staffel-Starts anzeigen"), "6": (self.showConflicts, "Liste der Timer-Konflikte anzeigen"), "7": (self.showWishlist, "Merkzettel (vorgemerkte Folgen) anzeigen"), "8": (self.checkChannels, "Sender prüfen"), "9": (self.resetChannelList, "Alle Zuordnungen löschen"), }, -1) self.helpList[0][2].sort() self["helpActions"] = ActionMap([ "SerienRecorderActions", ], { "displayHelp": self.showHelp, "displayHelp_long": self.showManual, }, 0) self.setupSkin() self.modus = "list" self.changesMade = False self.timer_default = eTimer() if isDreamOS(): self.timer_default_conn = self.timer_default.timeout.connect( self.showChannels) else: self.timer_default.callback.append(self.showChannels) self.onLayoutFinish.append(self.__onLayoutFinished) self.onClose.append(self.__onClose) self.onLayoutFinish.append(self.setSkinProperties)
class serienRecModifyAdded(serienRecBaseScreen, Screen, HelpableScreen): def __init__(self, session, skip=True): serienRecBaseScreen.__init__(self, session) Screen.__init__(self, session) HelpableScreen.__init__(self) self.session = session self.picload = ePicLoad() self.database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) self.chooseMenuList_popup = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self["actions"] = HelpableActionMap(self, "SerienRecorderActions", { "ok": (self.keyOK, "für die ausgewählte Serien neue Einträge hinzufügen"), "cancel": (self.keyCancel, "alle Änderungen verwerfen und zurück zur vorherigen Ansicht"), "left": (self.keyLeft, "zur vorherigen Seite blättern"), "right": (self.keyRight, "zur nächsten Seite blättern"), "up": (self.keyUp, "eine Zeile nach oben"), "down": (self.keyDown, "eine Zeile nach unten"), "red": (self.keyRed, "ausgewählten Eintrag löschen"), "green": (self.keyGreen, "alle Änderungen speichern und zurück zur vorherigen Ansicht"), "yellow": (self.keyYellow, "umschalten Sortierung ein/aus"), "menu": (self.recSetup, "Menü für globale Einstellungen öffnen"), "0" : (self.readLogFile, "Log-File des letzten Suchlaufs anzeigen"), "3" : (self.showProposalDB, "Liste der Serien/Staffel-Starts anzeigen"), "4" : (self.serieInfo, "Informationen zur ausgewählten Serie anzeigen"), "6" : (self.showConflicts, "Liste der Timer-Konflikte anzeigen"), "7" : (self.showWishlist, "Merkzettel (vorgemerkte Folgen) anzeigen"), }, -1) self.helpList[0][2].sort() self["helpActions"] = ActionMap(["SerienRecorderActions" ,], { "displayHelp" : self.showHelp, "displayHelp_long" : self.showManual, }, 0) self.setupSkin() self.delAdded = False self.addedlist = [] self.addedlist_tmp = [] self.dbData = [] self.modus = "menu_list" self.aSerie = "" self.aStaffel = "0" self.aFromEpisode = 0 self.aToEpisode = 0 if skip: self.onShown.append(self.functionWillBeDeleted) else: self.onLayoutFinish.append(self.readAdded) self.onClose.append(self.__onClose) self.onLayoutFinish.append(self.setSkinProperties) def functionWillBeDeleted(self): from SerienRecorderMarkerScreen import serienRecMarker self.session.open(serienRecMarker) self.hide() self.session.open(MessageBox, "WICHTIGER Hinweis:\n\n" "Dieser Funktionsaufruf wird ab dem nächsten Update nicht mehr zur Verfügung stehen!!\n\n" "Die manuelle Bearbeitung der Timer-Liste, d.h. Hinzufügen und Löschen einzelner Episoden " "kann in der Episoden-Liste der jeweiligen Serie erfolgen. Dazu in der Serien-Marker Ansicht die gewünschte Serie auswählen, " "und mit der Taste 5 die Episoden-Liste öffnen. Danach können mit der grünen Taste einzelne Episoden für die Timererstellung " "gesperrt oder wieder freigegeben werden.", MessageBox.TYPE_INFO) self.close() def callHelpAction(self, *args): HelpableScreen.callHelpAction(self, *args) def setSkinProperties(self): super(self.__class__, self).setSkinProperties() self['text_red'].setText("Eintrag löschen") self['text_green'].setText("Speichern") self['text_ok'].setText("Neuer Eintrag") if config.plugins.serienRec.addedListSorted.value: self['text_yellow'].setText("unsortierte Liste") else: self['text_yellow'].setText("Sortieren") self.num_bt_text[1][0] = buttonText_na super(self.__class__, self).startDisplayTimer() def setupSkin(self): self.skin = None InitSkin(self) # normal self.chooseMenuList = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self.chooseMenuList.l.setFont(0, gFont('Regular', 20 + int(config.plugins.serienRec.listFontsize.value))) self.chooseMenuList.l.setItemHeight(int(25 *skinFactor)) self['menu_list'] = self.chooseMenuList self['menu_list'].show() # popup self.chooseMenuList_popup = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self.chooseMenuList_popup.l.setFont(0, gFont('Regular', 20 + int(config.plugins.serienRec.listFontsize.value))) self.chooseMenuList_popup.l.setItemHeight(int(25 *skinFactor)) self['popup_list'] = self.chooseMenuList_popup self['popup_list'].hide() if config.plugins.serienRec.showCover.value: self['cover'].show() if not config.plugins.serienRec.showAllButtons.value: self['bt_red'].show() self['bt_green'].show() self['bt_ok'].show() self['bt_yellow'].show() self['bt_exit'].show() #self['bt_text'].show() self['bt_info'].show() self['bt_menu'].show() self['text_red'].show() self['text_green'].show() self['text_ok'].show() self['text_yellow'].show() self['text_0'].show() self['text_1'].show() self['text_2'].show() self['text_3'].show() self['text_4'].show() def updateMenuKeys(self): updateMenuKeys(self) def serieInfo(self): if self.modus == "menu_list": check = self['menu_list'].getCurrent() if check is None: return serien_name = self['menu_list'].getCurrent()[0][1] else: check = self['popup_list'].getCurrent() if check is None: return serien_name = self['popup_list'].getCurrent()[0][0] serien_id = None url = self.database.getMarkerURL(serien_name) if url: serien_id = url from SerienRecorderSeriesInfoScreen import serienRecShowInfo self.session.open(serienRecShowInfo, serien_name, serien_id) def setupClose(self, result): super(self.__class__, self).setupClose(result) if result[1]: self.readAdded() def readAdded(self): self.addedlist = [] timers = self.database.getAllTimer(None) for timer in timers: (Serie, Staffel, Episode, title, start_time, stbRef, webChannel, eit, active) = timer zeile = "%s - S%sE%s - %s" % (Serie, str(Staffel).zfill(2), str(Episode).zfill(2), title) self.addedlist.append((zeile.replace(" - dump", " - %s" % "(Manuell hinzugefügt !!)"), Serie, Staffel, Episode, title, start_time, webChannel)) self['title'].instance.setForegroundColor(parseColor("red")) self['title'].setText("Für diese Episoden werden keine Timer mehr erstellt !") self.addedlist_tmp = self.addedlist[:] if config.plugins.serienRec.addedListSorted.value: self.addedlist_tmp.sort() self.chooseMenuList.setList(map(self.buildList, self.addedlist_tmp)) self.getCover() @staticmethod def buildList(entry): (zeile, Serie, Staffel, Episode, title, start_time, webChannel) = entry foregroundColor = parseColor('foreground').argb() return [entry, (eListboxPythonMultiContent.TYPE_TEXT, 20, 00, 1280 * skinFactor, 25 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, zeile, foregroundColor) ] @staticmethod def buildList_popup(entry): (Serie,) = entry foregroundColor = parseColor('foreground').argb() return [entry, (eListboxPythonMultiContent.TYPE_TEXT, 5, 0, 560 * skinFactor, 25 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, Serie, foregroundColor) ] def answerStaffel(self, aStaffel): self.aStaffel = aStaffel if self.aStaffel is None or self.aStaffel == "": return self.session.openWithCallback(self.answerFromEpisode, NTIVirtualKeyBoard, title = "von Episode:") def answerFromEpisode(self, aFromEpisode): self.aFromEpisode = aFromEpisode if self.aFromEpisode is None or self.aFromEpisode == "": return self.session.openWithCallback(self.answerToEpisode, NTIVirtualKeyBoard, title = "bis Episode:") def answerToEpisode(self, aToEpisode): self.aToEpisode = aToEpisode if self.aToEpisode == "": self.aToEpisode = self.aFromEpisode if self.aToEpisode is None: # or self.aFromEpisode is None or self.aStaffel is None: return else: print "[SerienRecorder] Staffel: %s" % self.aStaffel print "[SerienRecorder] von Episode: %s" % self.aFromEpisode print "[SerienRecorder] bis Episode: %s" % self.aToEpisode if self.aStaffel.startswith('0') and len(self.aStaffel) > 1: self.aStaffel = self.aStaffel[1:] if self.database.addToTimerList(self.aSerie, self.aFromEpisode, self.aToEpisode, self.aStaffel, "dump", int(time.time()), "", "", 0, 1): self.readAdded() def keyOK(self): if self.modus == "menu_list": self.modus = "popup_list" self['popup_list'].show() self['popup_bg'].show() self['menu_list'].hide() l = self.database.getMarkerNames() self.chooseMenuList_popup.setList(map(self.buildList_popup, l)) self['popup_list'].moveToIndex(0) else: self.modus = "menu_list" self['menu_list'].show() self['popup_list'].hide() self['popup_bg'].hide() if self['popup_list'].getCurrent() is None: print "[SerienRecorder] Marker-Liste leer." return self.aSerie = self['popup_list'].getCurrent()[0][0] self.aStaffel = "0" self.aFromEpisode = 0 self.aToEpisode = 0 self.session.openWithCallback(self.answerStaffel, NTIVirtualKeyBoard, title = "%s: Staffel eingeben:" % self.aSerie) def keyRed(self): check = None if self.modus == "menu_list": check = self['menu_list'].getCurrent() if check is None: print "[SerienRecorder] Added-File leer." return else: zeile = self['menu_list'].getCurrent()[0] (txt, serie, staffel, episode, title, start_time, webChannel) = zeile self.dbData.append((serie.lower(), str(staffel).lower(), episode.lower(), title.lower(), start_time, webChannel.lower())) self.addedlist_tmp.remove(zeile) self.addedlist.remove(zeile) self.chooseMenuList.setList(map(self.buildList, self.addedlist_tmp)) self.delAdded = True def keyGreen(self): if self.modus == "menu_list" and self.delAdded: self.database.removeTimers(self.dbData) self.close() def keyYellow(self): if self.modus == "menu_list" and len(self.addedlist_tmp) != 0: if config.plugins.serienRec.addedListSorted.value: self.addedlist_tmp = self.addedlist[:] self['text_yellow'].setText("Sortieren") config.plugins.serienRec.addedListSorted.setValue(False) else: self.addedlist_tmp.sort() self['text_yellow'].setText("unsortierte Liste") config.plugins.serienRec.addedListSorted.setValue(True) config.plugins.serienRec.addedListSorted.save() SerienRecorder.configfile.save() self.chooseMenuList.setList(map(self.buildList, self.addedlist_tmp)) self.getCover() def getCover(self): if self.modus == "menu_list": check = self['menu_list'].getCurrent() if check is None: return serien_name = self['menu_list'].getCurrent()[0][1] else: check = self['popup_list'].getCurrent() if check is None: return serien_name = self['popup_list'].getCurrent()[0][0] serien_id = None url = self.database.getMarkerURL(serien_name) if url: serien_id = url SerienRecorder.getCover(self, serien_name, serien_id) def keyLeft(self): self[self.modus].pageUp() self.getCover() def keyRight(self): self[self.modus].pageDown() self.getCover() def keyDown(self): self[self.modus].down() self.getCover() def keyUp(self): self[self.modus].up() self.getCover() def __onClose(self): self.stopDisplayTimer() def callDeleteMsg(self, answer): if answer: self.keyGreen() self.close() def keyCancel(self): if self.delAdded: self.session.openWithCallback(self.callDeleteMsg, MessageBox, "Sollen die Änderungen gespeichert werden?", MessageBox.TYPE_YESNO, default = True) else: self.close()
class serienRecModifyAdded(serienRecBaseScreen, Screen, HelpableScreen): def __init__(self, session, skip=True): serienRecBaseScreen.__init__(self, session) Screen.__init__(self, session) HelpableScreen.__init__(self) self.session = session self.picload = ePicLoad() self.database = SRDatabase(SerienRecorder.serienRecDataBaseFilePath) self.chooseMenuList_popup = MenuList( [], enableWrapAround=True, content=eListboxPythonMultiContent) self["actions"] = HelpableActionMap( self, "SerienRecorderActions", { "ok": (self.keyOK, "für die ausgewählte Serien neue Einträge hinzufügen"), "cancel": (self.keyCancel, "alle Änderungen verwerfen und zurück zur vorherigen Ansicht" ), "left": (self.keyLeft, "zur vorherigen Seite blättern"), "right": (self.keyRight, "zur nächsten Seite blättern"), "up": (self.keyUp, "eine Zeile nach oben"), "down": (self.keyDown, "eine Zeile nach unten"), "red": (self.keyRed, "ausgewählten Eintrag löschen"), "green": (self.keyGreen, "alle Änderungen speichern und zurück zur vorherigen Ansicht" ), "yellow": (self.keyYellow, "umschalten Sortierung ein/aus"), "menu": (self.recSetup, "Menü für globale Einstellungen öffnen"), "0": (self.readLogFile, "Log-File des letzten Suchlaufs anzeigen"), "3": (self.showProposalDB, "Liste der Serien/Staffel-Starts anzeigen"), "4": (self.serieInfo, "Informationen zur ausgewählten Serie anzeigen"), "6": (self.showConflicts, "Liste der Timer-Konflikte anzeigen"), "7": (self.showWishlist, "Merkzettel (vorgemerkte Folgen) anzeigen"), }, -1) self.helpList[0][2].sort() self["helpActions"] = ActionMap([ "SerienRecorderActions", ], { "displayHelp": self.showHelp, "displayHelp_long": self.showManual, }, 0) self.setupSkin() self.delAdded = False self.addedlist = [] self.addedlist_tmp = [] self.dbData = [] self.modus = "menu_list" self.aSerie = "" self.aStaffel = "0" self.aFromEpisode = 0 self.aToEpisode = 0 if skip: self.onShown.append(self.functionWillBeDeleted) else: self.onLayoutFinish.append(self.readAdded) self.onClose.append(self.__onClose) self.onLayoutFinish.append(self.setSkinProperties) def functionWillBeDeleted(self): from SerienRecorderMarkerScreen import serienRecMarker self.session.open(serienRecMarker) self.hide() self.session.open( MessageBox, "WICHTIGER Hinweis:\n\n" "Dieser Funktionsaufruf wird ab dem nächsten Update nicht mehr zur Verfügung stehen!!\n\n" "Die manuelle Bearbeitung der Timer-Liste, d.h. Hinzufügen und Löschen einzelner Episoden " "kann in der Episoden-Liste der jeweiligen Serie erfolgen. Dazu in der Serien-Marker Ansicht die gewünschte Serie auswählen, " "und mit der Taste 5 die Episoden-Liste öffnen. Danach können mit der grünen Taste einzelne Episoden für die Timererstellung " "gesperrt oder wieder freigegeben werden.", MessageBox.TYPE_INFO) self.close() def callHelpAction(self, *args): HelpableScreen.callHelpAction(self, *args) def setSkinProperties(self): super(self.__class__, self).setSkinProperties() self['text_red'].setText("Eintrag löschen") self['text_green'].setText("Speichern") self['text_ok'].setText("Neuer Eintrag") if config.plugins.serienRec.addedListSorted.value: self['text_yellow'].setText("unsortierte Liste") else: self['text_yellow'].setText("Sortieren") self.num_bt_text[1][0] = buttonText_na super(self.__class__, self).startDisplayTimer() def setupSkin(self): self.skin = None InitSkin(self) # normal self.chooseMenuList = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self.chooseMenuList.l.setFont( 0, gFont('Regular', 20 + int(config.plugins.serienRec.listFontsize.value))) self.chooseMenuList.l.setItemHeight(int(25 * skinFactor)) self['menu_list'] = self.chooseMenuList self['menu_list'].show() # popup self.chooseMenuList_popup = MenuList( [], enableWrapAround=True, content=eListboxPythonMultiContent) self.chooseMenuList_popup.l.setFont( 0, gFont('Regular', 20 + int(config.plugins.serienRec.listFontsize.value))) self.chooseMenuList_popup.l.setItemHeight(int(25 * skinFactor)) self['popup_list'] = self.chooseMenuList_popup self['popup_list'].hide() if config.plugins.serienRec.showCover.value: self['cover'].show() if not config.plugins.serienRec.showAllButtons.value: self['bt_red'].show() self['bt_green'].show() self['bt_ok'].show() self['bt_yellow'].show() self['bt_exit'].show() #self['bt_text'].show() self['bt_info'].show() self['bt_menu'].show() self['text_red'].show() self['text_green'].show() self['text_ok'].show() self['text_yellow'].show() self['text_0'].show() self['text_1'].show() self['text_2'].show() self['text_3'].show() self['text_4'].show() def updateMenuKeys(self): updateMenuKeys(self) def serieInfo(self): if self.modus == "menu_list": check = self['menu_list'].getCurrent() if check is None: return serien_name = self['menu_list'].getCurrent()[0][1] else: check = self['popup_list'].getCurrent() if check is None: return serien_name = self['popup_list'].getCurrent()[0][0] serien_id = None url = self.database.getMarkerURL(serien_name) if url: serien_id = url from SerienRecorderSeriesInfoScreen import serienRecShowInfo self.session.open(serienRecShowInfo, serien_name, serien_id) def setupClose(self, result): super(self.__class__, self).setupClose(result) if result[1]: self.readAdded() def readAdded(self): self.addedlist = [] timers = self.database.getAllTimer(None) for timer in timers: (Serie, Staffel, Episode, title, start_time, stbRef, webChannel, eit, active) = timer zeile = "%s - S%sE%s - %s" % (Serie, str(Staffel).zfill(2), str(Episode).zfill(2), title) self.addedlist.append( (zeile.replace(" - dump", " - %s" % "(Manuell hinzugefügt !!)"), Serie, Staffel, Episode, title, start_time, webChannel)) self['title'].instance.setForegroundColor(parseColor("red")) self['title'].setText( "Für diese Episoden werden keine Timer mehr erstellt !") self.addedlist_tmp = self.addedlist[:] if config.plugins.serienRec.addedListSorted.value: self.addedlist_tmp.sort() self.chooseMenuList.setList(map(self.buildList, self.addedlist_tmp)) self.getCover() @staticmethod def buildList(entry): (zeile, Serie, Staffel, Episode, title, start_time, webChannel) = entry foregroundColor = parseColor('foreground').argb() return [ entry, (eListboxPythonMultiContent.TYPE_TEXT, 20, 00, 1280 * skinFactor, 25 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, zeile, foregroundColor) ] @staticmethod def buildList_popup(entry): (Serie, ) = entry foregroundColor = parseColor('foreground').argb() return [ entry, (eListboxPythonMultiContent.TYPE_TEXT, 5, 0, 560 * skinFactor, 25 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, Serie, foregroundColor) ] def answerStaffel(self, aStaffel): self.aStaffel = aStaffel if self.aStaffel is None or self.aStaffel == "": return self.session.openWithCallback(self.answerFromEpisode, NTIVirtualKeyBoard, title="von Episode:") def answerFromEpisode(self, aFromEpisode): self.aFromEpisode = aFromEpisode if self.aFromEpisode is None or self.aFromEpisode == "": return self.session.openWithCallback(self.answerToEpisode, NTIVirtualKeyBoard, title="bis Episode:") def answerToEpisode(self, aToEpisode): self.aToEpisode = aToEpisode if self.aToEpisode == "": self.aToEpisode = self.aFromEpisode if self.aToEpisode is None: # or self.aFromEpisode is None or self.aStaffel is None: return else: print "[SerienRecorder] Staffel: %s" % self.aStaffel print "[SerienRecorder] von Episode: %s" % self.aFromEpisode print "[SerienRecorder] bis Episode: %s" % self.aToEpisode if self.aStaffel.startswith('0') and len(self.aStaffel) > 1: self.aStaffel = self.aStaffel[1:] if self.database.addToTimerList(self.aSerie, self.aFromEpisode, self.aToEpisode, self.aStaffel, "dump", int(time.time()), "", "", 0, 1): self.readAdded() def keyOK(self): if self.modus == "menu_list": self.modus = "popup_list" self['popup_list'].show() self['popup_bg'].show() self['menu_list'].hide() l = self.database.getMarkerNames() self.chooseMenuList_popup.setList(map(self.buildList_popup, l)) self['popup_list'].moveToIndex(0) else: self.modus = "menu_list" self['menu_list'].show() self['popup_list'].hide() self['popup_bg'].hide() if self['popup_list'].getCurrent() is None: print "[SerienRecorder] Marker-Liste leer." return self.aSerie = self['popup_list'].getCurrent()[0][0] self.aStaffel = "0" self.aFromEpisode = 0 self.aToEpisode = 0 self.session.openWithCallback(self.answerStaffel, NTIVirtualKeyBoard, title="%s: Staffel eingeben:" % self.aSerie) def keyRed(self): check = None if self.modus == "menu_list": check = self['menu_list'].getCurrent() if check is None: print "[SerienRecorder] Added-File leer." return else: zeile = self['menu_list'].getCurrent()[0] (txt, serie, staffel, episode, title, start_time, webChannel) = zeile self.dbData.append( (serie.lower(), str(staffel).lower(), episode.lower(), title.lower(), start_time, webChannel.lower())) self.addedlist_tmp.remove(zeile) self.addedlist.remove(zeile) self.chooseMenuList.setList(map(self.buildList, self.addedlist_tmp)) self.delAdded = True def keyGreen(self): if self.modus == "menu_list" and self.delAdded: self.database.removeTimers(self.dbData) self.close() def keyYellow(self): if self.modus == "menu_list" and len(self.addedlist_tmp) != 0: if config.plugins.serienRec.addedListSorted.value: self.addedlist_tmp = self.addedlist[:] self['text_yellow'].setText("Sortieren") config.plugins.serienRec.addedListSorted.setValue(False) else: self.addedlist_tmp.sort() self['text_yellow'].setText("unsortierte Liste") config.plugins.serienRec.addedListSorted.setValue(True) config.plugins.serienRec.addedListSorted.save() SerienRecorder.configfile.save() self.chooseMenuList.setList(map(self.buildList, self.addedlist_tmp)) self.getCover() def getCover(self): if self.modus == "menu_list": check = self['menu_list'].getCurrent() if check is None: return serien_name = self['menu_list'].getCurrent()[0][1] else: check = self['popup_list'].getCurrent() if check is None: return serien_name = self['popup_list'].getCurrent()[0][0] serien_id = None url = self.database.getMarkerURL(serien_name) if url: serien_id = url SerienRecorder.getCover(self, serien_name, serien_id) def keyLeft(self): self[self.modus].pageUp() self.getCover() def keyRight(self): self[self.modus].pageDown() self.getCover() def keyDown(self): self[self.modus].down() self.getCover() def keyUp(self): self[self.modus].up() self.getCover() def __onClose(self): self.stopDisplayTimer() def callDeleteMsg(self, answer): if answer: self.keyGreen() self.close() def keyCancel(self): if self.delAdded: self.session.openWithCallback( self.callDeleteMsg, MessageBox, "Sollen die Änderungen gespeichert werden?", MessageBox.TYPE_YESNO, default=True) else: self.close()
class serienRecMainScreen(serienRecBaseScreen, Screen, HelpableScreen): def __init__(self, session): serienRecBaseScreen.__init__(self, session) Screen.__init__(self, session) HelpableScreen.__init__(self) self.session = session self.picload = ePicLoad() self.picloader = None self.ErrorMsg = "unbekannt" self.skin = None self.chooseMenuList = None self.chooseMenuList_popup = None self.popup_list = [] self.piconLoader = PiconLoader() self.database = None self.singleTimer_conn = None self.displayTimer_conn = None self["actions"] = HelpableActionMap(self, "SerienRecorderActions", { "ok" : (self.keyOK, "Marker für die ausgewählte Serie hinzufügen"), "cancel": (self.keyCancel, "SerienRecorder beenden"), "left" : (self.keyLeft, "zur vorherigen Seite blättern"), "right" : (self.keyRight, "zur nächsten Seite blättern"), "up" : (self.keyUp, "eine Zeile nach oben"), "down" : (self.keyDown, "eine Zeile nach unten"), "red" : (self.keyRed, "Anzeige-Modus auswählen"), "green" : (self.keyGreen, "Ansicht Sender-Zuordnung öffnen"), "yellow": (self.keyYellow, "Ansicht Serien-Marker öffnen"), "blue" : (self.keyBlue, "Ansicht Timer-Liste öffnen"), "info" : (self.keyCheck, "Suchlauf für Timer starten"), "menu" : (self.recSetup, "Menü für globale Einstellungen öffnen"), "nextBouquet" : (self.nextPage, "Serienplaner des nächsten Tages laden"), "prevBouquet" : (self.backPage, "Serienplaner des vorherigen Tages laden"), "startTeletext" : (self.wunschliste, "Informationen zur ausgewählten Serie auf Wunschliste anzeigen"), "0" : (self.readLogFile, "Log-File des letzten Suchlaufs anzeigen"), "1" : (self.searchSeries, "Serie manuell suchen"), "2" : (self.reloadSerienplaner, "Serienplaner neu laden"), "3" : (self.showProposalDB, "Liste der Serien/Staffel-Starts anzeigen"), "4" : (self.serieInfo, "Informationen zur ausgewählten Serie anzeigen"), "6" : (self.showConflicts, "Liste der Timer-Konflikte anzeigen"), "7" : (self.showWishlist, "Merkzettel (vorgemerkte Folgen) anzeigen"), "5" : (self.imapTest, "IMAP Test"), }, -1) self.helpList[0][2].sort() self["helpActions"] = ActionMap(["SerienRecorderActions" ,], { "displayHelp" : self.showHelp, "displayHelp_long" : self.showManual, }, 0) SerienRecorder.ReadConfigFile() if not os.path.exists(config.plugins.serienRec.piconPath.value): config.plugins.serienRec.showPicons.value = False self.setupSkin() if config.plugins.serienRec.updateInterval.value == 24: config.plugins.serienRec.timeUpdate.value = True elif config.plugins.serienRec.updateInterval.value == 0: config.plugins.serienRec.timeUpdate.value = False else: config.plugins.serienRec.timeUpdate.value = False global showMainScreen if config.plugins.serienRec.firstscreen.value == "0": showMainScreen = True else: showMainScreen = False self.pRegional = 0 self.pPaytv = 1 self.pPrime = 1 self.page = 0 self.modus = "list" self.loading = True self.daylist = [[]] self.displayTimer = None self.displayMode = 1 self.serviceRefs = None self.onLayoutFinish.append(self.setSkinProperties) self.onFirstExecBegin.append(self.showSplashScreen) self.onFirstExecBegin.append(self.checkForUpdate) if config.plugins.serienRec.showStartupInfoText.value: if fileExists("%sStartupInfoText" % SerienRecorder.serienRecMainPath): self.onFirstExecBegin.append(self.showInfoText) else: self.onFirstExecBegin.append(self.startScreen) else: self.onFirstExecBegin.append(self.startScreen) self.onClose.append(self.__onClose) def imapTest(self): from SerienRecorderTVPlaner import imaptest imaptest(self.session) def showInfoText(self): from SerienRecorderStartupInfoScreen import ShowStartupInfo self.session.openWithCallback(self.startScreen, ShowStartupInfo) def showSplashScreen(self): from SerienRecorderSplashScreen import ShowSplashScreen self.session.openWithCallback(self.checkForUpdate, ShowSplashScreen, config.plugins.serienRec.showversion.value) def checkForUpdate(self): if config.plugins.serienRec.Autoupdate.value: from SerienRecorderUpdateScreen import checkGitHubUpdate checkGitHubUpdate(self.session).checkForUpdate() self.startScreen() def callHelpAction(self, *args): HelpableScreen.callHelpAction(self, *args) def setSkinProperties(self): super(self.__class__, self).setSkinProperties() self['text_red'].setText("Anzeige-Modus") self['text_green'].setText("Sender zuordnen") self['text_ok'].setText("Marker hinzufügen") self['text_yellow'].setText("Serien Marker") self['text_blue'].setText("Timer-Liste") self.num_bt_text[0][1] = "IMAP-Test" self.num_bt_text[1][0] = "Serie suchen" self.num_bt_text[2][0] = "Neu laden" self.num_bt_text[2][2] = "Timer suchen" super(self.__class__, self).startDisplayTimer() def setupSkin(self): self.skin = None InitSkin(self) self.chooseMenuList = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self.chooseMenuList.l.setFont(0, gFont('Regular', 20 + int(config.plugins.serienRec.listFontsize.value))) self.chooseMenuList.l.setItemHeight(int(50 * skinFactor)) self['menu_list'] = self.chooseMenuList self['menu_list'].show() # popup self.chooseMenuList_popup = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self.chooseMenuList_popup.l.setFont(0, gFont('Regular', 20 + int(config.plugins.serienRec.listFontsize.value))) self.chooseMenuList_popup.l.setItemHeight(int(30 * skinFactor)) self['popup_list'] = self.chooseMenuList_popup self['popup_list'].hide() self['title'].setText("Lade infos from Web...") if config.plugins.serienRec.showCover.value: self['cover'].show() if not config.plugins.serienRec.showAllButtons.value: self['bt_red'].show() self['bt_green'].show() self['bt_ok'].show() self['bt_yellow'].show() self['bt_blue'].show() self['bt_exit'].show() self['bt_text'].show() self['bt_epg'].show() self['bt_info'].show() self['bt_menu'].show() self['text_red'].show() self['text_green'].show() self['text_ok'].show() self['text_yellow'].show() self['text_blue'].show() self['text_0'].show() self['text_1'].show() self['text_2'].show() self['text_3'].show() self['text_4'].show() def updateMenuKeys(self): updateMenuKeys(self) def test(self): i = 0 def reloadSerienplaner(self): # lt = datetime.datetime.now() # lt += datetime.timedelta(days=self.page) # key = time.strftime('%d.%m.%Y', lt.timetuple()) # cache = serienRecMainScreen.loadPlanerData(config.plugins.serienRec.screenplaner.value) # if key in cache: # del cache[key] self.readPlanerData(False) def readLogFile(self): from SerienRecorderLogScreen import serienRecReadLog self.session.open(serienRecReadLog) def showProposalDB(self): from SerienRecorderSeasonBeginsScreen import serienRecShowSeasonBegins self.session.openWithCallback(self.readPlanerData, serienRecShowSeasonBegins) def searchSeries(self): if self.modus == "list": self.session.openWithCallback(self.wSearch, NTIVirtualKeyBoard, title = "Serien Titel eingeben:") def wSearch(self, serien_name): if serien_name: from SerienRecorderSearchResultScreen import serienRecSearchResultScreen self.session.openWithCallback(self.handleSeriesSearchEnd, serienRecSearchResultScreen, serien_name) def handleSeriesSearchEnd(self, serien_name=None): if serien_name: from SerienRecorderMarkerScreen import serienRecMarker self.session.openWithCallback(self.readPlanerData, serienRecMarker, serien_name) else: self.readPlanerData(False) def serieInfo(self): if self.loading: return check = self['menu_list'].getCurrent() if check is None: return (serien_name, serien_id) = self.getSeriesNameID() from SerienRecorderSeriesInfoScreen import serienRecShowInfo self.session.open(serienRecShowInfo, serien_name, serien_id) def wunschliste(self): (serien_name, serien_id) = self.getSeriesNameID() super(self.__class__, self).wunschliste(serien_id) def setHeadline(self): if int(config.plugins.serienRec.screenplaner.value) == 1: self['headline'].setText("Serien-Planer (Serien Tagesübersicht)") self['text_red'].setText("Top 30") elif int(config.plugins.serienRec.screenplaner.value) == 2: self['headline'].setText("Top 30 SerienRecorder Serien") self['text_red'].setText("Tagesübersicht") self['headline'].instance.setForegroundColor(parseColor("red")) def recSetup(self): from SerienRecorderSetupScreen import serienRecSetup self.session.openWithCallback(self.setupClose, serienRecSetup) def setupClose(self, result): super(self.__class__, self).setupClose(result) if result[1]: self.readPlanerData() 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(): self.keyCancel() self.close() return 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() if not showMainScreen: from SerienRecorderMarkerScreen import serienRecMarker self.session.openWithCallback(self.readPlanerData, serienRecMarker) else: self.readPlanerData(False) 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 processPlanerData(self, data, useCache=False): if not data or len(data) == 0: self['title'].setText("Fehler beim Abrufen der SerienPlaner-Daten") return if useCache: (headDate, self.daylist) = data else: self.daylist = [[]] headDate = [data["date"]] markers = self.database.getAllMarkerStatusForBoxID(config.plugins.serienRec.BoxID.value) timers = self.database.getTimer(self.page) for event in data["events"]: aufnahme = False serieAdded = 0 start_h = event["time"][:+2] start_m = event["time"][+3:] start_time = TimeHelpers.getUnixTimeWithDayOffset(start_h, start_m, self.page) serien_name = event["name"].encode("utf-8") serien_name_lower = serien_name.lower() serien_id = int(event["id"]) sender = event["channel"] title = event["title"].encode("utf-8") staffel = event["season"] episode = event["episode"] self.ErrorMsg = "%s - S%sE%s - %s (%s)" % \ (serien_name, str(staffel).zfill(2), str(episode).zfill(2), title, sender) serienTimers = [timer for timer in timers if timer[0] == serien_name_lower] serienTimersOnChannel = [serienTimer for serienTimer in serienTimers if serienTimer[2] == sender.lower()] for serienTimerOnChannel in serienTimersOnChannel: if (int(serienTimerOnChannel[1]) >= (int(start_time) - 300)) and ( int(serienTimerOnChannel[1]) < (int(start_time) + 300)): aufnahme = True # 0 = no marker, 1 = active marker, 2 = deactive marker if serien_id in markers: serieAdded = 1 if markers[serien_id] else 2 staffel = str(staffel).zfill(2) episode = str(episode).zfill(2) ############################## # # CHECK # # ueberprueft anhand des Seriennamen, Season, Episode ob die serie bereits auf der HDD existiert # seasonEpisodeString = "S%sE%s" % (str(staffel).zfill(2), str(episode).zfill(2)) bereits_vorhanden = False if config.plugins.serienRec.sucheAufnahme.value: (dirname, dirname_serie) = getDirname(self.database, serien_name, staffel) if str(episode).isdigit(): if int(episode) == 0: bereits_vorhanden = STBHelpers.countEpisodeOnHDD(dirname, seasonEpisodeString, serien_name, False, title) > 0 and True or False else: bereits_vorhanden = STBHelpers.countEpisodeOnHDD(dirname, seasonEpisodeString, serien_name, False) > 0 and True or False else: bereits_vorhanden = STBHelpers.countEpisodeOnHDD(dirname, seasonEpisodeString, serien_name, False) > 0 and True or False title = "%s - %s" % (seasonEpisodeString, title) regional = False paytv = False neu = event["new"] prime = False transmissionTime = event["time"] url = '' self.daylist[0].append(( regional, paytv, neu, prime, transmissionTime, url, serien_name, sender, staffel, episode, title, aufnahme, serieAdded, bereits_vorhanden, serien_id)) print "[SerienRecorder] Es wurden %s Serie(n) gefunden" % len(self.daylist[0]) if headDate: d = headDate[0].split(',') d.reverse() key = d[0].strip() cache = serienRecSeriesPlanner.loadPlanerData(1) cache.update({key: (headDate, self.daylist)}) if config.plugins.serienRec.planerCacheEnabled.value: serienRecSeriesPlanner.writePlanerData(1, cache) self.loading = False if len(self.daylist[0]) != 0: if headDate: self['title'].setText( "Es wurden für - %s - %s Serie(n) gefunden." % (headDate[0], len(self.daylist[0]))) self['title'].instance.setForegroundColor(parseColor("foreground")) else: self['title'].setText("Es wurden für heute %s Serie(n) gefunden." % len(self.daylist[0])) self['title'].instance.setForegroundColor(parseColor("foreground")) self.chooseMenuList.setList(map(self.buildPlanerList, self.daylist[0])) self.ErrorMsg = "'getCover()'" self.getCover() else: if int(self.page) < 1 and not int(self.page) == 0: self.page -= 1 self['title'].setText("Es wurden für heute %s Serie(n) gefunden." % len(self.daylist[0])) self['title'].instance.setForegroundColor(parseColor("foreground")) print "[SerienRecorder] Wunschliste Serien-Planer -> LISTE IST LEER !!!!" self.chooseMenuList.setList(map(self.buildPlanerList, self.daylist[0])) def processTopThirty(self, data, useCache=False): if not data or len(data) == 0: self['title'].setText("Fehler beim Abrufen der SerienPlaner-Daten") return if useCache: (headDate, self.daylist) = data else: self.daylist = [[]] headDate = [data["date"]] markers = self.database.getAllMarkerStatusForBoxID(config.plugins.serienRec.BoxID.value) rank = 0 for serie in data["series"]: serien_name = serie["name"].encode("utf-8") serien_id = int(serie["id"]) average = serie["average"] # 0 = no marker, 1 = active marker, 2 = deactive marker serieAdded = 0 if serien_id in markers: serieAdded = 1 if markers[serien_id] else 2 rank += 1 self.daylist[0].append((serien_name, average, serien_id, serieAdded, rank)) if headDate: d = headDate[0].split(',') d.reverse() key = d[0].strip() cache = serienRecSeriesPlanner.loadPlanerData(2) cache.update({key: (headDate, self.daylist)}) if config.plugins.serienRec.planerCacheEnabled.value: serienRecSeriesPlanner.writePlanerData(2, cache) self.loading = False self['title'].setText("") self.chooseMenuList.setList(map(self.buildTopThirtyList, self.daylist[0])) self.ErrorMsg = "'getCover()'" self.getCover() def buildPlanerList(self, entry): (regional, paytv, neu, prime, transmissionTime, url, serien_name, sender, staffel, episode, title, aufnahme, serieAdded, bereits_vorhanden, serien_id) = entry imageNone = "%simages/black.png" % SerienRecorder.serienRecMainPath imageNeu = "%simages/neu.png" % SerienRecorder.serienRecMainPath imageTimer = "%simages/timer.png" % SerienRecorder.serienRecMainPath imageHDD = "%simages/hdd_icon.png" % SerienRecorder.serienRecMainPath if serieAdded == 1: seriesColor = parseColor('green').argb() elif serieAdded == 2: seriesColor = parseColor('red').argb() else: seriesColor = None if aufnahme: seriesColor = parseColor('blue').argb() titleColor = timeColor = parseColor('foreground').argb() if int(neu) == 0: imageNeu = imageNone if bereits_vorhanden: imageHDDTimer = imageHDD elif aufnahme: imageHDDTimer = imageTimer else: imageHDDTimer = imageNone if config.plugins.serienRec.showPicons.value != "0": picon = loadPNG(imageNone) if sender and self.serviceRefs.get(sender): # Get picon by reference or name piconPath = self.piconLoader.getPicon(self.serviceRefs.get(sender)[0] if config.plugins.serienRec.showPicons.value == "1" else self.serviceRefs.get(sender)[1]) if piconPath: self.picloader = PicLoader(80 * skinFactor, 40 * skinFactor) picon = self.picloader.load(piconPath) self.picloader.destroy() return [entry, (eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 5, 5 * skinFactor, 80 * skinFactor, 40 * skinFactor, picon), ( eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 330 * skinFactor, 7 * skinFactor, 30 * skinFactor, 22 * skinFactor, loadPNG(imageNeu)), (eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 330 * skinFactor, 30 * skinFactor, 30 * skinFactor, 22 * skinFactor, loadPNG(imageHDDTimer)), (eListboxPythonMultiContent.TYPE_TEXT, 100 * skinFactor, 3, 200 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, sender), (eListboxPythonMultiContent.TYPE_TEXT, 100 * skinFactor, 29 * skinFactor, 150 * skinFactor, 18 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, transmissionTime, timeColor, timeColor), (eListboxPythonMultiContent.TYPE_TEXT, 365 * skinFactor, 3, 500 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, serien_name, seriesColor, seriesColor), (eListboxPythonMultiContent.TYPE_TEXT, 365 * skinFactor, 29 * skinFactor, 500 * skinFactor, 18 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, title, titleColor, titleColor) ] else: return [entry, (eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 5, 7, 30 * skinFactor, 22 * skinFactor, loadPNG(imageNeu)), (eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 5, 30 * skinFactor, 30 * skinFactor, 22 * skinFactor, loadPNG(imageHDDTimer)), (eListboxPythonMultiContent.TYPE_TEXT, 40 * skinFactor, 3, 280 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, sender), (eListboxPythonMultiContent.TYPE_TEXT, 40 * skinFactor, 29 * skinFactor, 150 * skinFactor, 18 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, transmissionTime, timeColor, timeColor), (eListboxPythonMultiContent.TYPE_TEXT, 340 * skinFactor, 3, 520 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, serien_name, seriesColor, seriesColor), (eListboxPythonMultiContent.TYPE_TEXT, 340 * skinFactor, 29 * skinFactor, 520 * skinFactor, 18 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, title, titleColor, titleColor) ] @staticmethod def buildTopThirtyList(entry): (serien_name, average, serien_id, serieAdded, rank) = entry if serieAdded == 1: seriesColor = parseColor('green').argb() elif serieAdded == 2: seriesColor = parseColor('red').argb() else: seriesColor = None title = "%d Abrufe/Tag" % average titleColor = parseColor('foreground').argb() rank = "%d." % rank return [entry, (eListboxPythonMultiContent.TYPE_TEXT, 5 * skinFactor, 3, 40 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_RIGHT | RT_VALIGN_CENTER, rank, titleColor, titleColor), (eListboxPythonMultiContent.TYPE_TEXT, 70 * skinFactor, 3, 520 * skinFactor, 26 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, serien_name, seriesColor, seriesColor), (eListboxPythonMultiContent.TYPE_TEXT, 70 * skinFactor, 29 * skinFactor, 520 * skinFactor, 18 * skinFactor, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, title, titleColor, titleColor) ] 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 getCover(self): if self.loading: return check = self['menu_list'].getCurrent() if check is None: return (serien_name, serien_id) = self.getSeriesNameID() self.ErrorMsg = "'getCover()'" SerienRecorder.getCover(self, serien_name, serien_id) def keyRed(self): if self.modus == "list": if config.plugins.serienRec.screenplaner.value == 1: config.plugins.serienRec.screenplaner.value = 2 else: config.plugins.serienRec.screenplaner.value = 1 config.plugins.serienRec.screenplaner.save() SerienRecorder.configfile.save() self.readPlanerData(False) def getSeriesNameID(self): if config.plugins.serienRec.screenplaner.value == 1: serien_name = self['menu_list'].getCurrent()[0][6] serien_id = self['menu_list'].getCurrent()[0][14] else: serien_name = self['menu_list'].getCurrent()[0][0] serien_id = self['menu_list'].getCurrent()[0][2] return serien_name, serien_id def keyGreen(self): from SerienRecorderChannelScreen import serienRecMainChannelEdit self.session.openWithCallback(self.readPlanerData, serienRecMainChannelEdit) def keyYellow(self): from SerienRecorderMarkerScreen import serienRecMarker self.session.openWithCallback(self.readPlanerData, serienRecMarker) def keyBlue(self): from SerienRecorderTimerListScreen import serienRecTimerListScreen self.session.openWithCallback(self.readPlanerData, serienRecTimerListScreen) def keyCheck(self): if config.plugins.serienRec.tvplaner.value: self.session.openWithCallback(self.executeAutoCheck, MessageBox, "Bei 'ja' wird der Suchlauf für TV-Planer Timer gestartet, bei 'nein' wird ein voller Suchlauf durchgeführt.", MessageBox.TYPE_YESNO) else: self.executeAutoCheck(False) def executeAutoCheck(self, withTVPlaner): from SerienRecorderAutoCheckScreen import serienRecRunAutoCheckScreen self.session.openWithCallback(self.readPlanerData, serienRecRunAutoCheckScreen, withTVPlaner) def keyLeft(self): if self.modus == "list": self['menu_list'].pageUp() self.getCover() def keyRight(self): if self.modus == "list": self['menu_list'].pageDown() self.getCover() def keyDown(self): if self.modus == "list": self['menu_list'].down() self.getCover() def keyUp(self): if self.modus == "list": self['menu_list'].up() self.getCover() def nextPage(self): if config.plugins.serienRec.screenplaner.value == 1 and self.page < 4: self.page += 1 self.chooseMenuList.setList(map(self.buildPlanerList, [])) self.readPlanerData(False) def backPage(self): if config.plugins.serienRec.screenplaner.value == 1 and not self.page < 1: self.page -= 1 self.chooseMenuList.setList(map(self.buildPlanerList, [])) self.readPlanerData(False) def __onClose(self): self.stopDisplayTimer() def keyCancel(self): if self.modus == "list": self.stopDisplayTimer() self.close()
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