Beispiel #1
0
def parseConfig(configuration, list, version = None, uniqueTimerId = 0, defaultTimer = None):
	try:
		intVersion = int(version)
	except ValueError:
		print('[AutoTimer] Config version "%s" is not a valid integer, assuming old version' % version)
		intVersion = -1

	if intVersion < 5:
		parseConfigOld(configuration, list, uniqueTimerId)
		return

	if defaultTimer is not None:
		# Read in defaults for a new timer
		for defaults in configuration.findall("defaults"):
			parseEntry(defaults, defaultTimer, True)

	for timer in configuration.findall("timer"):
		uniqueTimerId += 1
		baseTimer = preferredAutoTimerComponent(
			uniqueTimerId,
			'',
			'',
			True
		)

		if parseEntry(timer, baseTimer):
			list.append(baseTimer)
def addAutotimerFromSearchString(session, match):
	from AutoTimerComponent import preferredAutoTimerComponent
	from AutoTimerImporter import AutoTimerImporter
	from plugin import autotimer

	# Create instance if needed
	if autotimer is None:
		from AutoTimer import AutoTimer
		autotimer = AutoTimer()
		autotimer.readXml()

	session.openWithCallback(
		importerCallback,
		AutoTimerImporter,
		preferredAutoTimerComponent(
			autotimer.getUniqueId(),
			match,
			'',		# Match
			True	# Enabled
		),
		match,		# Proposed Match
		None,		# Proposed Begin
		None,		# Proposed End
		None,		# Proposed Disabled
		None,		# Proposed ServiceReference
		None,		# Proposed afterEvent
		None,		# Proposed justplay
		None,		# Proposed dirname, can we get anything useful here?
		[]			# Proposed tags
	)
def parseConfig(configuration, list, version = None, uniqueTimerId = 0, defaultTimer = None):
	try:
		intVersion = int(version)
	except ValueError:
		print('[AutoTimer] Config version "%s" is not a valid integer, assuming old version' % version)
		intVersion = -1

	if intVersion < 5:
		parseConfigOld(configuration, list, uniqueTimerId)
		return

	if defaultTimer is not None:
		# Read in defaults for a new timer
		for defaults in configuration.findall("defaults"):
			parseEntry(defaults, defaultTimer, True)

	for timer in configuration.findall("timer"):
		uniqueTimerId += 1
		baseTimer = preferredAutoTimerComponent(
			uniqueTimerId,
			'',
			'',
			True
		)

		if parseEntry(timer, baseTimer):
			list.append(baseTimer)
def addAutotimerFromSearchString(session, match):
	from AutoTimerComponent import preferredAutoTimerComponent
	from AutoTimerImporter import AutoTimerImporter
	from plugin import autotimer

	# Create instance if needed
	if autotimer is None:
		from AutoTimer import AutoTimer
		autotimer = AutoTimer()
		autotimer.readXml()

	session.openWithCallback(
		importerCallback,
		AutoTimerImporter,
		preferredAutoTimerComponent(
			autotimer.getUniqueId(),
			match,
			'',		# Match
			True	# Enabled
		),
		match,		# Proposed Match
		None,		# Proposed Begin
		None,		# Proposed End
		None,		# Proposed Disabled
		None,		# Proposed ServiceReference
		None,		# Proposed afterEvent
		None,		# Proposed justplay
		None,		# Proposed dirname, can we get anything useful here?
		[]			# Proposed tags
	)
    def readXml(self):
        # Abort if no config found
        if not os_path.exists(XML_CONFIG):
            print("[AutoTimer] No configuration file present")
            return

        # Parse if mtime differs from whats saved
        mtime = os_path.getmtime(XML_CONFIG)
        if mtime == self.configMtime:
            print("[AutoTimer] No changes in configuration, won't parse")
            return

        # Save current mtime
        self.configMtime = mtime

        # Parse Config
        try:
            configuration = cet_parse(XML_CONFIG).getroot()
        except:
            try:
                if os_path.exists(XML_CONFIG + "_old"):
                    os_rename(XML_CONFIG + "_old", XML_CONFIG + "_old(1)")
                os_rename(XML_CONFIG, XML_CONFIG + "_old")
                print(
                    "[AutoTimer] autotimer.xml is corrupt rename file to /etc/enigma2/autotimer.xml_old"
                )
            except:
                pass
            if Standby.inStandby is None:
                AddPopup(_(
                    "The autotimer file (/etc/enigma2/autotimer.xml) is corrupt. A new and empty config was created. A backup of the config can be found here (/etc/enigma2/autotimer.xml_old) "
                ),
                         type=MessageBox.TYPE_ERROR,
                         timeout=0,
                         id="AutoTimerLoadFailed")

            self.timers = []
            self.defaultTimer = preferredAutoTimerComponent(
                0,  # Id
                "",  # Name
                "",  # Match
                True  # Enabled
            )

            try:
                self.writeXml()
                configuration = cet_parse(XML_CONFIG).getroot()
            except:
                print(
                    "[AutoTimer] fatal error, the autotimer.xml cannot create")
                return

        # Empty out timers and reset Ids
        del self.timers[:]
        self.defaultTimer.clear(-1, True)

        parseConfig(configuration, self.timers, configuration.get("version"),
                    0, self.defaultTimer)
        self.uniqueTimerId = len(self.timers)
