edd19685755acbefe5f53312b3e9af17f97956a9
[openblackhole/openblackhole-enigma2.git] / lib / python / Screens / TimerEntry.py
1 from Screen import Screen
2 import ChannelSelection
3 from ServiceReference import ServiceReference
4 from Components.config import config, ConfigSelection, ConfigText, ConfigSubList, ConfigDateTime, ConfigClock, ConfigYesNo, getConfigListEntry
5 from Components.ActionMap import NumberActionMap
6 from Components.ConfigList import ConfigListScreen
7 from Components.MenuList import MenuList
8 from Components.Button import Button
9 from Components.Label import Label
10 from Components.Pixmap import Pixmap
11 from Screens.MovieSelection import getPreferredTagEditor
12 from Screens.LocationBox import MovieLocationBox
13 from Screens.ChoiceBox import ChoiceBox
14 from RecordTimer import AFTEREVENT
15 from Tools.Directories import resolveFilename, SCOPE_HDD
16 from enigma import eEPGCache
17 from time import localtime, mktime, time, strftime
18 from datetime import datetime
19
20 class TimerEntry(Screen, ConfigListScreen):
21         def __init__(self, session, timer):
22                 Screen.__init__(self, session)
23                 self.timer = timer
24
25                 self.entryDate = None
26                 self.entryService = None
27
28                 self["oktext"] = Label(_("OK"))
29                 self["canceltext"] = Label(_("Cancel"))
30                 self["ok"] = Pixmap()
31                 self["cancel"] = Pixmap()
32
33                 self.createConfig()
34
35                 self["actions"] = NumberActionMap(["SetupActions", "GlobalActions", "PiPSetupActions"],
36                 {
37                         "ok": self.keySelect,
38                         "save": self.keyGo,
39                         "cancel": self.keyCancel,
40                         "volumeUp": self.incrementStart,
41                         "volumeDown": self.decrementStart,
42                         "size+": self.incrementEnd,
43                         "size-": self.decrementEnd
44                 }, -2)
45
46                 self.list = []
47                 ConfigListScreen.__init__(self, self.list, session = session)
48                 self.createSetup("config")
49
50         def createConfig(self):
51                         justplay = self.timer.justplay
52
53                         afterevent = {
54                                 AFTEREVENT.NONE: "nothing",
55                                 AFTEREVENT.DEEPSTANDBY: "deepstandby",
56                                 AFTEREVENT.STANDBY: "standby",
57                                 AFTEREVENT.AUTO: "auto"
58                                 }[self.timer.afterEvent]
59
60                         weekday_table = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")
61
62                         # calculate default values
63                         day = []
64                         weekday = 0
65                         for x in (0, 1, 2, 3, 4, 5, 6):
66                                 day.append(0)
67                         if self.timer.repeated: # repeated
68                                 type = "repeated"
69                                 if (self.timer.repeated == 31): # Mon-Fri
70                                         repeated = "weekdays"
71                                 elif (self.timer.repeated == 127): # daily
72                                         repeated = "daily"
73                                 else:
74                                         flags = self.timer.repeated
75                                         repeated = "user"
76                                         count = 0
77                                         for x in (0, 1, 2, 3, 4, 5, 6):
78                                                 if flags == 1: # weekly
79                                                         print "Set to weekday " + str(x)
80                                                         weekday = x
81                                                 if flags & 1 == 1: # set user defined flags
82                                                         day[x] = 1
83                                                         count += 1
84                                                 else:
85                                                         day[x] = 0
86                                                 flags = flags >> 1
87                                         if count == 1:
88                                                 repeated = "weekly"
89                         else: # once
90                                 type = "once"
91                                 repeated = None
92                                 weekday = (int(strftime("%w", localtime(self.timer.begin))) - 1) % 7
93                                 day[weekday] = 1
94
95                         self.timerentry_justplay = ConfigSelection(choices = [("zap", _("zap")), ("record", _("record"))], default = {0: "record", 1: "zap"}[justplay])
96                         self.timerentry_afterevent = ConfigSelection(choices = [("nothing", _("do nothing")), ("standby", _("go to standby")), ("deepstandby", _("go to deep standby")), ("auto", _("auto"))], default = afterevent)
97                         self.timerentry_type = ConfigSelection(choices = [("once",_("once")), ("repeated", _("repeated"))], default = type)
98                         self.timerentry_name = ConfigText(default = self.timer.name, visible_width = 50, fixed_size = False)
99                         self.timerentry_description = ConfigText(default = self.timer.description, visible_width = 50, fixed_size = False)
100                         self.timerentry_tags = self.timer.tags[:]
101                         self.timerentry_tagsset = ConfigSelection(choices = [not self.timerentry_tags and "None" or " ".join(self.timerentry_tags)])
102
103                         self.timerentry_repeated = ConfigSelection(default = repeated, choices = [("daily", _("daily")), ("weekly", _("weekly")), ("weekdays", _("Mon-Fri")), ("user", _("user defined"))])
104
105                         self.timerentry_date = ConfigDateTime(default = self.timer.begin, formatstring = _("%d.%B %Y"), increment = 86400)
106                         self.timerentry_starttime = ConfigClock(default = self.timer.begin)
107                         self.timerentry_endtime = ConfigClock(default = self.timer.end)
108
109                         default = self.timer.dirname or resolveFilename(SCOPE_HDD)
110                         tmp = config.movielist.videodirs.value
111                         if default not in tmp:
112                                 tmp.append(default)
113                         self.timerentry_dirname = ConfigSelection(default = default, choices = tmp)
114
115                         self.timerentry_repeatedbegindate = ConfigDateTime(default = self.timer.repeatedbegindate, formatstring = _("%d.%B %Y"), increment = 86400)
116
117                         self.timerentry_weekday = ConfigSelection(default = weekday_table[weekday], choices = [("mon",_("Monday")), ("tue", _("Tuesday")), ("wed",_("Wednesday")), ("thu", _("Thursday")), ("fri", _("Friday")), ("sat", _("Saturday")), ("sun", _("Sunday"))])
118
119                         self.timerentry_day = ConfigSubList()
120                         for x in (0, 1, 2, 3, 4, 5, 6):
121                                 self.timerentry_day.append(ConfigYesNo(default = day[x]))
122
123                         # FIXME some service-chooser needed here
124                         servicename = "N/A"
125                         try: # no current service available?
126                                 servicename = str(self.timer.service_ref.getServiceName())
127                         except:
128                                 pass
129                         self.timerentry_service_ref = self.timer.service_ref
130                         self.timerentry_service = ConfigSelection([servicename])
131
132         def createSetup(self, widget):
133                 self.list = []
134                 self.list.append(getConfigListEntry(_("Name"), self.timerentry_name))
135                 self.list.append(getConfigListEntry(_("Description"), self.timerentry_description))
136                 self.timerJustplayEntry = getConfigListEntry(_("Timer Type"), self.timerentry_justplay)
137                 self.list.append(self.timerJustplayEntry)
138                 self.timerTypeEntry = getConfigListEntry(_("Repeat Type"), self.timerentry_type)
139                 self.list.append(self.timerTypeEntry)
140
141                 if self.timerentry_type.value == "once":
142                         self.frequencyEntry = None
143                 else: # repeated
144                         self.frequencyEntry = getConfigListEntry(_("Repeats"), self.timerentry_repeated)
145                         self.list.append(self.frequencyEntry)
146                         self.repeatedbegindateEntry = getConfigListEntry(_("Starting on"), self.timerentry_repeatedbegindate)
147                         self.list.append(self.repeatedbegindateEntry)
148                         if self.timerentry_repeated.value == "daily":
149                                 pass
150                         if self.timerentry_repeated.value == "weekdays":
151                                 pass
152                         if self.timerentry_repeated.value == "weekly":
153                                 self.list.append(getConfigListEntry(_("Weekday"), self.timerentry_weekday))
154
155                         if self.timerentry_repeated.value == "user":
156                                 self.list.append(getConfigListEntry(_("Monday"), self.timerentry_day[0]))
157                                 self.list.append(getConfigListEntry(_("Tuesday"), self.timerentry_day[1]))
158                                 self.list.append(getConfigListEntry(_("Wednesday"), self.timerentry_day[2]))
159                                 self.list.append(getConfigListEntry(_("Thursday"), self.timerentry_day[3]))
160                                 self.list.append(getConfigListEntry(_("Friday"), self.timerentry_day[4]))
161                                 self.list.append(getConfigListEntry(_("Saturday"), self.timerentry_day[5]))
162                                 self.list.append(getConfigListEntry(_("Sunday"), self.timerentry_day[6]))
163
164                 self.entryDate = getConfigListEntry(_("Date"), self.timerentry_date)
165                 if self.timerentry_type.value == "once":
166                         self.list.append(self.entryDate)
167                 
168                 self.entryStartTime = getConfigListEntry(_("StartTime"), self.timerentry_starttime)
169                 self.list.append(self.entryStartTime)
170                 if self.timerentry_justplay.value != "zap":
171                         self.entryEndTime = getConfigListEntry(_("EndTime"), self.timerentry_endtime)
172                         self.list.append(self.entryEndTime)
173                 else:
174                         self.entryEndTime = None
175                 self.channelEntry = getConfigListEntry(_("Channel"), self.timerentry_service)
176                 self.list.append(self.channelEntry)
177
178                 self.dirname = getConfigListEntry(_("Location"), self.timerentry_dirname)
179                 self.tagsSet = getConfigListEntry(_("Tags"), self.timerentry_tagsset)
180                 if self.timerentry_justplay.value != "zap":
181                         if config.usage.setup_level.index >= 2: # expert+
182                                 self.list.append(self.dirname)
183                         if getPreferredTagEditor():
184                                 self.list.append(self.tagsSet)
185                         self.list.append(getConfigListEntry(_("After event"), self.timerentry_afterevent))
186
187                 self[widget].list = self.list
188                 self[widget].l.setList(self.list)
189
190         def newConfig(self):
191                 print "newConfig", self["config"].getCurrent()
192                 if self["config"].getCurrent() == self.timerTypeEntry:
193                         self.createSetup("config")
194                 if self["config"].getCurrent() == self.timerJustplayEntry:
195                         self.createSetup("config")
196                 if self["config"].getCurrent() == self.frequencyEntry:
197                         self.createSetup("config")
198
199         def keyLeft(self):
200                 if self["config"].getCurrent() in (self.channelEntry, self.tagsSet):
201                         self.keySelect()
202                 else:
203                         ConfigListScreen.keyLeft(self)
204                         self.newConfig()
205
206         def keyRight(self):
207                 if self["config"].getCurrent() in (self.channelEntry, self.tagsSet):
208                         self.keySelect()
209                 else:
210                         ConfigListScreen.keyRight(self)
211                         self.newConfig()
212
213         def keySelect(self):
214                 cur = self["config"].getCurrent()
215                 if cur == self.channelEntry:
216                         self.session.openWithCallback(
217                                 self.finishedChannelSelection,
218                                 ChannelSelection.SimpleChannelSelection,
219                                 _("Select channel to record from")
220                         )
221                 elif config.usage.setup_level.index >= 2 and cur == self.dirname:
222                         self.session.openWithCallback(
223                                 self.pathSelected,
224                                 MovieLocationBox,
225                                 _("Choose target folder"),
226                                 self.timerentry_dirname.value,
227                                 minFree = 100 # We require at least 100MB free space
228                         )
229                 elif getPreferredTagEditor() and cur == self.tagsSet:
230                         self.session.openWithCallback(
231                                 self.tagEditFinished,
232                                 getPreferredTagEditor(),
233                                 self.timerentry_tags
234                         )
235                 else:
236                         self.keyGo()
237
238         def finishedChannelSelection(self, *args):
239                 if args:
240                         self.timerentry_service_ref = ServiceReference(args[0])
241                         self.timerentry_service.setCurrentText(self.timerentry_service_ref.getServiceName())
242                         self["config"].invalidate(self.channelEntry)
243
244         def getTimestamp(self, date, mytime):
245                 d = localtime(date)
246                 dt = datetime(d.tm_year, d.tm_mon, d.tm_mday, mytime[0], mytime[1])
247                 return int(mktime(dt.timetuple()))
248
249         def getBeginEnd(self):
250                 date = self.timerentry_date.value
251                 endtime = self.timerentry_endtime.value
252                 starttime = self.timerentry_starttime.value
253
254                 begin = self.getTimestamp(date, starttime)
255                 end = self.getTimestamp(date, endtime)
256
257                 # if the endtime is less than the starttime, add 1 day.
258                 if end < begin:
259                         end += 86400
260                 return begin, end
261
262         def keyGo(self):
263                 self.timer.name = self.timerentry_name.value
264                 self.timer.description = self.timerentry_description.value
265                 self.timer.justplay = self.timerentry_justplay.value == "zap"
266                 self.timer.resetRepeated()
267                 self.timer.afterEvent = {
268                         "nothing": AFTEREVENT.NONE,
269                         "deepstandby": AFTEREVENT.DEEPSTANDBY,
270                         "standby": AFTEREVENT.STANDBY,
271                         "auto": AFTEREVENT.AUTO
272                         }[self.timerentry_afterevent.value]
273                 self.timer.service_ref = self.timerentry_service_ref
274                 self.timer.tags = self.timerentry_tags
275
276                 self.timer.dirname = self.timerentry_dirname.value
277                 config.movielist.last_timer_videodir.value = self.timer.dirname
278                 config.movielist.last_timer_videodir.save()
279
280                 if self.timerentry_type.value == "once":
281                         self.timer.begin, self.timer.end = self.getBeginEnd()
282                 if self.timerentry_type.value == "repeated":
283                         if self.timerentry_repeated.value == "daily":
284                                 for x in (0, 1, 2, 3, 4, 5, 6):
285                                         self.timer.setRepeated(x)
286
287                         if self.timerentry_repeated.value == "weekly":
288                                 self.timer.setRepeated(self.timerentry_weekday.index)
289
290                         if self.timerentry_repeated.value == "weekdays":
291                                 for x in (0, 1, 2, 3, 4):
292                                         self.timer.setRepeated(x)
293
294                         if self.timerentry_repeated.value == "user":
295                                 for x in (0, 1, 2, 3, 4, 5, 6):
296                                         if self.timerentry_day[x].value:
297                                                 self.timer.setRepeated(x)
298
299                         self.timer.repeatedbegindate = self.getTimestamp(self.timerentry_repeatedbegindate.value, self.timerentry_starttime.value)
300                         if self.timer.repeated:
301                                 self.timer.begin = self.getTimestamp(self.timerentry_repeatedbegindate.value, self.timerentry_starttime.value)
302                                 self.timer.end = self.getTimestamp(self.timerentry_repeatedbegindate.value, self.timerentry_endtime.value)
303                         else:
304                                 self.timer.begin = self.getTimestamp(time.time(), self.timerentry_starttime.value)
305                                 self.timer.end = self.getTimestamp(time.time(), self.timerentry_endtime.value)
306
307                         # when a timer end is set before the start, add 1 day
308                         if self.timer.end < self.timer.begin:
309                                 self.timer.end += 86400
310
311                 if self.timer.eit is not None:
312                         event = eEPGCache.getInstance().lookupEventId(self.timer.service_ref.ref, self.timer.eit)
313                         if event:
314                                 n = event.getNumOfLinkageServices()
315                                 if n > 1:
316                                         tlist = []
317                                         ref = self.session.nav.getCurrentlyPlayingServiceReference()
318                                         parent = self.timer.service_ref.ref
319                                         selection = 0
320                                         for x in range(n):
321                                                 i = event.getLinkageService(parent, x)
322                                                 if i.toString() == ref.toString():
323                                                         selection = x
324                                                 tlist.append((i.getName(), i))
325                                         self.session.openWithCallback(self.subserviceSelected, ChoiceBox, title=_("Please select a subservice to record..."), list = tlist, selection = selection)
326                                         return
327                                 elif n > 0:
328                                         parent = self.timer.service_ref.ref
329                                         self.timer.service_ref = ServiceReference(event.getLinkageService(parent, 0))
330                 self.saveTimer()
331                 self.close((True, self.timer))
332
333         def incrementStart(self):
334                 self.timerentry_starttime.increment()
335                 self["config"].invalidate(self.entryStartTime)
336
337         def decrementStart(self):
338                 self.timerentry_starttime.decrement()
339                 self["config"].invalidate(self.entryStartTime)
340
341         def incrementEnd(self):
342                 if self.entryEndTime is not None:
343                         self.timerentry_endtime.increment()
344                         self["config"].invalidate(self.entryEndTime)
345
346         def decrementEnd(self):
347                 if self.entryEndTime is not None:
348                         self.timerentry_endtime.decrement()
349                         self["config"].invalidate(self.entryEndTime)
350
351         def subserviceSelected(self, service):
352                 if not service is None:
353                         self.timer.service_ref = ServiceReference(service[1])
354                 self.saveTimer()
355                 self.close((True, self.timer))
356
357         def saveTimer(self):
358                 self.session.nav.RecordTimer.saveTimer()
359
360         def keyCancel(self):
361                 self.close((False,))
362
363         def pathSelected(self, res):
364                 if res is not None:
365                         if config.movielist.videodirs.value != self.timerentry_dirname.choices:
366                                 self.timerentry_dirname.setChoices(config.movielist.videodirs.value, default=res)
367                         self.timerentry_dirname.value = res
368
369         def tagEditFinished(self, ret):
370                 if ret is not None:
371                         self.timerentry_tags = ret
372                         self.timerentry_tagsset.setChoices([not ret and "None" or " ".join(ret)])
373                         self["config"].invalidate(self.tagsSet)
374
375 class TimerLog(Screen):
376         def __init__(self, session, timer):
377                 Screen.__init__(self, session)
378                 self.timer = timer;
379                 self.log_entries = self.timer.log_entries[:]
380
381                 self.fillLogList()
382
383                 self["loglist"] = MenuList(self.list)
384                 self["logentry"] = Label()
385
386                 self["key_red"] = Button(_("Delete entry"))
387                 self["key_green"] = Button()
388                 self["key_yellow"] = Button("")
389                 self["key_blue"] = Button(_("Clear log"))
390
391                 self.onShown.append(self.updateText)
392
393                 self["actions"] = NumberActionMap(["OkCancelActions", "DirectionActions", "ColorActions"],
394                 {
395                         "ok": self.keyClose,
396                         "cancel": self.keyClose,
397                         "up": self.up,
398                         "down": self.down,
399                         "left": self.left,
400                         "right": self.right,
401                         "red": self.deleteEntry,
402                         "blue": self.clearLog
403                 }, -1)
404
405         def deleteEntry(self):
406                 cur = self["loglist"].getCurrent()
407                 if cur is None:
408                         return 
409                 self.log_entries.remove(cur[1])
410                 self.fillLogList()
411                 self["loglist"].l.setList(self.list)
412                 self.updateText()
413
414         def fillLogList(self):
415                 self.list = [(str(strftime("%Y-%m-%d %H-%M", localtime(x[0])) + " - " + x[2]), x) for x in self.log_entries]
416
417         def clearLog(self):
418                 self.log_entries = []
419                 self.fillLogList()
420                 self["loglist"].l.setList(self.list)
421                 self.updateText()
422
423         def keyClose(self):
424                 if self.timer.log_entries != self.log_entries:
425                         self.timer.log_entries = self.log_entries
426                         self.close((True, self.timer))
427                 else:
428                         self.close((False,))
429
430         def up(self):
431                 self["loglist"].instance.moveSelection(self["loglist"].instance.moveUp)
432                 self.updateText()
433
434         def down(self):
435                 self["loglist"].instance.moveSelection(self["loglist"].instance.moveDown)
436                 self.updateText()
437
438         def left(self):
439                 self["loglist"].instance.moveSelection(self["loglist"].instance.pageUp)
440                 self.updateText()
441
442         def right(self):
443                 self["loglist"].instance.moveSelection(self["loglist"].instance.pageDown)
444                 self.updateText()
445
446         def updateText(self):
447                 if self.list:
448                         self["logentry"].setText(str(self["loglist"].getCurrent()[1][2]))
449                 else:
450                         self["logentry"].setText("")