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 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)
Exemplo n.º 3
0
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)
Exemplo n.º 4
0
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()
Exemplo n.º 5
0
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