def addAutotimerFromEvent(session, evt = None, service = None):
	from AutoTimerComponent import preferredAutoTimerComponent
	from AutoTimerImporter import AutoTimerImporter
	from plugin import autotimer

	# Create instance if needed
	if autotimer is None:
		from AutoTimer import AutoTimer
		autotimer = AutoTimer()
		autotimer.readXml()

	match = evt and evt.getEventName() or ""
	name = match or "New AutoTimer"
	sref = None
	if service is not None:
		service = str(service)
		myref = eServiceReference(service)
		if not (myref.flags & eServiceReference.isGroup):
			# strip all after last :
			pos = service.rfind(':')
			if pos != -1:
				if service[pos-1] == ':':
					pos -= 1
				service = service[:pos+1]

		sref = ServiceReference(myref)
	if evt:
		# timespan defaults to +- 1h
		begin = evt.getBeginTime()-3600
		end = begin + evt.getDuration()+7200
	else:
		begin = end = 0

	# XXX: we might want to make sure that we actually collected any data because the importer does not do so :-)

	session.openWithCallback(
		importerCallback,
		AutoTimerImporter,
		preferredAutoTimerComponent(
			autotimer.getUniqueId(),
			name,
			'',		# Match
			True	# Enabled
		),
		match,		# Proposed Match
		begin,		# Proposed Begin
		end,		# Proposed End
		None,		# Proposed Disabled
		sref,		# Proposed ServiceReference
		None,		# Proposed afterEvent
		None,		# Proposed justplay
		None,		# Proposed dirname, can we get anything useful here?
		[]			# Proposed tags
	)
	def __init__(self):
		# Initialize
		self.timers = []
		self.configMtime = -1
		self.uniqueTimerId = 0
		self.defaultTimer = preferredAutoTimerComponent(
			0,		# Id
			"",		# Name
			"",		# Match
			True 	# Enabled
		)
Beispiel #8
0
	def __init__(self):
		# Initialize
		self.timers = []
		self.configMtime = -1
		self.uniqueTimerId = 0
		self.defaultTimer = preferredAutoTimerComponent(
			0,		# Id
			"",		# Name
			"",		# Match
			True 	# Enabled
		)
