tiny optimization
[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, writeConfig
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, time
16
17 # EPGCache & Event
18 from enigma import eEPGCache, eServiceReference
19
20 # Enigma2 Config
21 from Components.config import config
22
23 # AutoTimer Component
24 from AutoTimerComponent import AutoTimerComponent
25
26 XML_CONFIG = "/etc/enigma2/autotimer.xml"
27
28 def getTimeDiff(timer, begin, end):
29         if begin <= timer.begin <= end:
30                 return end - timer.begin
31         elif timer.begin <= begin <= timer.end:
32                 return timer.end - begin
33         return 0
34
35 typeMap = {
36         "exact": eEPGCache.EXAKT_TITLE_SEARCH,
37         "partial": eEPGCache.PARTIAL_TITLE_SEARCH
38 }
39
40 caseMap = {
41         "sensitive": eEPGCache.CASE_CHECK,
42         "insensitive": eEPGCache.NO_CASE_CHECK
43 }
44
45 class AutoTimerIgnoreTimerException(Exception):
46         def __init__(self, cause):
47                 self.cause = cause
48
49         def __str__(self):
50                 return "[AutoTimer] " + str(self.cause)
51
52         def __repr__(self):
53                 return str(type(self))
54
55 class AutoTimer:
56         """Read and save xml configuration, query EPGCache"""
57
58         def __init__(self):
59                 # Initialize
60                 self.timers = []
61                 self.configMtime = -1
62                 self.uniqueTimerId = 0
63                 self.defaultTimer = AutoTimerComponent(
64                         0,              # Id
65                         "",             # Name
66                         "",             # Match
67                         True    # Enabled
68                 )
69
70 # Configuration
71
72         def readXml(self):
73                 # Abort if no config found
74                 if not os_path.exists(XML_CONFIG):
75                         print "[AutoTimer] No configuration file present"
76                         return
77
78                 # Parse if mtime differs from whats saved
79                 mtime = os_path.getmtime(XML_CONFIG)
80                 if mtime == self.configMtime:
81                         print "[AutoTimer] No changes in configuration, won't parse"
82                         return
83
84                 # Save current mtime
85                 self.configMtime = mtime
86
87                 # Parse Config
88                 configuration = cet_parse(XML_CONFIG).getroot()
89
90                 # Empty out timers and reset Ids
91                 del self.timers[:]
92                 self.defaultTimer.clear(-1, True)
93
94                 parseConfig(
95                         configuration,
96                         self.timers,
97                         configuration.get("version"),
98                         0,
99                         self.defaultTimer
100                 )
101                 self.uniqueTimerId = len(self.timers)
102
103         def writeXml(self):
104                 writeConfig(XML_CONFIG, self.defaultTimer, self.timers)
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                 list = self.timers
119                 return [(x,) for x in list]
120
121         def getSortedTupleTimerList(self):
122                 list = self.timers[:]
123                 list.sort()
124                 return [(x,) for x in list]
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
159                 self.readXml()
160
161                 # Save Recordings in a dict to speed things up a little
162                 # We include processed timers as we might search for duplicate descriptions
163                 recorddict = {}
164                 for timer in NavigationInstance.instance.RecordTimer.timer_list + NavigationInstance.instance.RecordTimer.processed_timers:
165                         recorddict.setdefault(str(timer.service_ref), []).append(timer)
166
167                 # Iterate Timer
168                 for timer in self.getEnabledTimerList():
169                         # Workaround to allow search for umlauts if we know the encoding
170                         match = timer.match
171                         if timer.encoding != 'UTF-8':
172                                 try:
173                                         match = match.decode('UTF-8').encode(timer.encoding)
174                                 except UnicodeDecodeError:
175                                         pass
176
177                         # Search EPG, default to empty list
178                         epgcache = eEPGCache.getInstance()
179                         ret = epgcache.search(('RI', 100, typeMap[timer.searchType], match, caseMap[timer.searchCase])) or []
180
181                         for serviceref, eit in ret:
182                                 eserviceref = eServiceReference(serviceref)
183
184                                 evt = epgcache.lookupEventId(eserviceref, eit)
185                                 if not evt:
186                                         print "[AutoTimer] Could not create Event!"
187                                         continue
188
189                                 # Try to determine real service (we always choose the last one)
190                                 n = evt.getNumOfLinkageServices()
191                                 if n > 0:
192                                         i = evt.getLinkageService(eserviceref, n-1)
193                                         serviceref = i.toString()
194
195                                 # Gather Information
196                                 name = evt.getEventName()
197                                 description = evt.getShortDescription()
198                                 begin = evt.getBeginTime()
199                                 duration = evt.getDuration()
200                                 end = begin + duration
201
202                                 # If event starts in less than 60 seconds skip it
203                                 if begin < time() + 60:
204                                         continue
205
206                                 # Convert begin time
207                                 timestamp = localtime(begin)
208
209                                 # Update timer
210                                 timer.update(begin, timestamp)
211
212                                 # Check Duration, Timespan and Excludes
213                                 if timer.checkServices(serviceref) \
214                                         or timer.checkDuration(duration) \
215                                         or timer.checkTimespan(timestamp) \
216                                         or timer.checkFilter(name, description,
217                                                 evt.getExtendedDescription(), str(timestamp.tm_wday)):
218                                         continue
219
220                                 if timer.hasOffset():
221                                         # Apply custom Offset
222                                         begin, end = timer.applyOffset(begin, end)
223                                 else:
224                                         # Apply E2 Offset
225                                         begin -= config.recording.margin_before.value * 60
226                                         end += config.recording.margin_after.value * 60
227
228
229                                 total += 1
230
231                                 # Append to timerlist and abort if simulating
232                                 timers.append((name, begin, end, serviceref, timer.name))
233                                 if simulateOnly:
234                                         continue
235
236                                 # Initialize
237                                 newEntry = None
238                                 oldExists = False
239
240                                 # Check for double Timers
241                                 # We first check eit and if user wants us to guess event based on time
242                                 # we try this as backup. The allowed diff should be configurable though.
243                                 for rtimer in recorddict.get(serviceref, ()):
244                                         if rtimer.eit == eit or config.plugins.autotimer.try_guessing.value and getTimeDiff(rtimer, begin, end) > ((duration/10)*8):
245                                                 oldExists = True
246
247                                                 # Abort if we don't want to modify timers or timer is repeated
248                                                 if config.plugins.autotimer.refresh.value == "none" or rtimer.repeated:
249                                                         print "[AutoTimer] Won't modify existing timer because either no modification allowed or repeated timer"
250                                                         break
251
252                                                 if hasattr(rtimer, "isAutoTimer"):
253                                                                 print "[AutoTimer] Modifying existing AutoTimer!"
254                                                 else:
255                                                         if config.plugins.autotimer.refresh.value != "all":
256                                                                 print "[AutoTimer] Won't modify existing timer because it's no timer set by us"
257                                                                 break
258
259                                                         print "[AutoTimer] Warning, we're messing with a timer which might not have been set by us"
260
261                                                 newEntry = rtimer
262                                                 modified += 1
263
264                                                 # Modify values saved in timer
265                                                 newEntry.name = name
266                                                 newEntry.description = description
267                                                 newEntry.begin = int(begin)
268                                                 newEntry.end = int(end)
269                                                 newEntry.service_ref = ServiceReference(serviceref)
270
271                                                 break
272                                         elif timer.getAvoidDuplicateDescription() == 1 and rtimer.description == description:
273                                                 oldExists = True
274                                                 print "[AutoTimer] We found a timer with same description, skipping event"
275                                                 break
276
277                                 # We found no timer we want to edit
278                                 if newEntry is None:
279                                         # But there is a match
280                                         if oldExists:
281                                                 continue
282
283                                         # We want to search for possible doubles
284                                         if timer.getAvoidDuplicateDescription() == 2:
285                                                 # I thinks thats the fastest way to do this, though it's a little ugly
286                                                 try:
287                                                         for list in recorddict.values():
288                                                                 for rtimer in list:
289                                                                         if rtimer.description == description:
290                                                                                 raise AutoTimerIgnoreTimerException("We found a timer with same description, skipping event")
291                                                 except AutoTimerIgnoreTimerException, etite:
292                                                         print etite
293                                                         continue
294
295                                         if timer.checkCounter(timestamp):
296                                                 continue
297
298                                         print "[AutoTimer] Adding an event."
299                                         newEntry = RecordTimerEntry(ServiceReference(serviceref), begin, end, name, description, eit)
300
301                                         # Mark this entry as AutoTimer (only AutoTimers will have this Attribute set)
302                                         newEntry.isAutoTimer = True
303
304                                 # Apply afterEvent
305                                 if timer.hasAfterEvent():
306                                         afterEvent = timer.getAfterEventTimespan(localtime(end))
307                                         if afterEvent is None:
308                                                 afterEvent = timer.getAfterEvent()
309                                         if afterEvent is not None:
310                                                 newEntry.afterEvent = afterEvent
311
312                                 newEntry.dirname = timer.destination
313                                 newEntry.justplay = timer.justplay
314                                 newEntry.tags = timer.tags
315
316                                 if oldExists:
317                                         # XXX: this won't perform a sanity check, but do we actually want to do so?
318                                         NavigationInstance.instance.RecordTimer.timeChanged(newEntry)
319                                 else:
320                                         conflicts = NavigationInstance.instance.RecordTimer.record(newEntry)
321                                         if conflicts and config.plugins.autotimer.disabled_on_conflict.value:
322                                                 newEntry.disabled = True
323                                                 # We might want to do the sanity check locally so we don't run it twice - but I consider this workaround a hack anyway
324                                                 conflicts = NavigationInstance.instance.RecordTimer.record(newEntry)
325                                         if conflicts is None:
326                                                 timer.decrementCounter()
327                                                 new += 1
328                                                 if recorddict.has_key(serviceref):
329                                                         recorddict[serviceref].append(newEntry)
330                                                 else:
331                                                         recorddict[serviceref] = [newEntry]
332
333                 return (total, new, modified, timers)
334