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