def addAutotimerFromEvent(session, evt = None, service = None):
	from AutoTimerComponent import preferredAutoTimerComponent
	from AutoTimerImporter import AutoTimerImporter
	from plugin import autotimer

	# Create instance if needed
	if autotimer is None:
		from AutoTimer import AutoTimer
		autotimer = AutoTimer()
		autotimer.readXml()

	match = evt and evt.getEventName() or ""
	name = match or "New AutoTimer"
	sref = None
	if service is not None:
		service = str(service)
		myref = eServiceReference(service)
		if not (myref.flags & eServiceReference.isGroup):
			# strip all after last :
			pos = service.rfind(':')
			if pos != -1:
				if service[pos-1] == ':':
					pos -= 1
				service = service[:pos+1]

		sref = ServiceReference(myref)
	if evt:
		# timespan defaults to +- 1h
		begin = evt.getBeginTime()-3600
		end = begin + evt.getDuration()+7200
	else:
		begin = end = 0

	# XXX: we might want to make sure that we actually collected any data because the importer does not do so :-)

	session.openWithCallback(
		importerCallback,
		AutoTimerImporter,
		preferredAutoTimerComponent(
			autotimer.getUniqueId(),
			name,
			'',		# Match
			True	# Enabled
		),
		match,		# Proposed Match
		begin,		# Proposed Begin
		end,		# Proposed End
		None,		# Proposed Disabled
		sref,		# Proposed ServiceReference
		None,		# Proposed afterEvent
		None,		# Proposed justplay
		None,		# Proposed dirname, can we get anything useful here?
		[]			# Proposed tags
	)
def parseConfig(configuration, list, version=None, uniqueTimerId=0, defaultTimer=None):
    if version != CURRENT_CONFIG_VERSION:
        parseConfigOld(configuration, list, uniqueTimerId)
        return

    if defaultTimer is not None:
        # Read in defaults for a new timer
        for defaults in configuration.findall("defaults"):
            parseEntry(defaults, defaultTimer, True)

    for timer in configuration.findall("timer"):
        uniqueTimerId += 1
        baseTimer = preferredAutoTimerComponent(uniqueTimerId, "", "", True)

        if parseEntry(timer, baseTimer):
            list.append(baseTimer)
	def __init__(self):
		# Initialize
		self.timers = []
		self.configMtime = -1
		self.uniqueTimerId = 0
		self.defaultTimer = preferredAutoTimerComponent(
			0,		# Id
			"",		# Name
			"",		# Match
			True 	# Enabled
		)
		self.epgcache = eEPGCache.getInstance()
		# Create dict of all movies in all folders used by an autotimer to compare with recordings
		self.serviceHandler = eServiceCenter.getInstance()
		self.moviedict = {}
		self.normalizedTimers = {}
		print "[AutoTimer] init ..."
Beispiel #12
0
def parseConfig(configuration,
                list,
                version=None,
                uniqueTimerId=0,
                defaultTimer=None):
    if version != CURRENT_CONFIG_VERSION:
        parseConfigOld(configuration, list, uniqueTimerId)
        return

    if defaultTimer is not None:
        # Read in defaults for a new timer
        for defaults in configuration.findall("defaults"):
            parseEntry(defaults, defaultTimer, True)

    for timer in configuration.findall("timer"):
        uniqueTimerId += 1
        baseTimer = preferredAutoTimerComponent(uniqueTimerId, '', '', True)

        if parseEntry(timer, baseTimer):
            list.append(baseTimer)
