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