Added comments
[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 = defaultdict(list)                     # Contains the the marked similar eits and the conflicting strings
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                 # Save Recordings in a dict to speed things up a little
176                 # We include processed timers as we might search for duplicate descriptions
177                 # The recordict is always filled
178                 #Question: It might be better to name it timerdict
179                 #Question: Move to a separate function getTimerDict()
180                 #Note: It is also possible to use RecordTimer isInTimer(), but we won't get the timer itself on a match 
181                 recorddict = defaultdict(list)
182                 for timer in ( recordHandler.timer_list + recordHandler.processed_timers ):
183                         if timer and timer.service_ref:
184                                 event = epgcache.lookupEventId(timer.service_ref.ref, timer.eit)
185                                 extdesc = event and event.getExtendedDescription()
186                                 timer.extdesc = extdesc
187                                 recorddict[str(timer.service_ref)].append(timer)
188
189                 # Create dict of all movies in all folders used by an autotimer to compare with recordings
190                 # The moviedict will be filled only if one AutoTimer is configured to avoid duplicate description for any recordings
191                 #Question: It might be better to name it recorddict
192                 moviedict = defaultdict(list)
193
194                 # Iterate Timer
195                 for timer in self.getEnabledTimerList():
196                         # Precompute timer destination dir
197                         dest = timer.destination or config.usage.default_path.value
198
199                         # Workaround to allow search for umlauts if we know the encoding
200                         match = timer.match
201                         if timer.encoding != 'UTF-8':
202                                 try:
203                                         match = match.decode('UTF-8').encode(timer.encoding)
204                                 except UnicodeDecodeError:
205                                         pass
206
207                         # Search EPG, default to empty list
208                         epgmatches = epgcache.search(('RITBDSE', 500, typeMap[timer.searchType], match, caseMap[timer.searchCase])) or []
209                         # Sort list of tuples by begin time 'B'
210                         epgmatches.sort(key = lambda x: x[3]) 
211
212                         # Reset the the marked similar servicerefs
213                         similar.clear()
214
215                         # Loop over all EPG matches
216                         for idx, ( serviceref, eit, name, begin, duration, shortdesc, extdesc ) in enumerate( epgmatches ):
217
218                                 #Question: Do we need this? 
219                                 #Question: Move to separate function getRealService()
220                                 eserviceref = eServiceReference(serviceref)
221                                 evt = epgcache.lookupEventId(eserviceref, eit)
222                                 if not evt:
223                                         print "[AutoTimer] Could not create Event!"
224                                         continue
225                                 # Try to determine real service (we always choose the last one)
226                                 n = evt.getNumOfLinkageServices()
227                                 if n > 0:
228                                         i = evt.getLinkageService(eserviceref, n-1)
229                                         serviceref = i.toString()
230
231                                 evtBegin = begin
232                                 evtEnd = end = begin + duration
233
234                                 # If event starts in less than 60 seconds skip it
235                                 if begin < time() + 60:
236                                         print "[AutoTimer] Skipping an event because it starts in less than 60 seconds"
237                                         continue
238
239                                 # If maximum days in future is set then check time
240                                 if checkEvtLimit:
241                                         if begin > evtLimit:
242                                                 continue
243
244                                 # Convert begin time
245                                 timestamp = localtime(begin)
246                                 # Update timer
247                                 timer.update(begin, timestamp)
248
249                                 # Check if eit is in similar matches list
250                                 similarTimer = False
251                                 if eit in similar:
252                                         similarTimer = True
253
254                                 # Check timer conditions
255                                 if not similarTimer:
256                                         # Check Duration, Timespan, Timeframe and Excludes
257                                         if timer.checkServices(serviceref) \
258                                                 or timer.checkDuration(duration) \
259                                                 or timer.checkTimespan(timestamp) \
260                                                 or timer.checkTimeframe(begin) \
261                                                 or timer.checkFilter(name, shortdesc, extdesc, str(timestamp.tm_wday)):
262                                                 continue
263                                 else:
264                                         # Check Duration and Excludes except dayofweek 
265                                         if timer.checkServices(serviceref) \
266                                                 or timer.checkDuration(duration) \
267                                                 or timer.checkFilter(name, shortdesc, extdesc, None):
268                                                 continue
269
270                                 if timer.hasOffset():
271                                         # Apply custom Offset
272                                         begin, end = timer.applyOffset(begin, end)
273                                 else:
274                                         # Apply E2 Offset
275                                         begin -= config.recording.margin_before.value * 60
276                                         end += config.recording.margin_after.value * 60
277
278                                 # Eventually change service to alternative
279                                 if timer.overrideAlternatives:
280                                         serviceref = timer.getAlternative(serviceref)
281
282                                 total += 1
283
284                                 # Append to timerlist and abort if simulating
285                                 timers.append((name, begin, end, serviceref, timer.name))
286                                 if simulateOnly:
287                                         continue
288
289                                 # Check for existing recordings in directory
290                                 if timer.avoidDuplicateDescription == 3:
291                                         # Reset movie Exists
292                                         movieExists = False
293
294                                         # Eventually create cache
295                                         if dest and dest not in moviedict:
296                                                 #Question: Move to a separate function getRecordDict()
297                                                 movielist = serviceHandler.list(eServiceReference("2:0:1:0:0:0:0:0:0:0:" + dest))
298                                                 if movielist is None:
299                                                         print "[AutoTimer] listing of movies in " + dest + " failed"
300                                                 else:
301                                                         append = moviedict[dest].append
302                                                         while 1:
303                                                                 movieref = movielist.getNext()
304                                                                 if not movieref.valid():
305                                                                         break
306                                                                 if movieref.flags & eServiceReference.mustDescent:
307                                                                         continue
308                                                                 info = serviceHandler.info(movieref)
309                                                                 if info is None:
310                                                                         continue
311                                                                 event = info.getEvent(movieref)
312                                                                 if event is None:
313                                                                         continue
314                                                                 append({
315                                                                         "name": info.getName(movieref),
316                                                                         "shortdesc": info.getInfoString(movieref, iServiceInformation.sDescription),
317                                                                         "extdesc": event.getExtendedDescription()
318                                                                 })
319                                                         del append
320
321                                         for movieinfo in moviedict.get(dest, []):
322                                                 if movieinfo.get("name") == name \
323                                                         and movieinfo.get("shortdesc") == shortdesc \
324                                                         and movieinfo.get("extdesc") == extdesc:
325                                                         print "[AutoTimer] We found a matching recorded movie, skipping event:", name
326                                                         movieExists = True
327                                                         break
328
329                                         if movieExists:
330                                                 continue
331
332                                 # Initialize
333                                 newEntry = None
334                                 oldExists = False
335
336                                 # Check for double Timers
337                                 # We first check eit and if user wants us to guess event based on time
338                                 # we try this as backup. The allowed diff should be configurable though.
339                                 for rtimer in recorddict.get(serviceref, []):
340                                         if rtimer.eit == eit or config.plugins.autotimer.try_guessing.value and getTimeDiff(rtimer, evtBegin, evtEnd) > ((duration/10)*8):
341                                                 oldExists = True
342
343                                                 # Abort if we don't want to modify timers or timer is repeated
344                                                 if config.plugins.autotimer.refresh.value == "none" or rtimer.repeated:
345                                                         print "[AutoTimer] Won't modify existing timer because either no modification allowed or repeated timer"
346                                                         break
347
348                                                 if hasattr(rtimer, "isAutoTimer"):
349                                                         rtimer.log(501, "[AutoTimer] AutoTimer %s modified this automatically generated timer." % (timer.name))
350                                                 else:
351                                                         if config.plugins.autotimer.refresh.value != "all":
352                                                                 print "[AutoTimer] Won't modify existing timer because it's no timer set by us"
353                                                                 break
354
355                                                         rtimer.log(501, "[AutoTimer] Warning, AutoTimer %s messed with a timer which might not belong to it." % (timer.name))
356
357                                                 newEntry = rtimer
358                                                 modified += 1
359
360                                                 # Modify values saved in timer
361                                                 newEntry.name = name
362                                                 newEntry.description = shortdesc
363                                                 newEntry.begin = int(begin)
364                                                 newEntry.end = int(end)
365                                                 newEntry.service_ref = ServiceReference(serviceref)
366
367                                                 break
368                                         elif timer.avoidDuplicateDescription >= 1 \
369                                                 and not rtimer.disabled \
370                                                 and rtimer.name == name \
371                                                 and rtimer.description == shortdesc \
372                                                 and rtimer.extdesc == extdesc:
373                                                 oldExists = True
374                                                 print "[AutoTimer] We found a timer (similar service) with same description, skipping event"
375                                                 break
376
377                                 # We found no timer we want to edit
378                                 if newEntry is None:
379                                         # But there is a match
380                                         if oldExists:
381                                                 continue
382
383                                         # We want to search for possible doubles
384                                         if timer.avoidDuplicateDescription >= 2:
385                                                 for rtimer in chain.from_iterable( recorddict.values() ):
386                                                         if not rtimer.disabled \
387                                                                 and rtimer.name == name \
388                                                                 and rtimer.description == shortdesc \
389                                                                 and rtimer.extdesc == extdesc:
390                                                                 oldExists = True
391                                                                 print "[AutoTimer] We found a timer (any service) with same description, skipping event"
392                                                                 break
393                                                 if oldExists:
394                                                         continue
395
396                                         if timer.checkCounter(timestamp):
397                                                 print "[AutoTimer] Not adding new timer because counter is depleted."
398                                                 continue
399
400                                         newEntry = RecordTimerEntry(ServiceReference(serviceref), begin, end, name, shortdesc, eit)
401                                         newEntry.log(500, "[AutoTimer] Try to add new timer based on AutoTimer %s." % (timer.name))
402
403                                         # Mark this entry as AutoTimer (only AutoTimers will have this Attribute set)
404                                         newEntry.isAutoTimer = True
405
406                                 # Apply afterEvent
407                                 if timer.hasAfterEvent():
408                                         afterEvent = timer.getAfterEventTimespan(localtime(end))
409                                         if afterEvent is None:
410                                                 afterEvent = timer.getAfterEvent()
411                                         if afterEvent is not None:
412                                                 newEntry.afterEvent = afterEvent
413
414                                 newEntry.dirname = timer.destination
415                                 newEntry.justplay = timer.justplay
416                                 newEntry.tags = timer.tags
417                                 newEntry.vpsplugin_enabled = timer.vps_enabled
418                                 newEntry.vpsplugin_overwrite = timer.vps_overwrite
419
420                                 if oldExists:
421                                         # XXX: this won't perform a sanity check, but do we actually want to do so?
422                                         recordHandler.timeChanged(newEntry)
423                                 else:
424                                         conflictString = ""
425                                         if similarTimer:
426                                                 conflictString = similar[eit].conflictString
427                                                 newEntry.log(504, "[AutoTimer] Try to add similar Timer because of conflicts with %s." % (conflictString))
428
429                                         # Try to add timer
430                                         conflicts = recordHandler.record(newEntry)
431
432                                         if conflicts:
433                                                 conflictString += ' / '.join(["%s (%s)" % (x.name, strftime("%Y%m%d %H%M", localtime(x.begin))) for x in conflicts])
434                                                 print "[AutoTimer] conflict with %s detected" % (conflictString)
435
436                                         if conflicts and config.plugins.autotimer.addsimilar_on_conflict.value:
437                                                 # We start our search right after our actual index
438                                                 # Attention we have to use a copy of the list, because we have to append the previous older matches
439                                                 lepgm = len(epgmatches)
440                                                 for i in xrange(lepgm):
441                                                         servicerefS, eitS, nameS, beginS, durationS, shortdescS, extdescS = epgmatches[ (i+idx+1)%lepgm ]
442                                                 #for servicerefS, eitS, nameS, beginS, durationS, shortdescS, extdescS in ( epgmatches[idx+1:] + epgmatches[:idx] ):
443                                                         # Match only if the descriptions are equal
444                                                         if extdesc == extdescS and shortdesc == shortdescS:
445                                                                 # Check if the similar is already known
446                                                                 if eitS not in similar:
447                                                                         print "[AutoTimer] Found similar Timer: " + name
448                                                                         
449                                                                         # Store the actual and similar eit and conflictString, so it can be handled later
450                                                                         newEntry.conflictString = conflictString
451                                                                         similar[eit] = newEntry
452                                                                         similar[eitS] = newEntry
453                                                                         similarTimer = True
454                                                                         if beginS <= evtBegin:
455                                                                                 # Event is before our actual epgmatch so we have to append it to the epgmatches list
456                                                                                 epgmatches.append((servicerefS, eitS, nameS, beginS, durationS, shortdescS, extdescS))
457                                                                         # If we need a second similar it will be found the next time
458                                                                         break
459                                                                 else:
460                                                                         similarTimer = False
461                                                                         newEntry = similar[eitS]
462                                                                         break
463
464                                         if conflicts is None:
465                                                 timer.decrementCounter()
466                                                 new += 1
467                                                 timer.extdesc = extdesc
468                                                 recorddict[serviceref].append(newEntry)
469
470                                                 # Similar timers are in new timers list and additionally in similar timers list
471                                                 if similarTimer:
472                                                         similars.append((name, begin, end, serviceref, timer.name))
473                                                         similar.clear()
474
475                                         # Don't care about similar timers
476                                         elif not similarTimer:
477                                                 conflicting.append((name, begin, end, serviceref, timer.name))
478
479                                                 if config.plugins.autotimer.disabled_on_conflict.value:
480                                                         newEntry.log(503, "[AutoTimer] Timer disabled because of conflicts with %s." % (conflictString))
481                                                         newEntry.disabled = True
482                                                         # We might want to do the sanity check locally so we don't run it twice - but I consider this workaround a hack anyway
483                                                         conflicts = recordHandler.record(newEntry)
484
485                 return (total, new, modified, timers, conflicting, similars)