Beispiel #13
0
def parseConfigOld(configuration, list, uniqueTimerId = 0):
	print("[AutoTimer] Trying to parse old config")

	# Iterate Timers
	for timer in configuration.findall("timer"):
		# Increment uniqueTimerId
		uniqueTimerId += 1

		# Get name (V2+)
		name = timer.get("name")
		if name:
			name = name.encode("UTF-8")
		# Get name (= match) (V1)
		else:
			# Read out name
			name = getValue(timer.findall("name"), "").encode("UTF-8")

		if not name:
			print('[AutoTimer] Erroneous config is missing attribute "name", skipping entry')
			continue

		# Read out match (V3+)
		match = timer.get("match")
		if match:
			# Read out match
			match = match.encode("UTF-8")
			if not match:
				print('[AutoTimer] Erroneous config contains empty attribute "match", skipping entry')
				continue
		# V2-
		else:
			# Setting match to name
			match = name


		# See if Timer is ensabled (V2+)
		enabled = timer.get("enabled")
		if enabled:
			if enabled == "no":
				enabled = False
			elif enabled == "yes":
				enabled = True
			else:
				print('[AutoTimer] Erroneous config contains invalid value for "enabled":', enabled,', skipping entry')
				enabled = False
		# V1
		else:
			elements = timer.findall("enabled")
			if elements:
				if getValue(elements, "yes") == "no":
					enabled = False
				else:
					enabled = True
			else:
				enabled = True

		# Read out timespan (V4+; Falling back on missing definition should be OK)
		start = timer.get("from")
		end = timer.get("to")
		if start and end:
			start = [int(x) for x in start.split(':')]
			end = [int(x) for x in end.split(':')]
			timetuple = (start, end)
		# V3-
		else:
			elements = timer.findall("timespan")
			Len = len(elements)
			if Len:
				# Read out last definition
				start = elements[Len-1].get("from")
				end = elements[Len-1].get("to")
				if start and end:
					start = [int(x) for x in start.split(':')]
					end = [int(x) for x in end.split(':')]
					timetuple = (start, end)
				else:
					print('[AutoTimer] Erroneous config contains invalid definition of "timespan", ignoring definition')
					timetuple = None
			else:
				timetuple = None

		# Read out allowed services (V*)
		elements = timer.findall("serviceref")
		if elements:
			servicelist = []
			for service in elements:
				value = service.text
				if value:
					myref = eServiceReference(str(value))
					if not (myref.flags & eServiceReference.isGroup):
						# strip all after last :
						pos = value.rfind(':')
						if pos != -1:
							if value[pos-1] == ':':
								pos -= 1
							value = value[:pos+1]

					servicelist.append(value)
		else:
			servicelist = None

		# Read out allowed bouquets (V* though officially supported since V4)
		bouquets = []
		for bouquet in timer.findall("bouquet"):
			value = bouquet.text
			if value:
				bouquets.append(value)

		# Read out offset (V4+)
		offset = timer.get("offset")
		if offset:
			offset = offset.split(",")
			if len(offset) == 1:
				before = after = int(offset[0] or 0) * 60
			else:
				before = int(offset[0] or 0) * 60
				after = int(offset[1] or 0) * 60
			offset = (before, after)
		# V3-
		else:
			elements = timer.findall("offset")
			Len = len(elements)
			if Len:
				value = elements[Len-1].get("both")
				if value == '':
					before = int(elements[Len-1].get("before", 0)) * 60
					after = int(elements[Len-1].get("after", 0)) * 60
				else:
					before = after = int(value) * 60
				offset = (before, after)
			else:
				offset = None

		# Read out counter
		counter = int(timer.get("counter", '0'))
		counterLeft = int(timer.get("left", counter))
		counterLimit = timer.get("lastActivation")
		counterFormat = timer.get("counterFormat", "")
		lastBegin = int(timer.get("lastBegin", 0))

		# Read out justplay
		justplay = int(timer.get("justplay", '0'))
		setEndtime = int(timer.get("setEndtime", '1'))

		# Read out avoidDuplicateDescription
		avoidDuplicateDescription = int(timer.get("avoidDuplicateDescription", 0))
		searchForDuplicateDescription = int(timer.get("searchForDuplicateDescription", 3)) - 1
		if searchForDuplicateDescription < 0 or searchForDuplicateDescription > 2:
			searchForDuplicateDescription = 2

		# Read out afterevent (compatible to V* though behaviour for V3- is different as V4+ allows multiple afterevents while the last definication was chosen before)
		idx = {
			"none": AFTEREVENT.NONE,
			"deepstandby": AFTEREVENT.DEEPSTANDBY,
			"shutdown": AFTEREVENT.DEEPSTANDBY,
			"standby": AFTEREVENT.STANDBY,
			"auto": AFTEREVENT.AUTO
		}
		afterevent = []
		for element in timer.findall("afterevent"):
			value = element.text

			if value in idx:
				value = idx[value]
			else:
				print('[AutoTimer] Erroneous config contains invalid value for "afterevent":', afterevent,', ignoring definition')
				continue

			start = element.get("from")
			end = element.get("to")
			if start and end:
				start = [int(x) for x in start.split(':')]
				end = [int(x) for x in end.split(':')]
				afterevent.append((value, (start, end)))
			else:
				afterevent.append((value, None))

		# Read out exclude (V*)
		idx = {"title": 0, "shortdescription": 1, "description": 2, "dayofweek": 3}
		excludes = ([], [], [], [])
		for exclude in timer.findall("exclude"):
			where = exclude.get("where")
			value = exclude.text
			if not (value and where):
				continue

			if where in idx:
				excludes[idx[where]].append(value.encode("UTF-8"))

		# Read out includes (use same idx) (V4+ feature, should not harm V3-)
		includes = ([], [], [], [])
		for include in timer.findall("include"):
			where = include.get("where")
			value = include.text
			if not (value and where):
				continue

			if where in idx:
				includes[idx[where]].append(value.encode("UTF-8"))

		# Read out max length (V4+)
		maxlen = timer.get("maxduration")
		if maxlen:
			maxlen = int(maxlen)*60
		# V3-
		else:
			elements = timer.findall("maxduration")
			if elements:
				maxlen = getValue(elements, None)
				if maxlen is not None:
					maxlen = int(maxlen)*60
			else:
				maxlen = None

		# Read out recording path
		destination = timer.get("destination", "").encode("UTF-8") or None

		# Read out recording tags
		tags = []
		for tag in timer.findall("tag"):
			value = tag.text
			if not value:
				continue

			tags.append(value.encode("UTF-8"))

		# Finally append timer
		list.append(preferredAutoTimerComponent(
				uniqueTimerId,
				name,
				match,
				enabled,
				timespan = timetuple,
				services = servicelist,
				offset = offset,
				afterevent = afterevent,
				exclude = excludes,
				include = includes,
				maxduration = maxlen,
				destination = destination,
				matchCount = counter,
				matchLeft = counterLeft,
				matchLimit = counterLimit,
				matchFormatString = counterFormat,
				lastBegin = lastBegin,
				justplay = justplay,
				setEndtime = setEndtime,
				avoidDuplicateDescription = avoidDuplicateDescription,
				searchForDuplicateDescription = searchForDuplicateDescription,
				bouquets = bouquets,
				tags = tags
		))
