treewide: remove references to /media/cf and /media/usb
[enigma2-plugins.git] / tvcharts / src / plugin.py
1 #####################################################
2 # TVCharts Plugin for Enigma2 Dreamboxes
3 # Coded by Homey (c) 2011
4 #
5 # Version: 1.5
6 # Support: www.i-have-a-dreambox.com
7 #####################################################
8 from Components.About import about
9 from Components.ActionMap import ActionMap
10 from Components.Button import Button
11 from Components.config import config, configfile, getConfigListEntry, ConfigSubsection, ConfigYesNo, ConfigInteger, ConfigSelection
12 from Components.ConfigList import ConfigList, ConfigListScreen
13 from Components.Label import Label
14 from Components.MenuList import MenuList
15 from Components.MultiContent import MultiContentEntryText, MultiContentEntryPixmapAlphaTest
16 from Components.ServiceEventTracker import ServiceEventTracker
17 from Components.Sources.StaticText import StaticText
18 from Components.UsageConfig import preferredTimerPath
19 from Components.Pixmap import Pixmap
20 from RecordTimer import RecordTimer, RecordTimerEntry, parseEvent
21 from ServiceReference import ServiceReference
22 from Screens.EventView import EventViewSimple
23 from Screens.MessageBox import MessageBox
24 from Screens.Screen import Screen
25 from Screens.Setup import SetupSummary
26 from Screens.TimerEntry import TimerEntry
27 from Screens.TimerEdit import TimerSanityConflict
28 from Tools.Directories import fileExists
29 from Tools.HardwareInfo import HardwareInfo
30 from Plugins.Plugin import PluginDescriptor
31 from Components.Network import iNetworkInfo
32
33 from enigma import eTimer, eEPGCache, loadPNG, eListboxPythonMultiContent, gFont, eServiceReference, eServiceCenter, iPlayableService
34 from random import randint
35 from os import system as os_system
36 from time import time, gmtime, strftime
37 from twisted.web.client import getPage
38 from xml.dom.minidom import parse, parseString
39 from urllib import urlencode
40
41 import timer
42 import xml.etree.cElementTree
43 import Screens.Standby
44
45 ##############################
46 #####  CONFIG SETTINGS   #####
47 ##############################
48 config.plugins.tvcharts = ConfigSubsection()
49 config.plugins.tvcharts.enabled = ConfigYesNo(default = True)
50 config.plugins.tvcharts.maxentries = ConfigInteger(default=10, limits=(5, 100))
51 config.plugins.tvcharts.maxtimerentries = ConfigInteger(default=10, limits=(5, 100))
52 config.plugins.tvcharts.submittimers = ConfigYesNo(default = True)
53 config.plugins.tvcharts.submitplugins = ConfigYesNo(default = True)
54 config.plugins.tvcharts.bouquetfilter = ConfigYesNo(default = True)
55
56 ##########################################################
57 session = [ ]
58
59 #Channellist Menu Entry
60 class ChannelListMenu(MenuList):
61         def __init__(self, list, enableWrapAround=False):
62                 MenuList.__init__(self, list, enableWrapAround, eListboxPythonMultiContent)
63                 self.l.setFont(0, gFont("Regular", 24))
64                 self.l.setFont(1, gFont("Regular", 20))
65                 self.l.setFont(2, gFont("Regular", 16))
66                 self.l.setItemHeight(76)
67
68 def ChannelListEntryComponent(type, channelname, serviceref, eventid, eventname, starttime, endtime, usercount, percent):
69         res = [ (serviceref, eventid) ]
70
71         # PIXMAP / PICON
72         pixmap = "/usr/share/enigma2/skin_default/picon_default.png"
73         searchPaths = ('/usr/share/enigma2/picon/',)
74
75         srefstring = serviceref
76         pos = srefstring.rfind(':')
77         if pos != -1:
78                 srefstring = srefstring[:pos].rstrip(':').replace(':','_')
79                 for path in searchPaths:
80                         pngname = path + srefstring + ".png"
81                         if fileExists(pngname):
82                                 pixmap = pngname
83
84         # Build Menu
85         if type == "tvcharts":
86                 res.append(MultiContentEntryPixmapAlphaTest(pos=(8, 8), size=(100, 60), png=loadPNG(pixmap)))
87                 res.append(MultiContentEntryText(pos=(130, 5), size=(480, 30), font=0, text="%s (Viewer: %s)" % (channelname, usercount)))
88                 res.append(MultiContentEntryText(pos=(130, 35), size=(480, 25), font=1, text=eventname))
89         elif type == "timercharts":
90                 res.append(MultiContentEntryPixmapAlphaTest(pos=(10, 10), size=(100, 60), png=loadPNG(pixmap)))
91                 res.append(MultiContentEntryText(pos=(130, 5), size=(480, 28), font=0, text="%s (User: %s)" % (channelname, usercount)))
92                 res.append(MultiContentEntryText(pos=(130, 33), size=(480, 25), font=1, text=eventname))
93                 res.append(MultiContentEntryText(pos=(130, 57), size=(480, 20), font=2, text="%s Uhr - %s Uhr (%smin)" % (strftime("%d.%m.%Y %H:%M", gmtime(starttime)), strftime("%H:%M", gmtime(endtime)), int((endtime-starttime)/60))))
94         elif type == "moviecharts":
95                 res.append(MultiContentEntryPixmapAlphaTest(pos=(8, 8), size=(100, 60), png=loadPNG(pixmap)))
96                 res.append(MultiContentEntryText(pos=(130, 5), size=(480, 30), font=0, text=eventname))
97                 res.append(MultiContentEntryText(pos=(130, 33), size=(480, 25), font=1, text="Viewer: %s" % (usercount)))
98                 res.append(MultiContentEntryText(pos=(130, 57), size=(480, 20), font=2, text="%s Uhr - %s" % (strftime("%d.%m.%Y %H:%M", gmtime(starttime)), channelname)))
99
100         return res
101
102 ##############################
103 #####   TV Charts MAIN   #####
104 ##############################
105
106 class TVChartsMain(Screen):
107
108         skin = """
109         <screen position="center,center" size="620,510" title="TV Charts">
110                 <widget name="channellist" position="10,10" zPosition="1" size="600,458" scrollbarMode="showOnDemand" />
111                 <widget name="info" position="0,447" zPosition="2" size="620,20" font="Regular;18" noWrap="1" foregroundColor="#ffffff" transparent="1" halign="center" valign="center" />
112                 <ePixmap name="red"    position="22,470"  zPosition="3" size="140,40" pixmap="/usr/share/enigma2/skin_default/buttons/red.png" transparent="1" alphatest="on" />
113                 <ePixmap name="green"  position="167,470" zPosition="3" size="140,40" pixmap="/usr/share/enigma2/skin_default/buttons/green.png" transparent="1" alphatest="on" />
114                 <ePixmap name="yellow" position="312,470" zPosition="3" size="140,40" pixmap="/usr/share/enigma2/skin_default/buttons/yellow.png" transparent="1" alphatest="on" />
115                 <ePixmap name="blue"   position="457,470" zPosition="3" size="140,40" pixmap="/usr/share/enigma2/skin_default/buttons/blue.png" transparent="1" alphatest="on" />
116                 <widget name="key_red" position="22,470" zPosition="4" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
117                 <widget name="key_green" position="167,470" zPosition="4" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
118                 <widget name="key_yellow" position="312,470" zPosition="4" size="140,40" valign="center" halign="center"  font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
119                 <widget name="key_blue" position="457,470" zPosition="4" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
120         </screen>"""
121
122         def __init__(self, session):
123                 Screen.__init__(self, session)
124
125                 self.session = session
126
127                 self["channellist"] = ChannelListMenu([])
128                 self["info"] = Label()
129
130                 self["key_red"] = Button("TV Charts")
131                 self["key_green"] = Button("Timer Charts")
132                 self["key_yellow"] = Button("Movie Charts")
133                 self["key_blue"] = Button("Settings")
134
135                 self["actions"] = ActionMap(["OkCancelActions", "ColorActions", "EPGSelectActions"],
136                 {
137                         "ok": self.okClicked,
138                         "red": self.switchToTVCharts,
139                         "green": self.switchToTimerCharts,
140                         "yellow": self.switchToMovieCharts,
141                         "blue": self.SettingsMenu,
142                         "info": self.ShowEventInfo,
143                         "cancel": self.close
144                 }, -1)
145
146                 self.epgcache = eEPGCache.getInstance()
147                 self.eventcache = []
148
149                 self.RefreshTimer = eTimer()
150                 self.RefreshTimer_conn = self.RefreshTimer.timeout.connect(self.downloadList)
151
152                 self.onLayoutFinish.append(self.firstPluginExec)
153
154         def firstPluginExec(self):
155                 self.updateEventCache()
156                 self.switchToTVCharts()
157
158         def okClicked(self):
159                 current = self["channellist"].getCurrent()
160                 if current is None:
161                         return
162
163                 if self.mode == "tvcharts":
164                         service = eServiceReference(str(current[0][0]))
165                         self.session.nav.playService(service)
166                 elif self.mode == "timercharts":
167                         serviceref = ServiceReference(current[0][0])
168                         eventid = int(current[0][1])
169                         event = self.getEventFromId(serviceref, eventid)
170                         if event is not None:
171                                 newEntry = RecordTimerEntry(serviceref, *parseEvent(event), checkOldTimers = True, dirname = preferredTimerPath())
172                                 self.session.openWithCallback(self.addTimerCallback, TimerEntry, newEntry)
173                         else:
174                                 self.session.open(MessageBox, "Sorry, no EPG Info available for this event", type=MessageBox.TYPE_ERROR, timeout=10)
175                 elif self.mode == "moviecharts":
176                         print "[TVCharts] ToDo: Show Movie Info here ..."
177                         return
178
179         def addTimerCallback(self, answer):
180                 if answer[0]:
181                         entry = answer[1]
182                         simulTimerList = self.session.nav.RecordTimer.record(entry)
183                         if simulTimerList is not None:
184                                 for x in simulTimerList:
185                                         if x.setAutoincreaseEnd(entry):
186                                                 self.session.nav.RecordTimer.timeChanged(x)
187                                 simulTimerList = self.session.nav.RecordTimer.record(entry)
188                                 if simulTimerList is not None:
189                                         self.session.openWithCallback(self.finishSanityCorrection, TimerSanityConflict, simulTimerList)
190                 else:
191                         print "Timeredit aborted"
192
193         def finishSanityCorrection(self, answer):
194                 self.addTimerCallback(answer)
195
196         def SettingsMenu(self):
197                 self.session.open(TVChartsSetup)
198
199         def ShowEventInfo(self):
200                 current = self["channellist"].getCurrent()
201                 if current is None:
202                         return
203
204                 serviceref = current[0][0]
205                 eventid = current[0][1]
206
207                 service = ServiceReference(serviceref)
208                 event = self.getEventFromId(service, eventid)
209
210                 if event is not None:
211                         self.session.open(EventViewSimple, event, service)
212
213         def getEventFromId(self, service, eventid):
214                 event = None
215                 if self.epgcache is not None and eventid is not None:
216                         event = self.epgcache.lookupEventId(service.ref, eventid)
217                 return event
218
219         def updateEventCache(self):
220                 try:
221                         from Screens.ChannelSelection import service_types_tv
222                         from Components.Sources.ServiceList import ServiceList
223                         bouquetlist = ServiceList(eServiceReference(service_types_tv + ' FROM BOUQUET "bouquets.tv" ORDER BY bouquet'), validate_commands=False).getServicesAsList()
224                         for bouquetitem in bouquetlist:
225                                 serviceHandler = eServiceCenter.getInstance()
226                                 list = serviceHandler.list(eServiceReference(str(bouquetitem[0])))
227                                 services = list and list.getContent('S')
228                                 search = ['IBDCTSERNX']
229
230                                 if services: # It's a Bouquet
231                                         search.extend([(service, 0, -1) for service in services])
232
233                                 events = self.epgcache.lookupEvent(search)
234
235                                 for eventinfo in events:
236                                         #0 eventID | 4 eventname | 5 short descr | 6 long descr | 7 serviceref | 8 channelname
237                                         self.eventcache.append((eventinfo[0], eventinfo[7], eventinfo[8], eventinfo[4]))
238
239                 except Exception:
240                         print "[TVCharts Plugin] Error creating eventcache!"
241
242         def switchToTVCharts(self):
243                 self.mode = "tvcharts"
244                 self.setTitle("TV Charts")
245                 self["channellist"].setList([])
246                 self.feedurl = "http://www.dreambox-plugins.de/feeds/topchannels.php"
247                 self.downloadList()
248
249         def switchToTimerCharts(self):
250                 self.mode = "timercharts"
251                 self.setTitle("Timer Charts")
252                 self["channellist"].setList([])
253                 self.feedurl = "http://www.dreambox-plugins.de/feeds/toptimers.php?limit=%s" % config.plugins.tvcharts.maxtimerentries.value
254                 self.downloadList()
255
256         def switchToMovieCharts(self):
257                 self.mode = "moviecharts"
258                 self.setTitle("Movie Charts")
259                 self["channellist"].setList([])
260                 self.feedurl = "http://www.dreambox-plugins.de/feeds/topmovies.php"
261                 self.downloadList()
262
263         def downloadList(self):
264                 if config.plugins.tvcharts.enabled.value:
265                         self["info"].setText("Downloading feeds from server ...")
266                         getPage(self.feedurl).addCallback(self.downloadListCallback).addErrback(self.downloadListError)
267                 else:
268                         self["info"].setText("Error: Plugin disabled in Settings ...")
269
270         def downloadListError(self, error=""):
271                 print str(error)
272                 self.session.open(MessageBox, "Error downloading Feed:\n%s" % str(error), type=MessageBox.TYPE_ERROR)
273                 self["info"].setText("Error downloading Feed!")
274
275         def downloadListCallback(self, page=""):
276                 self["info"].setText("Parsing Feeds ...")
277
278                 channellist = []
279                 channelcount = 0
280                 useronline = 0
281                 totalusers = 0
282                 totaltimer = 0
283                 totalmovies = 0
284                 xml = parseString(page)
285
286                 if self.mode == "tvcharts":
287                         for node in xml.getElementsByTagName("DATA"):
288                                 useronline = int(node.getElementsByTagName("USERCOUNT")[0].childNodes[0].data)
289                                 totalusers = int(node.getElementsByTagName("TOTALUSERS")[0].childNodes[0].data)
290
291                         for node in xml.getElementsByTagName("CHANNEL"):
292                                 event_id = None
293                                 inBouquet = False
294                                 channelname =str(node.getElementsByTagName("NAME")[0].childNodes[0].data)
295                                 serviceref = str(node.getElementsByTagName("SERVICEREF")[0].childNodes[0].data)
296                                 eventname = str(node.getElementsByTagName("EVENTNAME")[0].childNodes[0].data)
297                                 usercount = int(node.getElementsByTagName("USERCOUNT")[0].childNodes[0].data)
298                                 percent = int(node.getElementsByTagName("PERCENT")[0].childNodes[0].data)
299
300                                 # Look for favourite channel for this event in my bouqets
301                                 for sepginfo in self.eventcache:
302                                         if sepginfo[2] == channelname:
303                                                 inBouquet = True
304                                         if sepginfo[3] == eventname:
305                                                 event_id = sepginfo[0]
306                                         if sepginfo[3] == eventname and sepginfo[1] != serviceref:
307                                                 if channelname[0:3].lower() == sepginfo[2][0:3].lower():
308                                                         serviceref = sepginfo[1]
309                                                         channelname = sepginfo[2]
310                                                 inBouquet = True
311                                                 break
312                                         elif sepginfo[3] == eventname and sepginfo[1] == serviceref:
313                                                 break
314
315                                 # Skip Channels that are not in my bouquets
316                                 if config.plugins.tvcharts.bouquetfilter.value and not inBouquet:
317                                         continue
318
319                                 # Skip Channels that are not in my bouquets
320                                 channelcount += 1
321                                 if channelcount > config.plugins.tvcharts.maxentries.value:
322                                         break
323
324                                 # Add to List
325                                 channellist.append(ChannelListEntryComponent(self.mode, channelname, serviceref, event_id, eventname, 0, 0, usercount, percent))
326
327                         if totalusers > 0:
328                                 self.setTitle("TV Charts (User online: %s of %s)" % (useronline, totalusers))
329
330                 elif self.mode == "timercharts":
331                         for node in xml.getElementsByTagName("DATA"):
332                                 totaltimer = int(node.getElementsByTagName("TIMERCOUNT")[0].childNodes[0].data)
333
334                         for node in xml.getElementsByTagName("TIMER"):
335                                 eitID = int(node.getElementsByTagName("ID")[0].childNodes[0].data)
336                                 channelname = str(node.getElementsByTagName("CHANNELNAME")[0].childNodes[0].data)
337                                 serviceref = str(node.getElementsByTagName("SERVICEREF")[0].childNodes[0].data)
338                                 eventname = str(node.getElementsByTagName("EVENTNAME")[0].childNodes[0].data)
339                                 starttime = int(node.getElementsByTagName("STARTTIME")[0].childNodes[0].data)
340                                 endtime = int(node.getElementsByTagName("ENDTIME")[0].childNodes[0].data)
341                                 usercount = int(node.getElementsByTagName("USERCOUNT")[0].childNodes[0].data)
342                                 percent = int(node.getElementsByTagName("PERCENT")[0].childNodes[0].data)
343
344                                 # Look for favourite channel for this event in my bouqets
345                                 for sepginfo in self.eventcache:
346                                         if sepginfo[2] == channelname:
347                                                 serviceref = sepginfo[1]
348                                                 channelname = sepginfo[2]
349                                                 inBouquet = True
350                                                 break
351
352                                 # Add to List
353                                 channellist.append(ChannelListEntryComponent(self.mode, channelname, serviceref, eitID, eventname, starttime, endtime, usercount, percent))
354
355                         if totaltimer > 0:
356                                 self.setTitle("Timer Charts (Total Timer: %s)" % (totaltimer))
357
358                 elif self.mode == "moviecharts":
359                         for node in xml.getElementsByTagName("DATA"):
360                                 totalmovies = int(node.getElementsByTagName("MOVIECOUNT")[0].childNodes[0].data)
361
362                         for node in xml.getElementsByTagName("MOVIE"):
363                                 eventid = int(node.getElementsByTagName("EVENTID")[0].childNodes[0].data)
364                                 eventname = str(node.getElementsByTagName("EVENTNAME")[0].childNodes[0].data)
365                                 channelname = str(node.getElementsByTagName("CHANNELNAME")[0].childNodes[0].data)
366                                 serviceref = str(node.getElementsByTagName("SERVICEREF")[0].childNodes[0].data)
367                                 starttime = int(node.getElementsByTagName("STARTTIME")[0].childNodes[0].data)
368                                 usercount = int(node.getElementsByTagName("USERCOUNT")[0].childNodes[0].data)
369
370                                 # Add to List
371                                 channellist.append(ChannelListEntryComponent(self.mode, channelname, serviceref, eventid, eventname, starttime, 0, usercount, 0))
372
373                         #if totalmovies > 0:
374                         #       self.setTitle("Movie Charts (Total Movies: %s)" % (totalmovies))
375
376                 self["info"].setText("")
377                 self["channellist"].setList(channellist)
378
379                 self.RefreshTimer.start(60000, True)
380
381 ############################
382 #####  SETTINGS SCREEN #####
383 ############################
384 class TVChartsSetup(Screen, ConfigListScreen):
385         def __init__(self, session):
386                 Screen.__init__(self, session)
387                 self.skinName = [ "TVChartsSetup", "Setup" ]
388                 self.setup_title = _("TV Charts Settings")
389
390                 self.onChangedEntry = [ ]
391                 self.list = [ ]
392                 ConfigListScreen.__init__(self, self.list, session = session, on_change = self.changedEntry)
393
394                 self["actions"] = ActionMap(["SetupActions", "ColorActions"],
395                 {
396                         "ok": self.SaveSettings,
397                         "green": self.SaveSettings,
398                         "red": self.Exit,
399                         "cancel": self.Exit
400                 }, -2)
401
402                 self["key_green"] = StaticText(_("OK"))
403                 self["key_red"] = StaticText(_("Cancel"))
404
405                 self.createSetup()
406                 self.onLayoutFinish.append(self.layoutFinished)
407
408         def layoutFinished(self):
409                 self.setTitle(self.setup_title)
410
411         def createSetup(self):
412                 self.list = [ getConfigListEntry(_("TV Charts Plugin Enable"), config.plugins.tvcharts.enabled) ]
413                 if config.plugins.tvcharts.enabled.value:
414                         self.list.extend((
415                                 getConfigListEntry(_("Max Toplist Entries"), config.plugins.tvcharts.maxentries),
416                                 getConfigListEntry(_("Max Timerlist Entries"), config.plugins.tvcharts.maxtimerentries),
417                                 getConfigListEntry(_("Enable Bouquet-Filter?"), config.plugins.tvcharts.bouquetfilter),
418                                 getConfigListEntry(_("Submit Timerlist?"), config.plugins.tvcharts.submittimers),
419                                 getConfigListEntry(_("Submit Pluginlist?"), config.plugins.tvcharts.submitplugins)
420                         ))
421
422                 self["config"].list = self.list
423                 self["config"].setList(self.list)
424
425         def keyLeft(self):
426                 ConfigListScreen.keyLeft(self)
427                 if self["config"].getCurrent()[1] == config.plugins.tvcharts.enabled:
428                         self.createSetup()
429
430         def keyRight(self):
431                 ConfigListScreen.keyRight(self)
432                 if self["config"].getCurrent()[1] == config.plugins.tvcharts.enabled:
433                         self.createSetup()
434
435         def changedEntry(self):
436                 for x in self.onChangedEntry:
437                         x()
438
439         def getCurrentEntry(self):
440                 return self["config"].getCurrent()[0]
441
442         def getCurrentValue(self):
443                 return str(self["config"].getCurrent()[1].getText())
444
445         def createSummary(self):
446                 return SetupSummary
447
448         def SaveSettings(self):
449                 config.plugins.tvcharts.save()
450                 configfile.save()
451                 self.close()
452
453         def Exit(self):
454                 self.close()
455
456
457 ##############################
458 #####   UPDATE STATUS    #####
459 ##############################
460 class DBUpdateStatus(Screen):
461         def __init__(self, session):
462                 Screen.__init__(self, session)
463
464                 self.DBStatusTimer = eTimer()
465                 self.DBStatusTimer_conn = self.DBStatusTimer.timeout.connect(self.updateStatus)
466
467                 self.__event_tracker = ServiceEventTracker(screen = self, eventmap =
468                         {
469                                 iPlayableService.evUpdatedInfo: self.restartTimer,
470                                 iPlayableService.evUpdatedEventInfo: self.restartTimer
471                         })
472
473                 self.recordtimer = session.nav.RecordTimer
474                 self.NetworkConnectionAvailable = False
475                 self.LastTimerlistUpdate = 0
476                 
477                 self.timerlist = ""
478                 self.pluginlist = ""
479
480                 self.onShow.append(self.restartTimer)
481
482         def restartTimer(self):
483                 if self.NetworkConnectionAvailable:
484                         self.DBStatusTimer.stop()
485                         self.DBStatusTimer.start((randint(15,60))*1000, True)
486                 else:
487                         self.checkNetwork()
488
489         def checkNetwork(self):
490                 if iNetworkInfo.isConnected():
491                         self.NetworkConnectionAvailable = True
492                         self.restartTimer()
493                 else:
494                         self.NetworkConnectionAvailable = False
495                         self.DBStatusTimer.stop()
496
497         def updateStatus(self):
498                 print "[TVCharts] Status Update ..."
499                 self.DBStatusTimer.stop()
500
501                 if not config.plugins.tvcharts.enabled.value or Screens.Standby.inStandby:
502                         return
503
504                 # Get Channelname
505                 sref = self.session.nav.getCurrentlyPlayingServiceReference()
506                 if sref is not None:
507                         ref = eServiceReference(sref.toString())
508                         ref.setName("")
509                         serviceHandler = eServiceCenter.getInstance()
510                         info = serviceHandler.info(ref)
511                         channel_name = info and info.getName(ref).replace('\xc2\x86', '').replace('\xc2\x87', '').decode("utf-8", "ignore").encode("utf-8") or ""
512                         self.serviceref = ref.toString()
513                 else:
514                         channel_name = ""
515                         self.serviceref = ""
516
517                 # Get Event Info
518                 service = self.session.nav.getCurrentService()
519                 info = service and service.info()
520                 event = info and info.getEvent(0)
521                 event_name = event and event.getEventName() or ""
522                 event_description = ""
523                 event_begin = 0
524
525                 if event is not None:
526                         curEvent = parseEvent(event)
527                         event_begin = int(curEvent[0])+(config.recording.margin_before.value*60)
528                         event_description = event.getExtendedDescription()
529
530                 # Get Box Info
531                 ifaces = iNetworkInfo.getConfiguredInterfaces()
532                 iface = None
533                 if len(ifaces) > 0:
534                         iface = ifaces.get(
535                                         "eth0",
536                                         ifaces.get(ifaces.keys()[0])
537                                 )
538                 if not iface:
539                         return
540                 self.BoxID = iface.ethernet.mac
541                 self.DeviceName = HardwareInfo().get_device_name()
542                 self.EnigmaVersion = about.getEnigmaVersionString()
543                 self.ImageVersion = about.getVersionString()
544
545                 # Get TimerList
546                 self.timerlist = ""
547                 if config.plugins.tvcharts.submittimers.value and self.LastTimerlistUpdate <= (time()-1800):
548                         self.LastTimerlistUpdate = time()
549                         try:
550                                 for timer in self.recordtimer.timer_list:
551                                         if timer.disabled == 0 and timer.justplay == 0:
552                                                 self.timerlist += "%s|%s|%s|%s|%s|%s|%s\n" % (timer.eit,str(int(timer.begin)+(config.recording.margin_before.value*60)), str(int(timer.end)-(config.recording.margin_after.value*60)), str(timer.service_ref), timer.name, timer.service_ref.getServiceName().replace('\xc2\x86', '').replace('\xc2\x87', '').decode("utf-8", "ignore").encode("utf-8"), timer.repeated)
553                         except Exception:
554                                 print "[TVCharts] Error loading timers!"
555
556                 # Get Pluginlist
557                 if config.plugins.tvcharts.submitplugins.value and self.pluginlist == "":
558                         try:
559                                 os_system("opkg list_installed | grep enigma2-plugin- > /tmp/plugins.txt")
560                                 for plugin in open('/tmp/plugins.txt', 'r'):
561                                         self.pluginlist += plugin[0:plugin.find(' - ')]+"\n"
562                                 os_system("rm -f /tmp/plugins.txt")
563                         except Exception:
564                                 print "[TVCharts] Error loading plugins!"
565                 
566                 # Status Update
567                 getPage(url='http://www.dreambox-plugins.de/feeds/TVCharts/status.php', agent="Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; en-US)", timeout=60, method='POST', headers={'Content-Type':'application/x-www-form-urlencoded'}, postdata=urlencode({'boxid' : self.BoxID, 'devicename' : self.DeviceName, 'imageversion' : self.ImageVersion, 'enigmaversion' : self.EnigmaVersion, 'lastchannel' : channel_name, 'lastevent' : event_name, 'eventdescr' : event_description, 'lastbegin' : event_begin, 'lastserviceref' : self.serviceref, 'timerlist' : self.timerlist, 'pluginlist' : self.pluginlist})).addErrback(self.updateError)
568
569                 # Restart Timer
570                 self.DBStatusTimer.start(900000, True)
571
572         def updateError(self, error=""):
573                 self.NetworkConnectionAvailable = False
574                 self.DBStatusTimer.stop()
575
576 #############################
577 #####    INIT PLUGIN    #####
578 #############################
579 def main(session, **kwargs):
580         session.open(TVChartsMain)
581
582 def autostart(reason, **kwargs):
583         global session
584         if "session" in kwargs:
585                 session = kwargs["session"]
586                 DBUpdateStatus(session)
587
588 def Plugins(path, **kwargs):
589         return [
590                 PluginDescriptor(where = [PluginDescriptor.WHERE_SESSIONSTART], fnc = autostart),
591                 PluginDescriptor(name="TV Charts", description="TV Charts Plugin", icon="plugin.png", where=PluginDescriptor.WHERE_EXTENSIONSMENU, fnc=main),
592                 PluginDescriptor(name="TV Charts", description="TV Charts Plugin", icon="plugin.png", where=PluginDescriptor.WHERE_PLUGINMENU, fnc=main) ]