Optimized execution time
[enigma2-plugins.git] / autotimer / src / AutoTimer.py
1 # Plugins Config
2 from xml.etree.cElementTree import parse as cet_parse
3 from os import path as os_path
4 from AutoTimerConfiguration import parseConfig, buildConfig
5
6 # Navigation (RecordTimer)
7 import NavigationInstance
8
9 # Timer
10 from ServiceReference import ServiceReference
11 from RecordTimer import RecordTimerEntry
12 from Components.TimerSanityCheck import TimerSanityCheck
13
14 # Timespan
15 from time import localtime, strftime, time, mktime
16 from datetime import timedelta, date
17
18 # EPGCache & Event
19 from enigma import eEPGCache, eServiceReference, eServiceCenter, iServiceInformation
20
21 # Enigma2 Config
22 from Components.config import config
23
24 # AutoTimer Component
25 from AutoTimerComponent import preferredAutoTimerComponent
26
27 from itertools import chain
28 from collections import defaultdict
29
30 XML_CONFIG = "/etc/enigma2/autotimer.xml"
31
32 def getTimeDiff(timer, begin, end):
33         if begin <= timer.begin <= end:
34                 return end - timer.begin
35         elif timer.begin <= begin <= timer.end:
36                 return timer.end - begin
37         return 0
38
39 typeMap = {
40         "exact": eEPGCache.EXAKT_TITLE_SEARCH,
41         "partial": eEPGCache.PARTIAL_TITLE_SEARCH
42 }
43
44 caseMap = {
45         "sensitive": eEPGCache.CASE_CHECK,
46         "insensitive": eEPGCache.NO_CASE_CHECK
47 }
48
49 class AutoTimer:
50         """Read and save xml configuration, query EPGCache"""
51
52         def __init__(self):
53                 # Initialize
54                 self.timers = []
55                 self.configMtime = -1
56                 self.uniqueTimerId = 0
57                 self.defaultTimer = preferredAutoTimerComponent(
58                         0,              # Id
59                         "",             # Name
60                         "",             # Match
61                         True    # Enabled
62                 )
63
64 # Configuration
65
66         def readXml(self):
67                 # Abort if no config found
68                 if not os_path.exists(XML_CONFIG):
69                         print "[AutoTimer] No configuration file present"
70                         return
71
72                 # Parse if mtime differs from whats saved
73                 mtime = os_path.getmtime(XML_CONFIG)
74                 if mtime == self.configMtime:
75                         print "[AutoTimer] No changes in configuration, won't parse"
76                         return
77
78                 # Save current mtime
79                 self.configMtime = mtime
80
81                 # Parse Config
82                 configuration = cet_parse(XML_CONFIG).getroot()
83
84                 # Empty out timers and reset Ids
85                 del self.timers[:]
86                 self.defaultTimer.clear(-1, True)
87
88                 parseConfig(
89                         configuration,
90                         self.timers,
91                         configuration.get("version"),
92                         0,
93                         self.defaultTimer
94                 )
95                 self.uniqueTimerId = len(self.timers)
96
97         def getXml(self):
98                 return buildConfig(self.defaultTimer, self.timers, webif = True)
99
100         def writeXml(self):
101                 file = open(XML_CONFIG, 'w')
102                 file.writelines(buildConfig(self.defaultTimer, self.timers))
103                 file.close()
104
105 # Manage List
106
107         def add(self, timer):
108                 self.timers.append(timer)
109
110         def getEnabledTimerList(self):
111                 return (x for x in self.timers if x.enabled)
112
113         def getTimerList(self):
114                 return self.timers
115
116         def getTupleTimerList(self):
117                 lst = self.timers
118                 return [(x,) for x in lst]
119
120         def getSortedTupleTimerList(self):
121                 lst = self.timers[:]
122                 lst.sort()
123                 return [(x,) for x in lst]
124
125         def getUniqueId(self):
126                 self.uniqueTimerId += 1
127                 return self.uniqueTimerId
128
129         def remove(self, uniqueId):
130                 idx = 0
131                 for timer in self.timers:
132                         if timer.id == uniqueId:
133                                 self.timers.pop(idx)
134                                 return
135                         idx += 1
136
137         def set(self, timer):
138                 idx = 0
139                 for stimer in self.timers:
140                         if stimer == timer:
141                                 self.timers[idx] = timer
142                                 return
143                         idx += 1
144                 self.timers.append(timer)
145
146 # Main function
147
148         def parseEPG(self, simulateOnly = False):
149                 if NavigationInstance.instance is None:
150                         print "[AutoTimer] Navigation is not available, can't parse EPG"
151                         return (0, 0, 0, [], [], [])
152
153                 total = 0
154                 new = 0
155                 modified = 0
156                 timers = []
157                 conflicting = []
158                 similar = {}                    # Contains the the marked similar servicerefs and the conflicting string
159                 similars = []                   # Contains the added similar timers 
160
161                 # NOTE: the config option specifies "the next X days" which means today (== 1) + X
162                 delta = timedelta(days = config.plugins.autotimer.maxdaysinfuture.value + 1)
163                 evtLimit = mktime((date.today() + delta).timetuple())
164                 checkEvtLimit = delta.days > 1
165                 del delta
166
167                 # Read AutoTimer configuration
168                 self.readXml()
169
170                 # Get E2 instances
171                 epgcache = eEPGCache.getInstance()
172                 serviceHandler = eServiceCenter.getInstance()
173                 recordHandler = NavigationInstance.instance.RecordTimer
174
175                 # Create dict of all movies in all folders used by an autotimer to compare with recordings
176                 # The moviedict will be filled only if one AutoTimer is configured to avoid duplicate description for any recordings
177                 moviedict = defaultdict(list)
178
179                 # Save Recordings in a dict to speed things up a little
180                 # We include processed timers as we might search for duplicate descriptions
181                 # The recordict is always filled
182                 recorddict = defaultdict(list)
183                 for timer in ( recordHandler.timer_list + recordHandler.processed_timers ):
184                         if timer and timer.service_ref:
185                                 event = epgcache.lookupEventId(timer.service_ref.ref, timer.eit)
186                                 extdesc = event and event.getExtendedDescription()
187                                 timer.extdesc = extdesc
188                                 recorddict[str(timer.service_ref)].append(timer)
189
190                 # Iterate Timer
191                 for timer in self.getEnabledTimerList():
192                         # Precompute timer destination dir
193                         dest = timer.destination or config.usage.default_path.value
194
195                         # Workaround to allow search for umlauts if we know the encoding
196                         match = timer.match
197                         if timer.encoding != 'UTF-8':
198                                 try:
199                                         match = match.decode('UTF-8').encode(timer.encoding)
200                                 except UnicodeDecodeError:
201                                         pass
202
203                         # Search EPG, default to empty list
204                         epgmatches = epgcache.search(('RITBDSE', 500, typeMap[timer.searchType], match, caseMap[timer.searchCase])) or []
205                         # Sort list of tuples by begin time 'B'
206                         epgmatches.sort(key = lambda x: x[3]) 
207
208                         # Reset the the marked similar servicerefs
209                         similar.clear()
210
211                         # Loop over all EPG matches
212                         for idx, ( serviceref, eit, name, begin, duration, shortdesc, extdesc ) in enumerate( epgmatches ):
213
214                                 # Reset similarMatch and conflictString
215                                 similarMatch = False
216                                 conflictString = ""
217                                 
218                                 # Check if serviceref is in similar matches list
219                                 if serviceref in similar:
220                                         similarMatch = True
221                                         conflictString = similar[serviceref]
222                                         del similar[serviceref]
223
224                                 eserviceref = eServiceReference(serviceref)
225                                 evt = epgcache.lookupEventId(eserviceref, eit)
226                                 if not evt:
227                                         print "[AutoTimer] Could not create Event!"
228                                         continue
229
230                                 # Try to determine real service (we always choose the last one)
231                                 n = evt.getNumOfLinkageServices()
232                                 if n > 0:
233                                         i = evt.getLinkageService(eserviceref, n-1)
234                                         serviceref = i.toString()
235
236                                 evtBegin = begin
237                                 evtEnd = end = begin + duration
238                                 
239                                 # If event starts in less than 60 seconds skip it
240                                 if begin < time() + 60:
241                                         print "[AutoTimer] Skipping an event because it starts in less than 60 seconds"
242                                         continue
243
244                                 # If maximum days in future is set then check time
245                                 if checkEvtLimit:
246                                         if begin > evtLimit:
247                                                 continue
248
249                                 # Convert begin time
250                                 timestamp = localtime(begin)
251                                 # Update timer
252                                 timer.update(begin, timestamp)
253
254                                 # Check Duration, Timespan, Timeframe and Excludes
255                                 # Remove similarMatch if You want perform the check also on similar timers
256                                 if timer.checkServices(serviceref) \
257                                         or timer.checkDuration(duration) \
258                                         or ( not similarMatch and timer.checkTimespan(timestamp) ) \
259                                         or ( not similarMatch and timer.checkTimeframe(begin) ) \
260                                         or timer.checkFilter(name, shortdesc, extdesc, ( not similarMatch and str(timestamp.tm_wday) ) ):
261                                         continue
262
263                                 if timer.hasOffset():
264                                         # Apply custom Offset
265                                         begin, end = timer.applyOffset(begin, end)
266                                 else:
267                                         # Apply E2 Offset
268                                         begin -= config.recording.margin_before.value * 60
269                                         end += config.recording.margin_after.value * 60
270
271                                 # Eventually change service to alternative
272                                 if timer.overrideAlternatives:
273                                         serviceref = timer.getAlternative(serviceref)
274
275                                 total += 1
276
277                                 # Append to timerlist and abort if simulating
278                                 #if not similarMatch: # Do we want the similar timers in the timers list?
279                                 timers.append((name, begin, end, serviceref, timer.name))
280                                 if simulateOnly:
281                                         continue
282
283                                 # Check for existing recordings in directory
284                                 if timer.avoidDuplicateDescription == 3:
285                                         # Reset movie Exists
286                                         movieExists = False
287
288                                         # Eventually create cache
289                                         if dest and dest not in moviedict:
290                                                 movielist = serviceHandler.list(eServiceReference("2:0:1:0:0:0:0:0:0:0:" + dest))
291                                                 if movielist is None:
292                                                         print "[AutoTimer] listing of movies in " + dest + " failed"
293                                                 else:
294                                                         append = moviedict[dest].append
295                                                         while 1:
296                                                                 movieref = movielist.getNext()
297                                                                 if not movieref.valid():
298                                                                         break
299                                                                 if movieref.flags & eServiceReference.mustDescent:
300                                                                         continue
301                                                                 info = serviceHandler.info(movieref)
302                                                                 if info is None:
303                                                                         continue
304                                                                 event = info.getEvent(movieref)
305                                                                 if event is None:
306                                                                         continue
307                                                                 append({
308                                                                         "name": info.getName(movieref),
309                                                                         "shortdesc": info.getInfoString(movieref, iServiceInformation.sDescription),
310                                                                         "extdesc": event.getExtendedDescription()
311                                                                 })
312                                                         del append
313
314                                         for movieinfo in moviedict.get(dest, []):
315                                                 if movieinfo.get("name") == name \
316                                                         and movieinfo.get("shortdesc") == shortdesc \
317                                                         and movieinfo.get("extdesc") == extdesc:
318                                                         print "[AutoTimer] We found a matching recorded movie, skipping event:", name
319                                                         movieExists = True
320                                                         break
321
322                                         if movieExists:
323                                                 continue
324
325                                 # Initialize
326                                 newEntry = None
327                                 oldExists = False
328                                 similarExists = False           # Indicates if we found a matching similar timer
329
330                                 # Check for double Timers
331                                 # We first check eit and if user wants us to guess event based on time
332                                 # we try this as backup. The allowed diff should be configurable though.
333                                 for rtimer in recorddict.get(serviceref, []):
334                                         if rtimer.eit == eit or config.plugins.autotimer.try_guessing.value and getTimeDiff(rtimer, evtBegin, evtEnd) > ((duration/10)*8):
335                                                 oldExists = True
336
337                                                 # Abort if we don't want to modify timers or timer is repeated
338                                                 if config.plugins.autotimer.refresh.value == "none" or rtimer.repeated:
339                                                         print "[AutoTimer] Won't modify existing timer because either no modification allowed or repeated timer"
340                                                         break
341
342                                                 if hasattr(rtimer, "isAutoTimer"):
343                                                         rtimer.log(501, "[AutoTimer] AutoTimer %s modified this automatically generated timer." % (timer.name,))
344                                                 else:
345                                                         if config.plugins.autotimer.refresh.value != "all":
346                                                                 print "[AutoTimer] Won't modify existing timer because it's no timer set by us"
347                                                                 break
348
349                                                         rtimer.log(501, "[AutoTimer] Warning, AutoTimer %s messed with a timer which might not belong to it." % (timer.name,))
350
351                                                 newEntry = rtimer
352                                                 modified += 1
353
354                                                 # Modify values saved in timer
355                                                 newEntry.name = name
356                                                 newEntry.description = shortdesc
357                                                 newEntry.begin = int(begin)
358                                                 newEntry.end = int(end)
359                                                 newEntry.service_ref = ServiceReference(serviceref)
360
361                                                 # Don't store the extended description within the timer
362                                                 if hasattr(newEntry, "extdesc"):
363                                                         del newEntry.extdesc
364
365                                                 break
366                                         elif timer.avoidDuplicateDescription >= 1 \
367                                                 and not rtimer.disabled \
368                                                 and rtimer.name == name \
369                                                 and rtimer.description == shortdesc \
370                                                 and hasattr(rtimer, "extdesc") and rtimer.extdesc == extdesc:
371                                                 oldExists = True
372                                                 print "[AutoTimer] We found a timer (similar service) with same description, skipping event"
373                                                 break
374
375                                 # We found no timer we want to edit
376                                 if newEntry is None:
377                                         # But there is a match
378                                         if oldExists:
379                                                 continue
380
381                                         # We want to search for possible doubles
382                                         if timer.avoidDuplicateDescription >= 2:
383                                                 for rtimer in list( chain.from_iterable( recorddict.values() ) ):
384                                                         if not rtimer.disabled \
385                                                                 and rtimer.name == name \
386                                                                 and rtimer.description == shortdesc \
387                                                                 and hasattr(rtimer, "extdesc") and rtimer.extdesc == extdesc:
388                                                                 oldExists = True
389                                                                 print "[AutoTimer] We found a timer (any service) with same description, skipping event"
390                                                                 break
391                                                 if oldExists:
392                                                         continue
393
394                                         if timer.checkCounter(timestamp):
395                                                 print "[AutoTimer] Not adding new timer because counter is depleted."
396                                                 continue
397
398                                         newEntry = RecordTimerEntry(ServiceReference(serviceref), begin, end, name, shortdesc, eit)
399                                         newEntry.log(500, "[AutoTimer] Adding new timer based on AutoTimer %s." % (timer.name,))
400
401                                         # Mark this entry as AutoTimer (only AutoTimers will have this Attribute set)
402                                         newEntry.isAutoTimer = True
403
404                                 # Apply afterEvent
405                                 if timer.hasAfterEvent():
406                                         afterEvent = timer.getAfterEventTimespan(localtime(end))
407                                         if afterEvent is None:
408                                                 afterEvent = timer.getAfterEvent()
409                                         if afterEvent is not None:
410                                                 newEntry.afterEvent = afterEvent
411
412                                 newEntry.dirname = timer.destination
413                                 newEntry.justplay = timer.justplay
414                                 newEntry.tags = timer.tags
415                                 newEntry.vpsplugin_enabled = timer.vps_enabled
416                                 newEntry.vpsplugin_overwrite = timer.vps_overwrite
417
418                                 if oldExists:
419                                         # XXX: this won't perform a sanity check, but do we actually want to do so?
420                                         recordHandler.timeChanged(newEntry)
421                                 else:
422                                         if similarMatch:
423                                                 newEntry.log(504, "[AutoTimer] Similar Timer is added because of conflicts with %s." % (conflictString))
424                                         conflicts = recordHandler.record(newEntry)
425
426                                         if conflicts:
427                                                 conflictString += ' / '.join(["%s (%s)" % (x.name, strftime("%Y%m%d %H%M", localtime(x.begin))) for x in conflicts])
428
429                                         if conflicts and config.plugins.autotimer.addsimilar_on_conflict.value:
430                                                 # We start our search right after our actual index
431                                                 for servicerefS, eitS, nameS, beginS, durationS, shortdescS, extdescS in epgmatches[idx+1:]:
432                                                         if evtBegin < beginS:
433                                                                 # Match must be after our conflicting event
434                                                                 if extdesc == extdescS and shortdesc == shortdescS:
435                                                                         # Match only if the descriptions are equal
436                                                                         print "[AutoTimer] Found similar Timer: " + name
437                                                                         
438                                                                         # Indicate that there exists a similar timer
439                                                                         similarExists = True
440                                                                         # Store the similar serviceref and conflictString, so it can be handled later
441                                                                         similar[servicerefS] = conflictString
442                                                                         
443                                                                         # If this one also will conflict and there are more matches, they will be marked the next time 
444                                                                         break
445
446                                         if conflicts and config.plugins.autotimer.disabled_on_conflict.value and not similarExists:                     # Don't add disabled timer if a similar timer exists
447                                         #if conflicts and config.plugins.autotimer.disabled_on_conflict.value:                                                                                                  # Add disabled timer even if a similar timer exists
448                                                 newEntry.log(503, "[AutoTimer] Timer disabled because of conflicts with %s." % (conflictString,))
449                                                 newEntry.disabled = True
450                                                 # We might want to do the sanity check locally so we don't run it twice - but I consider this workaround a hack anyway
451                                                 conflicts = recordHandler.record(newEntry)
452                                                 conflicting.append((name, begin, end, serviceref, timer.name))
453
454                                         if conflicts is None:                                                                                   # Similar timers will be added to the new timer list
455                                         #if conflicts is None and not similarMatch: # Similar timers won't be added to the new timer list
456                                                 timer.decrementCounter()
457                                                 new += 1
458                                                 timer.extdesc = extdesc
459                                                 recorddict[serviceref].append(newEntry)
460
461                                         elif conflicts:                                                                                                                 # Conflicting timers will be added also if a similar timer exists
462                                         #elif conflicts and not similarExists:                  # Conflicting timers won't be added if a similar timer exists
463                                                 conflicting.append((name, begin, end, serviceref, timer.name))
464
465                                         if similarMatch and conflicts is None:                  # Similar timers can be in new timers list and additionally in similar timers list
466                                         #elif similarMatch and conflicts is None:               # Similar timers will be only in new timers list or similar timers list
467                                                 similars.append((name, begin, end, serviceref, timer.name))
468
469                 return (total, new, modified, timers, conflicting, similars)