def parseConfigOld(configuration, list, uniqueTimerId = 0):
	print("[AutoTimer] Trying to parse old config")

	# Iterate Timers
	for timer in configuration.findall("timer"):
		# Increment uniqueTimerId
		uniqueTimerId += 1

		# Get name (V2+)
		name = timer.get("name")
		if name:
			name = name.encode("UTF-8")
		# Get name (= match) (V1)
		else:
			# Read out name
			name = getValue(timer.findall("name"), "").encode("UTF-8")

		if not name:
			print('[AutoTimer] Erroneous config is missing attribute "name", skipping entry')
			continue

		# Read out match (V3+)
		match = timer.get("match")
		if match:
			# Read out match
			match = match.encode("UTF-8")
			if not match:
				print('[AutoTimer] Erroneous config contains empty attribute "match", skipping entry')
				continue
		# V2-
		else:
			# Setting match to name
			match = name


		# See if Timer is ensabled (V2+)
		enabled = timer.get("enabled")
		if enabled:
			if enabled == "no":
				enabled = False
			elif enabled == "yes":
				enabled = True
			else:
				print('[AutoTimer] Erroneous config contains invalid value for "enabled":', enabled,', skipping entry')
				enabled = False
		# V1
		else:
			elements = timer.findall("enabled")
			if elements:
				if getValue(elements, "yes") == "no":
					enabled = False
				else:
					enabled = True
			else:
				enabled = True

		# Read out timespan (V4+; Falling back on missing definition should be OK)
		start = timer.get("from")
		end = timer.get("to")
		if start and end:
			start = [int(x) for x in start.split(':')]
			end = [int(x) for x in end.split(':')]
			timetuple = (start, end)
		# V3-
		else:
			elements = timer.findall("timespan")
			Len = len(elements)
			if Len:
				# Read out last definition
				start = elements[Len-1].get("from")
				end = elements[Len-1].get("to")
				if start and end:
					start = [int(x) for x in start.split(':')]
					end = [int(x) for x in end.split(':')]
					timetuple = (start, end)
				else:
					print('[AutoTimer] Erroneous config contains invalid definition of "timespan", ignoring definition')
					timetuple = None
			else:
				timetuple = None

		# Read out allowed services (V*)
		elements = timer.findall("serviceref")
		if elements:
			servicelist = []
			for service in elements:
				value = service.text
				if value:
					myref = eServiceReference(str(value))
					if not (myref.flags & eServiceReference.isGroup):
						# strip all after last :
						pos = value.rfind(':')
						if pos != -1:
							if value[pos-1] == ':':
								pos -= 1
							value = value[:pos+1]

					servicelist.append(value)
		else:
			servicelist = None

		# Read out allowed bouquets (V* though officially supported since V4)
		bouquets = []
		for bouquet in timer.findall("bouquet"):
			value = bouquet.text
			if value:
				bouquets.append(value)

		# Read out offset (V4+)
		offset = timer.get("offset")
		if offset:
			offset = offset.split(",")
			if len(offset) == 1:
				before = after = int(offset[0] or 0) * 60
			else:
				before = int(offset[0] or 0) * 60
				after = int(offset[1] or 0) * 60
			offset = (before, after)
		# V3-
		else:
			elements = timer.findall("offset")
			Len = len(elements)
			if Len:
				value = elements[Len-1].get("both")
				if value == '':
					before = int(elements[Len-1].get("before", 0)) * 60
					after = int(elements[Len-1].get("after", 0)) * 60
				else:
					before = after = int(value) * 60
				offset = (before, after)
			else:
				offset = None

		# Read out counter
		counter = int(timer.get("counter", '0'))
		counterLeft = int(timer.get("left", counter))
		counterLimit = timer.get("lastActivation")
		counterFormat = timer.get("counterFormat", "")
		lastBegin = int(timer.get("lastBegin", 0))

		# Read out justplay
		justplay = int(timer.get("justplay", '0'))
		setEndtime = int(timer.get("setEndtime", '1'))

		# Read out avoidDuplicateDescription
		avoidDuplicateDescription = int(timer.get("avoidDuplicateDescription", 0))
		searchForDuplicateDescription = int(timer.get("searchForDuplicateDescription", 3)) - 1
		if searchForDuplicateDescription < 0 or searchForDuplicateDescription > 2:
			searchForDuplicateDescription = 2

		# Read out afterevent (compatible to V* though behaviour for V3- is different as V4+ allows multiple afterevents while the last definication was chosen before)
		idx = {
			"none": AFTEREVENT.NONE,
			"deepstandby": AFTEREVENT.DEEPSTANDBY,
			"shutdown": AFTEREVENT.DEEPSTANDBY,
			"standby": AFTEREVENT.STANDBY,
			"auto": AFTEREVENT.AUTO
		}
		afterevent = []
		for element in timer.findall("afterevent"):
			value = element.text

			if value in idx:
				value = idx[value]
			else:
				print('[AutoTimer] Erroneous config contains invalid value for "afterevent":', afterevent,', ignoring definition')
				continue

			start = element.get("from")
			end = element.get("to")
			if start and end:
				start = [int(x) for x in start.split(':')]
				end = [int(x) for x in end.split(':')]
				afterevent.append((value, (start, end)))
			else:
				afterevent.append((value, None))

		# Read out exclude (V*)
		idx = {"title": 0, "shortdescription": 1, "description": 2, "dayofweek": 3}
		excludes = ([], [], [], [])
		for exclude in timer.findall("exclude"):
			where = exclude.get("where")
			value = exclude.text
			if not (value and where):
				continue

			if where in idx:
				excludes[idx[where]].append(value.encode("UTF-8"))

		# Read out includes (use same idx) (V4+ feature, should not harm V3-)
		includes = ([], [], [], [])
		for include in timer.findall("include"):
			where = include.get("where")
			value = include.text
			if not (value and where):
				continue

			if where in idx:
				includes[idx[where]].append(value.encode("UTF-8"))

		# Read out max length (V4+)
		maxlen = timer.get("maxduration")
		if maxlen:
			maxlen = int(maxlen)*60
		# V3-
		else:
			elements = timer.findall("maxduration")
			if elements:
				maxlen = getValue(elements, None)
				if maxlen is not None:
					maxlen = int(maxlen)*60
			else:
				maxlen = None

		# Read out recording path
		destination = timer.get("destination", "").encode("UTF-8") or None

		# Read out recording tags
		tags = []
		for tag in timer.findall("tag"):
			value = tag.text
			if not value:
				continue

			tags.append(value.encode("UTF-8"))

		# Finally append timer
		list.append(preferredAutoTimerComponent(
				uniqueTimerId,
				name,
				match,
				enabled,
				timespan = timetuple,
				services = servicelist,
				offset = offset,
				afterevent = afterevent,
				exclude = excludes,
				include = includes,
				maxduration = maxlen,
				destination = destination,
				matchCount = counter,
				matchLeft = counterLeft,
				matchLimit = counterLimit,
				matchFormatString = counterFormat,
				lastBegin = lastBegin,
				justplay = justplay,
				setEndtime = setEndtime,
				avoidDuplicateDescription = avoidDuplicateDescription,
				searchForDuplicateDescription = searchForDuplicateDescription,
				bouquets = bouquets,
				tags = tags
		))
