remove duplicate code, add 'quit and delete movie'-option (experts only), move import...
[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.LocationBox import MovieLocationBox
12 from Screens.ChoiceBox import ChoiceBox
13 from RecordTimer import AFTEREVENT
14 from Tools.Directories import resolveFilename, SCOPE_HDD
15 from enigma import eEPGCache
16 from time import localtime, mktime, time, strftime
17 from datetime import datetime
18
19 class TimerEntry(Screen, ConfigListScreen):
20         def __init__(self, session, timer):
21                 Screen.__init__(self, session)
22                 self.timer = timer
23
24                 self.entryStartDate = None
25                 self.entryEndDate = 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
92                         self.timerentry_repeated = ConfigSelection(default = repeated, choices = [("daily", _("daily")), ("weekly", _("weekly")), ("weekdays", _("Mon-Fri")), ("user", _("user defined"))])
93
94                         self.timerentry_startdate = ConfigDateTime(default = self.timer.begin, formatstring = _("%d.%B %Y"), increment = 86400)
95                         self.timerentry_starttime = ConfigClock(default = self.timer.begin)
96
97                         self.timerentry_enddate = ConfigDateTime(default = self.timer.end, formatstring =  _("%d.%B %Y"), increment = 86400)
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                         self.timerentry_startdate.addNotifier(self.checkDate)
124                         self.timerentry_enddate.addNotifier(self.checkDate)
125
126         def checkDate(self, configElement):
127                 if configElement is self.timerentry_startdate:
128                         if self.timerentry_enddate.value < self.timerentry_startdate.value:
129                                 self.timerentry_enddate.value = self.timerentry_startdate.value
130                                 self["config"].invalidate(self.entryEndDate)
131                 if configElement is self.timerentry_enddate:
132                         if (self.timerentry_enddate.value < self.timerentry_startdate.value):
133                                 self.timerentry_startdate.value = self.timerentry_enddate.value
134                                 self["config"].invalidate(self.entryStartDate)
135
136         def createSetup(self, widget):
137                 self.list = []
138                 self.list.append(getConfigListEntry(_("Name"), self.timerentry_name))
139                 self.list.append(getConfigListEntry(_("Description"), self.timerentry_description))
140                 self.timerJustplayEntry = getConfigListEntry(_("Timer Type"), self.timerentry_justplay)
141                 self.list.append(self.timerJustplayEntry)
142                 self.timerTypeEntry = getConfigListEntry(_("Repeat Type"), self.timerentry_type)
143                 self.list.append(self.timerTypeEntry)
144
145                 if self.timerentry_type.value == "once":
146                         self.frequencyEntry = None
147                 else: # repeated
148                         self.frequencyEntry = getConfigListEntry(_("Repeats"), self.timerentry_repeated)
149                         self.list.append(self.frequencyEntry)
150                         self.repeatedbegindateEntry = getConfigListEntry(_("Starting on"), self.timerentry_repeatedbegindate)
151                         self.list.append(self.repeatedbegindateEntry)
152                         if self.timerentry_repeated.value == "daily":
153                                 pass
154                         if self.timerentry_repeated.value == "weekdays":
155                                 pass
156                         if self.timerentry_repeated.value == "weekly":
157                                 self.list.append(getConfigListEntry(_("Weekday"), self.timerentry_weekday))
158
159                         if self.timerentry_repeated.value == "user":
160                                 self.list.append(getConfigListEntry(_("Monday"), self.timerentry_day[0]))
161                                 self.list.append(getConfigListEntry(_("Tuesday"), self.timerentry_day[1]))
162                                 self.list.append(getConfigListEntry(_("Wednesday"), self.timerentry_day[2]))
163                                 self.list.append(getConfigListEntry(_("Thursday"), self.timerentry_day[3]))
164                                 self.list.append(getConfigListEntry(_("Friday"), self.timerentry_day[4]))
165                                 self.list.append(getConfigListEntry(_("Saturday"), self.timerentry_day[5]))
166                                 self.list.append(getConfigListEntry(_("Sunday"), self.timerentry_day[6]))
167
168                         #self.list.append(getConfigListEntry("StartDate", self.timerentry_startdate))
169 #               self.list.append(getConfigListEntry("Weekday", self.timerentry_weekday))
170
171                 self.entryStartDate = getConfigListEntry(_("Start"), self.timerentry_startdate)
172                 if self.timerentry_type.value == "once":
173                         self.list.append(self.entryStartDate)
174                         self.list.append(getConfigListEntry(" ", self.timerentry_starttime))
175                 else:
176                         self.list.append(getConfigListEntry(_("StartTime"), self.timerentry_starttime))
177
178                 self.entryEndDate = getConfigListEntry(_("End"), self.timerentry_enddate)
179                 if self.timerentry_type.value == "once":
180                         if self.timerentry_justplay.value != "zap":
181                                 self.list.append(self.entryEndDate)
182                                 self.list.append(getConfigListEntry(" ", self.timerentry_endtime))
183                 else:
184                         if self.timerentry_justplay.value != "zap":
185                                 self.list.append(getConfigListEntry(_("EndTime"), self.timerentry_endtime))
186
187                 if self.timerentry_justplay.value != "zap":
188                         if config.usage.setup_level.index >= 2: # expert+
189                                 self.dirname = getConfigListEntry(_("Location"), self.timerentry_dirname)
190                                 self.list.append(self.dirname)
191                         self.list.append(getConfigListEntry(_("After event"), self.timerentry_afterevent))
192
193                 self.channelEntry = getConfigListEntry(_("Channel"), self.timerentry_service)
194                 self.list.append(self.channelEntry)
195
196                 self[widget].list = self.list
197                 self[widget].l.setList(self.list)
198
199         def newConfig(self):
200                 print "newConfig", self["config"].getCurrent()
201                 if self["config"].getCurrent() == self.timerTypeEntry:
202                         self.createSetup("config")
203                 if self["config"].getCurrent() == self.timerJustplayEntry:
204                         self.createSetup("config")
205                 if self["config"].getCurrent() == self.frequencyEntry:
206                         self.createSetup("config")
207
208         def keyLeft(self):
209                 if self["config"].getCurrent() is self.channelEntry:
210                         self.keySelect()
211                 else:
212                         ConfigListScreen.keyLeft(self)
213                         self.newConfig()
214
215         def keyRight(self):
216                 if self["config"].getCurrent() is self.channelEntry:
217                         self.keySelect()
218                 else:
219                         ConfigListScreen.keyRight(self)
220                         self.newConfig()
221
222         def keySelect(self):
223                 cur = self["config"].getCurrent()
224                 if cur == self.channelEntry:
225                         self.session.openWithCallback(
226                                 self.finishedChannelSelection,
227                                 ChannelSelection.SimpleChannelSelection,
228                                 _("Select channel to record from")
229                         )
230                 elif config.usage.setup_level.index >= 2 and cur == self.dirname:
231                         self.session.openWithCallback(
232                                 self.pathSelected,
233                                 MovieLocationBox,
234                                 _("Choose target folder"),
235                                 self.timerentry_dirname.value,
236                                 minFree = 100 # We require at least 100MB free space
237                         )
238                 else:
239                         self.keyGo()
240
241         def finishedChannelSelection(self, *args):
242                 if len(args):
243                         self.timerentry_service_ref = ServiceReference(args[0])
244                         self.timerentry_service.setCurrentText(self.timerentry_service_ref.getServiceName())
245                         self["config"].invalidate(self.channelEntry)
246
247         def getTimestamp(self, date, mytime):
248                 d = localtime(date)
249                 dt = datetime(d.tm_year, d.tm_mon, d.tm_mday, mytime[0], mytime[1])
250                 return int(mktime(dt.timetuple()))
251
252         def buildRepeatedBegin(self, rep_time, start_time):
253                 d = localtime(rep_time)
254                 dt = datetime(d.tm_year, d.tm_mon, d.tm_mday, start_time[0], start_time[1])
255                 return int(mktime(dt.timetuple()))
256
257         def getBeginEnd(self):
258                 enddate = self.timerentry_enddate.value
259                 endtime = self.timerentry_endtime.value
260
261                 startdate = self.timerentry_startdate.value
262                 starttime = self.timerentry_starttime.value
263
264                 begin = self.getTimestamp(startdate, starttime)
265                 end = self.getTimestamp(enddate, endtime)
266
267                 # because of the dateChecks, startdate can't be < enddate.
268                 # however, the endtime can be less than the starttime.
269                 # in this case, add 1 day.
270                 if end < begin:
271                         end += 86400
272                 return begin, end
273
274         def keyGo(self):
275                 self.timer.name = self.timerentry_name.value
276                 self.timer.description = self.timerentry_description.value
277                 self.timer.justplay = self.timerentry_justplay.value == "zap"
278                 self.timer.resetRepeated()
279                 self.timer.afterEvent = {"nothing": AFTEREVENT.NONE, "deepstandby": AFTEREVENT.DEEPSTANDBY, "standby": AFTEREVENT.STANDBY}[self.timerentry_afterevent.value]
280                 self.timer.service_ref = self.timerentry_service_ref
281
282                 self.timer.dirname = self.timerentry_dirname.value
283                 config.movielist.last_timer_videodir.value = self.timer.dirname
284                 config.movielist.last_timer_videodir.save()
285
286                 if self.timerentry_type.value == "once":
287                         self.timer.begin, self.timer.end = self.getBeginEnd()
288                 if self.timerentry_type.value == "repeated":
289                         if self.timerentry_repeated.value == "daily":
290                                 for x in range(0,7):
291                                         self.timer.setRepeated(x)
292
293                         if self.timerentry_repeated.value == "weekly":
294                                 self.timer.setRepeated(self.timerentry_weekday.index)
295
296                         if self.timerentry_repeated.value == "weekdays":
297                                 for x in range(0,5):
298                                         self.timer.setRepeated(x)
299
300                         if self.timerentry_repeated.value == "user":
301                                 for x in range(0,7):
302                                         if self.timerentry_day[x].value:
303                                                 self.timer.setRepeated(x)
304
305                         self.timer.repeatedbegindate = self.getTimestamp(self.timerentry_repeatedbegindate.value, self.timerentry_starttime.value)
306                         if self.timer.repeated:
307                                 self.timer.begin = self.getTimestamp(self.timerentry_repeatedbegindate.value, self.timerentry_starttime.value)
308                                 self.timer.end = self.getTimestamp(self.timerentry_repeatedbegindate.value, self.timerentry_endtime.value)
309                         else:
310                                 self.timer.begin = self.getTimestamp(time.time(), self.timerentry_starttime.value)
311                                 self.timer.end = self.getTimestamp(time.time(), self.timerentry_endtime.value)
312
313                         # when a timer end is set before the start, add 1 day
314                         if self.timer.end < self.timer.begin:
315                                 self.timer.end += 86400
316
317                 if self.timer.eit is not None:
318                         event = eEPGCache.getInstance().lookupEventId(self.timer.service_ref.ref, self.timer.eit)
319                         if event is not None:
320                                 n = event.getNumOfLinkageServices()
321                                 if n > 0:
322                                         tlist = []
323                                         ref = self.session.nav.getCurrentlyPlayingServiceReference()
324                                         parent = self.timer.service_ref.ref
325                                         selection = 0
326                                         for x in range(n):
327                                                 i = event.getLinkageService(parent, x)
328                                                 if i.toString() == ref.toString():
329                                                         selection = x
330                                                 tlist.append((i.getName(), i))
331                                         self.session.openWithCallback(self.subserviceSelected, ChoiceBox, title=_("Please select a subservice to record..."), list = tlist, selection = selection)
332                                         return
333
334                 self.saveTimer()
335                 self.close((True, self.timer))
336
337         def subserviceSelected(self, service):
338                 if not service is None:
339                         self.timer.service_ref = ServiceReference(service[1])
340                 self.saveTimer()
341                 self.close((True, self.timer))
342
343         def saveTimer(self):
344                 self.session.nav.RecordTimer.saveTimer()
345
346         def keyCancel(self):
347                 self.close((False,))
348
349         def pathSelected(self, res):
350                 if res is not None:
351                         if config.movielist.videodirs.value != self.timerentry_dirname.choices:
352                                 self.timerentry_dirname.setChoices(config.movielist.videodirs.value, default=res)
353                         self.timerentry_dirname.value = res
354
355 class TimerLog(Screen):
356         def __init__(self, session, timer):
357                 Screen.__init__(self, session)
358                 self.timer = timer;
359                 self.log_entries = self.timer.log_entries[:]
360
361                 self.fillLogList()
362
363                 self["loglist"] = MenuList(self.list)
364                 self["logentry"] = Label()
365
366                 self["key_red"] = Button(_("Delete entry"))
367                 self["key_green"] = Button()
368                 self["key_yellow"] = Button("")
369                 self["key_blue"] = Button(_("Clear log"))
370
371                 self.onShown.append(self.updateText)
372
373                 self["actions"] = NumberActionMap(["OkCancelActions", "DirectionActions", "ColorActions"],
374                 {
375                         "ok": self.keyClose,
376                         "cancel": self.keyClose,
377                         "up": self.up,
378                         "down": self.down,
379                         "left": self.left,
380                         "right": self.right,
381                         "red": self.deleteEntry,
382                         "blue": self.clearLog
383                 }, -1)
384
385         def deleteEntry(self):
386                 cur = self["loglist"].getCurrent()
387                 if cur is None:
388                         return 
389                 self.log_entries.remove(cur[1])
390                 self.fillLogList()
391                 self["loglist"].l.setList(self.list)
392                 self.updateText()
393
394         def fillLogList(self):
395                 self.list = [ ]
396                 for x in self.log_entries:
397                         self.list.append((str(strftime("%Y-%m-%d %H-%M", localtime(x[0])) + " - " + x[2]), x))
398
399         def clearLog(self):
400                 self.log_entries = []
401                 self.fillLogList()
402                 self["loglist"].l.setList(self.list)
403                 self.updateText()
404
405         def keyClose(self):
406                 if self.timer.log_entries != self.log_entries:
407                         self.timer.log_entries = self.log_entries
408                         self.close((True, self.timer))
409                 else:
410                         self.close((False,))
411
412         def up(self):
413                 self["loglist"].instance.moveSelection(self["loglist"].instance.moveUp)
414                 self.updateText()
415
416         def down(self):
417                 self["loglist"].instance.moveSelection(self["loglist"].instance.moveDown)
418                 self.updateText()
419
420         def left(self):
421                 self["loglist"].instance.moveSelection(self["loglist"].instance.pageUp)
422                 self.updateText()
423
424         def right(self):
425                 self["loglist"].instance.moveSelection(self["loglist"].instance.pageDown)
426                 self.updateText()
427
428         def updateText(self):
429                 if len(self.list) > 0:
430                         self["logentry"].setText(str(self["loglist"].getCurrent()[1][2]))
431                 else:
432                         self["logentry"].setText("")