def addAutotimerFromService(session, service = None):
	from AutoTimerComponent import preferredAutoTimerComponent
	from AutoTimerImporter import AutoTimerImporter
	from plugin import autotimer

	# Create instance if needed
	if autotimer is None:
		from AutoTimer import AutoTimer
		autotimer = AutoTimer()
		autotimer.readXml()

	serviceHandler = eServiceCenter.getInstance()
	info = serviceHandler.info(service)

	match = info and info.getName(service) or ""
	name = match or "New AutoTimer"
	sref = info and info.getInfoString(service, iServiceInformation.sServiceref)
	if sref:
		# strip all after last :
		pos = sref.rfind(':')
		if pos != -1:
			if sref[pos-1] == ':':
				pos -= 1
			sref = sref[:pos+1]

		sref = ServiceReference(sref)
	if info:
		begin = info.getInfo(service, iServiceInformation.sTimeCreate)
		end = begin + info.getLength(service)
	else:
		begin = end = 0

	from os.path import dirname
	path = dirname(service.getPath())
	if not path == '/':
		path += '/'

	tags = info.getInfoString(service, iServiceInformation.sTags)
	tags = tags and tags.split(' ') or []

	# XXX: we might want to make sure that we actually collected any data because the importer does not do so :-)

	session.openWithCallback(
		importerCallback,
		AutoTimerImporter,
		preferredAutoTimerComponent(
			autotimer.getUniqueId(),
			name,
			'',		# Match
			True	# Enabled
		),
		match,		# Proposed Match
		begin,		# Proposed Begin
		end,		# Proposed End
		None,		# Proposed Disabled
		sref,		# Proposed ServiceReference
		None,		# Proposed afterEvent
		None,		# Proposed justplay
		path,		# Proposed dirname
		tags		# Proposed tags
	)
	def readXml(self, **kwargs):
		if "xml_string" in kwargs:
			# reset time
			self.configMtime = -1
			# Parse Config
			configuration = cet_fromstring(kwargs["xml_string"])
			# TODO : check config and create backup if wrong
		else:

			# Abort if no config found
			if not os_path.exists(XML_CONFIG):
				print("[AutoTimer] No configuration file present")
				return
	
			# Parse if mtime differs from whats saved
			mtime = os_path.getmtime(XML_CONFIG)
			if mtime == self.configMtime:
				print("[AutoTimer] No changes in configuration, won't parse")
				return
	
			# Save current mtime
			self.configMtime = mtime
	
			# Parse Config
			try:
				configuration = cet_parse(XML_CONFIG).getroot()
			except:
				try:
					if os_path.exists(XML_CONFIG + "_old"):
						os_rename(XML_CONFIG + "_old", XML_CONFIG + "_old(1)")
					os_rename(XML_CONFIG, XML_CONFIG + "_old")
					print("[AutoTimer] autotimer.xml is corrupt rename file to /etc/enigma2/autotimer.xml_old")
				except:
					pass
				if Standby.inStandby is None:
					AddPopup(_("The autotimer file (/etc/enigma2/autotimer.xml) is corrupt. A new and empty config was created. A backup of the config can be found here (/etc/enigma2/autotimer.xml_old) "), type = MessageBox.TYPE_ERROR, timeout = 0, id = "AutoTimerLoadFailed")
	
				self.timers = []
				self.defaultTimer = preferredAutoTimerComponent(
					0,		# Id
					"",		# Name
					"",		# Match
					True	# Enabled
				)
	
				try:
					self.writeXml()
					configuration = cet_parse(XML_CONFIG).getroot()
				except:
					print("[AutoTimer] fatal error, the autotimer.xml cannot create")
					return

		# Empty out timers and reset Ids
		del self.timers[:]
		self.defaultTimer.clear(-1, True)

		parseConfig(
			configuration,
			self.timers,
			configuration.get("version"),
			0,
			self.defaultTimer
		)
		self.uniqueTimerId = len(self.timers)
def addAutotimerFromService(session, service = None):
	from AutoTimerComponent import preferredAutoTimerComponent
	from AutoTimerImporter import AutoTimerImporter
	from plugin import autotimer

	# Create instance if needed
	if autotimer is None:
		from AutoTimer import AutoTimer
		autotimer = AutoTimer()
		autotimer.readXml()

	serviceHandler = eServiceCenter.getInstance()
	info = serviceHandler.info(service)

	match = info and info.getName(service) or ""
	name = match or "New AutoTimer"
	sref = info and info.getInfoString(service, iServiceInformation.sServiceref)
	if sref:
		# strip all after last :
		pos = sref.rfind(':')
		if pos != -1:
			if sref[pos-1] == ':':
				pos -= 1
			sref = sref[:pos+1]

		sref = ServiceReference(sref)
	if info:
		begin = info.getInfo(service, iServiceInformation.sTimeCreate)
		end = begin + info.getLength(service)
	else:
		begin = end = 0

	from os.path import dirname
	path = dirname(service.getPath())
	if not path == '/':
		path += '/'

	tags = info.getInfoString(service, iServiceInformation.sTags)
	tags = tags and tags.split(' ') or []

	# XXX: we might want to make sure that we actually collected any data because the importer does not do so :-)

	session.openWithCallback(
		importerCallback,
		AutoTimerImporter,
		preferredAutoTimerComponent(
			autotimer.getUniqueId(),
			name,
			'',		# Match
			True	# Enabled
		),
		match,		# Proposed Match
		begin,		# Proposed Begin
		end,		# Proposed End
		None,		# Proposed Disabled
		sref,		# Proposed ServiceReference
		None,		# Proposed afterEvent
		None,		# Proposed justplay
		path,		# Proposed dirname
		tags		# Proposed tags
	)