cleanup
[enigma2-plugins.git] / mytube / src / plugin.py
1 from __init__ import _
2 from Plugins.Plugin import PluginDescriptor
3 from MyTubeService import GoogleSuggestions
4 from MyTubeSearch import ConfigTextWithGoogleSuggestions
5 from Tools.BoundFunction import boundFunction
6 from Screens.MessageBox import MessageBox
7 from Screens.Screen import Screen
8 from Screens.ChoiceBox import ChoiceBox
9 from Screens.InfoBar import MoviePlayer
10 from Screens.VirtualKeyBoard import VirtualKeyBoard
11 from Components.ActionMap import ActionMap, NumberActionMap
12 from Components.Label import Label
13 from Components.ScrollLabel import ScrollLabel
14 from Components.ProgressBar import ProgressBar
15 from Components.Pixmap import Pixmap
16 from Components.Button import Button
17 from Components.Sources.List import List
18 from Components.MultiContent import MultiContentEntryText, MultiContentEntryPixmapAlphaTest
19 from Components.AVSwitch import AVSwitch
20 from Components.ActionMap import HelpableActionMap
21 from Components.config import config, Config, ConfigSelection, ConfigSubsection, ConfigText, getConfigListEntry, ConfigYesNo, ConfigIP, ConfigNumber,ConfigLocations
22 from Components.config import KEY_DELETE, KEY_BACKSPACE, KEY_LEFT, KEY_RIGHT, KEY_HOME, KEY_END, KEY_TOGGLEOW, KEY_ASCII, KEY_TIMEOUT
23 from Components.ConfigList import ConfigListScreen
24 from Components.ServiceEventTracker import ServiceEventTracker, InfoBarBase
25 from Components.Console import Console
26 from Components.Sources.Source import Source
27 from Components.Task import Task, Job, job_manager
28
29 from threading import Thread
30 from threading import Condition
31
32 from Tools.Directories import pathExists, fileExists, resolveFilename, SCOPE_PLUGINS, SCOPE_SKIN_IMAGE, SCOPE_HDD
33 from Tools.LoadPixmap import LoadPixmap
34 from Tools.Downloader import HTTPProgressDownloader, downloadWithProgress
35 from enigma import eTimer, quitMainloop,eListbox,ePoint, RT_HALIGN_LEFT, RT_HALIGN_RIGHT, RT_VALIGN_CENTER, eListboxPythonMultiContent, eListbox, gFont, getDesktop, ePicLoad, eServiceCenter, iServiceInformation, eServiceReference,iSeekableService,iServiceInformation, iPlayableService, iPlayableServicePtr
36 from os import path as os_path, system as os_system, unlink, stat, mkdir, popen, makedirs, listdir, access, rename, remove, W_OK, R_OK, F_OK
37 from twisted.web import client
38 from twisted.internet import reactor
39 from time import time
40
41 from Screens.InfoBarGenerics import InfoBarShowHide, InfoBarSeek, InfoBarNotifications, InfoBarServiceNotifications
42
43 config.plugins.mytube = ConfigSubsection()
44 config.plugins.mytube.search = ConfigSubsection()
45
46 config.plugins.mytube.search.searchTerm = ConfigTextWithGoogleSuggestions("", False, threaded = True)
47 config.plugins.mytube.search.orderBy = ConfigSelection(
48                                 [
49                                  ("relevance", _("Relevance")),
50                                  ("viewCount", _("View Count")),
51                                  ("published", _("Published")),
52                                  ("rating", _("Rating"))
53                                 ], "relevance")
54 config.plugins.mytube.search.time = ConfigSelection(
55                                 [
56                                  ("all_time", _("All Time")),
57                                  ("this_month", _("This Month")),
58                                  ("this_week", _("This Week")),
59                                  ("today", _("Today"))
60                                 ], "all_time")
61 config.plugins.mytube.search.racy = ConfigSelection(
62                                 [
63                                  ("include", _("Yes")),
64                                  ("exclude", _("No"))
65                                 ], "include")
66 config.plugins.mytube.search.categories = ConfigSelection(
67                                 [
68                                  (None, _("All")),
69                                  ("Film", _("Film & Animation")),
70                                  ("Autos", _("Autos & Vehicles")),
71                                  ("Music", _("Music")),
72                                  ("Animals", _("Pets & Animals")),
73                                  ("Sports", _("Sports")),
74                                  ("Travel", _("Travel & Events")),
75                                  ("Shortmov", _("Short Movies")),
76                                  ("Games", _("Gaming")),
77                                  ("Comedy", _("Comedy")),
78                                  ("People", _("People & Blogs")),
79                                  ("News", _("News & Politics")),
80                                  ("Entertainment", _("Entertainment")),
81                                  ("Education", _("Education")),
82                                  ("Howto", _("Howto & Style")),
83                                  ("Nonprofit", _("Nonprofits & Activism")),
84                                  ("Tech", _("Science & Technology"))
85                                 ], None)
86 config.plugins.mytube.search.lr = ConfigSelection(
87                                 [
88                                  (None, _("All")),
89                                  ("au", _("Australia")),
90                                  ("br", _("Brazil")),
91                                  ("ca", _("Canada")),
92                                  ("cz", _("Czech Republic")),
93                                  ("fr", _("France")),
94                                  ("de", _("Germany")),
95                                  ("gb", _("Great Britain")),
96                                  ("au", _("Australia")),
97                                  ("nl", _("Holland")),
98                                  ("hk", _("Hong Kong")),
99                                  ("in", _("India")),
100                                  ("ie", _("Ireland")),
101                                  ("il", _("Israel")),
102                                  ("it", _("Italy")),
103                                  ("jp", _("Japan")),
104                                  ("mx", _("Mexico")),
105                                  ("nz", _("New Zealand")),
106                                  ("pl", _("Poland")),
107                                  ("ru", _("Russia")),
108                                  ("kr", _("South Korea")),
109                                  ("es", _("Spain")),
110                                  ("se", _("Sweden")),
111                                  ("tw", _("Taiwan")),
112                                  ("us", _("United States")) 
113                                 ], None)
114 config.plugins.mytube.search.sortOrder = ConfigSelection(
115                                 [
116                                  ("ascending", _("Ascending")),
117                                  ("descending", _("Descending"))
118                                 ], "ascending")
119
120 config.plugins.mytube.general = ConfigSubsection()
121 config.plugins.mytube.general.showHelpOnOpen = ConfigYesNo(default = True)
122 config.plugins.mytube.general.loadFeedOnOpen = ConfigYesNo(default = True)
123 config.plugins.mytube.general.startFeed = ConfigSelection(
124                                 [
125                                  ("hd", _("HD videos")),
126                                  ("most_viewed", _("Most viewed")),
127                                  ("top_rated", _("Top rated")),
128                                  ("recently_featured", _("Recently featured")),
129                                  ("most_discussed", _("Most discussed")),
130                                  ("top_favorites", _("Top favorites")),
131                                  ("most_linked", _("Most linked")),
132                                  ("most_responded", _("Most responded")),
133                                  ("most_recent", _("Most recent"))
134                                 ], "most_viewed")
135 config.plugins.mytube.general.on_movie_stop = ConfigSelection(default = "ask", choices = [
136         ("ask", _("Ask user")), ("quit", _("Return to movie list")), ("playnext", _("Play next video")), ("playagain", _("Play video again")) ])
137
138 config.plugins.mytube.general.on_exit = ConfigSelection(default = "ask", choices = [
139         ("ask", _("Ask user")), ("quit", _("Return to movie list"))])
140
141 default = resolveFilename(SCOPE_HDD)
142 tmp = config.movielist.videodirs.value
143 if default not in tmp:
144         tmp.append(default)
145 config.plugins.mytube.general.videodir = ConfigSelection(default = default, choices = tmp)
146 config.plugins.mytube.general.history = ConfigText(default="")
147 config.plugins.mytube.general.clearHistoryOnClose = ConfigYesNo(default = False)
148 #config.plugins.mytube.general.useHTTPProxy = ConfigYesNo(default = False)
149 #config.plugins.mytube.general.ProxyIP = ConfigIP(default=[0,0,0,0])
150 #config.plugins.mytube.general.ProxyPort = ConfigNumber(default=8080)
151
152 class downloadJob(Job):
153         def __init__(self, url, file, title):
154                 Job.__init__(self, title)
155                 downloadTask(self, url, file)
156
157 class downloadTask(Task):
158         def __init__(self, job, url, file):
159                 Task.__init__(self, job, ("download task"))
160                 self.end = 100
161                 self.url = url
162                 self.local = file
163
164         def prepare(self):
165                 self.error = None
166
167         def run(self, callback):
168                 self.callback = callback
169                 self.download = downloadWithProgress(self.url,self.local)
170                 self.download.addProgress(self.http_progress)
171                 self.download.start().addCallback(self.http_finished).addErrback(self.http_failed)
172         
173         def http_progress(self, recvbytes, totalbytes):
174                 #print "[http_progress] recvbytes=%d, totalbytes=%d" % (recvbytes, totalbytes)
175                 self.progress = int(self.end*recvbytes/float(totalbytes))
176         
177         def http_finished(self, string=""):
178                 print "[http_finished]" + str(string)
179                 Task.processFinished(self, 0)
180         
181         def http_failed(self, failure_instance=None, error_message=""):
182                 if error_message == "" and failure_instance is not None:
183                         error_message = failure_instance.getErrorMessage()
184                         print "[http_failed] " + error_message
185                         Task.processFinished(self, 1)
186
187
188
189 from MyTubeService import myTubeService
190 from MyTubeSearch import MyTubeSettingsScreen,MyTubeTasksScreen,MyTubeHistoryScreen
191
192
193 class MyTubePlayerMainScreen(Screen, ConfigListScreen):
194         BASE_STD_FEEDURL = "http://gdata.youtube.com/feeds/api/standardfeeds/"
195         #(entry, Title, Description, TubeID, thumbnail, PublishedDate,Views,duration,ratings )  
196         skin = """
197                 <screen name="MyTubePlayerMainScreen" flags="wfNoBorder" position="0,0" size="720,576" title="MyTubePlayerMainScreen..." >
198                         <ePixmap position="0,0" zPosition="-1" size="720,576" pixmap="~/mytubemain_bg.png" alphatest="on" transparent="1" backgroundColor="transparent"/>
199                         <widget name="config" zPosition="2" position="60,60" size="600,50" scrollbarMode="showNever" transparent="1" />
200                         <widget source="feedlist" render="Listbox" position="49,110" size="628,385" zPosition="1" scrollbarMode="showOnDemand" transparent="1" backgroundPixmap="~/list_bg.png" selectionPixmap="~/list_sel.png" >
201                                 <convert type="TemplatedMultiContent">
202                                 {"templates":
203                                         {"default": (77,[
204                                                         MultiContentEntryPixmapAlphaTest(pos = (0, 0), size = (100, 75), png = 4), # index 4 is the thumbnail
205                                                         MultiContentEntryText(pos = (100, 1), size = (500, 22), font=0, flags = RT_HALIGN_LEFT | RT_VALIGN_TOP| RT_WRAP, text = 1), # index 1 is the Title
206                                                         MultiContentEntryText(pos = (100, 24), size = (300, 18), font=1, flags = RT_HALIGN_LEFT | RT_VALIGN_TOP| RT_WRAP, text = 5), # index 5 is the Published Date
207                                                         MultiContentEntryText(pos = (100, 43), size = (300, 18), font=1, flags = RT_HALIGN_LEFT | RT_VALIGN_TOP| RT_WRAP, text = 6), # index 6 is the Views Count
208                                                         MultiContentEntryText(pos = (400, 24), size = (200, 18), font=1, flags = RT_HALIGN_LEFT | RT_VALIGN_TOP| RT_WRAP, text = 7), # index 7 is the duration
209                                                         MultiContentEntryText(pos = (400, 43), size = (200, 18), font=1, flags = RT_HALIGN_LEFT | RT_VALIGN_TOP| RT_WRAP, text = 8), # index 8 is the ratingcount
210                                                 ]),
211                                         "state": (77,[
212                                                         MultiContentEntryText(pos = (10, 1), size = (560, 28), font=2, flags = RT_HALIGN_LEFT | RT_VALIGN_TOP| RT_WRAP, text = 0), # index 0 is the name
213                                                         MultiContentEntryText(pos = (10, 22), size = (560, 46), font=3, flags = RT_HALIGN_LEFT | RT_VALIGN_TOP| RT_WRAP, text = 1), # index 2 is the description
214                                                 ])
215                                         },
216                                         "fonts": [gFont("Regular", 22),gFont("Regular", 18),gFont("Regular", 26),gFont("Regular", 20)],
217                                         "itemHeight": 77
218                                 }
219                                 </convert>
220                         </widget>
221
222                         <ePixmap pixmap="skin_default/buttons/key_info.png" position="50,500" zPosition="4" size="35,25" alphatest="on" transparent="1" />
223                         <ePixmap pixmap="skin_default/buttons/key_menu.png" position="50,520" zPosition="4" size="35,25" alphatest="on" transparent="1" />
224                         <ePixmap position="90,500" size="100,40" zPosition="4" pixmap="~/plugin.png" alphatest="on" transparent="1" />
225                         <ePixmap position="190,500" zPosition="4" size="140,40" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
226                         <ePixmap position="330,500" zPosition="4" size="140,40" pixmap="skin_default/buttons/green.png" transparent="1" alphatest="on" />
227                         <ePixmap position="470,500" zPosition="4" size="140,40" pixmap="skin_default/buttons/yellow.png" transparent="1" alphatest="on" />
228                         <widget name="key_red" position="190,500" zPosition="5" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
229                         <widget name="key_green" position="330,500" zPosition="5" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
230                         <widget name="key_yellow" position="470,500" zPosition="5" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
231                         <widget name="ButtonBlue" pixmap="skin_default/buttons/button_blue.png" position="610,510" zPosition="10" size="15,16" transparent="1" alphatest="on" />
232                         <widget name="VKeyIcon" pixmap="skin_default/vkey_icon.png" position="620,495" zPosition="10" size="60,48" transparent="1" alphatest="on" />
233                         <widget name="thumbnail" position="0,0" size="100,75" alphatest="on"/> # fake entry for dynamic thumbnail resizing, currently there is no other way doing this.
234                         <widget name="HelpWindow" position="160,255" zPosition="1" size="1,1" transparent="1" alphatest="on" />
235                 </screen>"""
236                 
237         def __init__(self, session):
238                 Screen.__init__(self, session)
239                 self.session = session
240                 self.skin_path = plugin_path
241                 self.FeedURL = None
242                 self.ytfeed = None
243                 self.currentFeedName = None
244                 self.videolist = []
245                 self.thumbnails = []
246                 self.video_playlist = []
247                 self.statuslist = []
248                 self.mytubeentries = None
249                 self.index = 0
250                 self.maxentries = 0
251                 self.picloads = {}
252                 self.oldfeedentrycount = 0
253                 self.appendEntries = False
254                 self.lastservice = session.nav.getCurrentlyPlayingServiceReference()
255                 self.propagateUpDownNormally = True
256                 self.FirstRun = True
257                 self.HistoryWindow = None
258                 self.History = None
259                 self.searchtext = _("Welcome to the MyTube Youtube Player.\n\nWhile entering your search term(s) you will get suggestions displayed matching your search term.\n\nTo select a suggestion press DOWN on your remote, select the desired result and press OK on your remote to start the search.\n\nPress exit to get back to the input field.")
260                 self.feedtext = _("Welcome to the MyTube Youtube Player.\n\nUse the Bouqet+ button to navigate to the search field and the Bouqet- to navigate to the video entries.\n\nTo play a movie just press OK on your remote control.\n\nPress info to see the movie description.\n\nPress the Menu button for additional options.\n\nThe Help button shows this help again.")
261                 self.currList = "configlist"
262                 self.oldlist = None
263                 self.CleanupConsole = None
264                 self["feedlist"] = List(self.videolist)
265                 self["thumbnail"] = Pixmap()
266                 self["thumbnail"].hide()
267                 self["HelpWindow"] = Pixmap()
268                 self["HelpWindow"].hide()
269                 self["key_red"] = Button(_("Close"))
270                 self["key_green"] = Button(_("Std. Feeds"))
271                 self["key_yellow"] = Button(_("History"))
272                 self["ButtonBlue"] = Pixmap()
273                 self["VKeyIcon"] = Pixmap()
274                 self["ButtonBlue"].hide()
275                 self["VKeyIcon"].hide()         
276
277                 self["searchactions"] = ActionMap(["ShortcutActions", "WizardActions", "HelpActions", "MediaPlayerActions"],
278                 {
279                         "ok": self.keyOK,
280                         "back": self.leavePlayer,
281                         "red": self.leavePlayer,
282                         "blue": self.openKeyboard,
283                         "yellow": self.handleHistory,
284                         "up": self.keyUp,
285                         "down": self.handleSuggestions,
286                         "left": self.keyLeft,
287                         "right": self.keyRight,
288                         "prevBouquet": self.switchToFeedList,
289                         "nextBouquet": self.switchToConfigList,
290                         "displayHelp": self.handleHelpWindow,
291                         "menu" : self.handleMenu,
292                 }, -2)
293
294                 self["suggestionactions"] = ActionMap(["ShortcutActions", "WizardActions", "MediaPlayerActions", "HelpActions"],
295                 {
296                         "ok": self.keyOK,
297                         "back": self.switchToConfigList,
298                         "red": self.switchToConfigList,
299                         "nextBouquet": self.switchToConfigList,
300                         "prevBouquet": self.switchToFeedList,
301                         "up": self.keyUp,
302                         "down": self.keyDown,
303                         "left": self.keyLeft,
304                         "right": self.keyRight,
305                 }, -2)
306
307
308                 self["videoactions"] = ActionMap(["ShortcutActions", "WizardActions", "MediaPlayerActions", "MovieSelectionActions", "HelpActions"],
309                 {
310                         "ok": self.keyOK,
311                         "back": self.leavePlayer,
312                         "red": self.leavePlayer,
313                         "yellow": self.handleHistory,
314                         "up": self.keyUp,
315                         "down": self.keyDown,   
316                         "nextBouquet": self.switchToConfigList,
317                         "green": self.keyStdFeed,
318                         "showEventInfo": self.showVideoInfo,
319                         "displayHelp": self.handleHelpWindow,
320                         "menu" : self.handleMenu,
321                 }, -2)
322
323                 self["statusactions"] = ActionMap(["ShortcutActions", "WizardActions", "HelpActions", "MediaPlayerActions"],
324                 {
325                         "back": self.leavePlayer,
326                         "red": self.leavePlayer,
327                         "nextBouquet": self.switchToConfigList,
328                         "green": self.keyStdFeed,
329                         "yellow": self.handleHistory,
330                 }, -2)
331
332                 self["historyactions"] = ActionMap(["ShortcutActions", "WizardActions", "MediaPlayerActions", "MovieSelectionActions", "HelpActions"],
333                 {
334                         "ok": self.keyOK,
335                         "back": self.closeHistory,
336                         "red": self.closeHistory,
337                         "yellow": self.handleHistory,
338                         "up": self.keyUp,
339                         "down": self.keyDown,   
340                         "left": self.keyLeft,
341                         "right": self.keyRight,
342                 }, -2)
343
344                 self["videoactions"].setEnabled(False)
345                 self["statusactions"].setEnabled(False)
346                 self["historyactions"].setEnabled(False)
347                 self.timer = eTimer()
348                 self.timer.callback.append(self.picloadTimeout)
349                 self.SearchConfigEntry = None
350                 self.searchContextEntries = []
351                 config.plugins.mytube.search.searchTerm.value = ""
352                 ConfigListScreen.__init__(self, self.searchContextEntries, session)
353                 self.createSetup()              
354                 self.onLayoutFinish.append(self.layoutFinished)
355                 self.onShown.append(self.setWindowTitle)
356                 self.onClose.append(self.__onClose)
357                 self.Timer = eTimer()
358                 self.Timer.callback.append(self.TimerFire)
359                 
360         def __onClose(self):
361                 del self.Timer
362                 del self.timer
363                 self.session.nav.playService(self.lastservice)
364                 
365         def layoutFinished(self):
366                 self.currList = "status"
367                 #self["key_green"].hide()
368                 current = self["config"].getCurrent()
369                 if current[1].help_window.instance is not None:
370                         current[1].help_window.instance.hide()
371                 self.statuslist.append(( _("Fetching feed entries"), _("Trying to download the Youtube feed entries. Please wait..." ) ))
372                 self["feedlist"].style = "state"
373                 self['feedlist'].setList(self.statuslist)
374                 self.Timer.start(200)
375
376         def TimerFire(self):
377                 self.Timer.stop()
378                 if config.plugins.mytube.general.loadFeedOnOpen.value:
379                         self.setState('getFeed')
380                 else:
381                         self.setState('byPass')
382                 
383         def setWindowTitle(self):
384                 self.setTitle(_("MyTubePlayer"))
385
386         def createSetup(self):
387                 self.searchContextEntries = []
388                 self.SearchConfigEntry = getConfigListEntry(_("Search Term(s)"), config.plugins.mytube.search.searchTerm)
389                 self.searchContextEntries.append(self.SearchConfigEntry)
390                 self["config"].list = self.searchContextEntries
391                 self["config"].l.setList(self.searchContextEntries)
392
393         def setState(self,status = None):
394                 if status:
395                         if self.FirstRun == True:
396                                 self.appendEntries = False
397                                 myTubeService.startService()
398                         self.currList = "status"
399                         self.statuslist = []
400                         self["videoactions"].setEnabled(False)
401                         self["searchactions"].setEnabled(False)
402                         #self["key_green"].hide()
403                         self["config_actions"].setEnabled(False)
404                         self["historyactions"].setEnabled(False)
405                         self["statusactions"].setEnabled(True)
406                         self["ButtonBlue"].hide()
407                         self["VKeyIcon"].hide() 
408                         if self.HistoryWindow is not None:
409                                 self.HistoryWindow.deactivate()
410                                 self.HistoryWindow.instance.hide()
411                         if status == 'getFeed':
412                                 self.hideSuggestions()
413                                 self.statuslist.append(( _("Fetching feed entries"), _("Trying to download the Youtube feed entries. Please wait..." ) ))
414                                 self["feedlist"].style = "state"
415                                 self['feedlist'].setList(self.statuslist)
416                         elif status == 'getSearchFeed':
417                                 self.hideSuggestions()
418                                 self.statuslist.append(( _("Fetching search entries"), _("Trying to download the Youtube search results. Please wait..." ) ))
419                                 self["feedlist"].style = "state"
420                                 self['feedlist'].setList(self.statuslist)
421                         elif status == 'Error':
422                                 self.hideSuggestions()
423                                 self.statuslist.append(( _("An error occured."), _("There was an error getting the feed entries. Please try again." ) ))
424                                 self["feedlist"].style = "state"
425                                 self['feedlist'].setList(self.statuslist)
426                         elif status == 'noVideos':
427                                 self["key_green"].show()
428                                 self.hideSuggestions()
429                                 self.statuslist.append(( _("No videos to display"), _("Please select a standard feed or try searching for videos." ) ))
430                                 self["feedlist"].style = "state"
431                                 self['feedlist'].setList(self.statuslist)
432                         elif status == 'byPass':
433                                 self.statuslist.append(( _("Not fetching feed entries"), _("Please enter your search term." ) ))
434                                 self["feedlist"].style = "state"
435                                 self['feedlist'].setList(self.statuslist)
436                                 self.switchToConfigList()
437                         if self.FirstRun == True:
438                                 if config.plugins.mytube.general.loadFeedOnOpen.value:
439                                         if config.plugins.mytube.general.startFeed.value == 'hd':
440                                                 self.FeedURL = "http://gdata.youtube.com/feeds/api/videos/-/HD"
441                                         else:
442                                                 self.FeedURL = self.BASE_STD_FEEDURL + str(config.plugins.mytube.general.startFeed.value)
443                                         self.getFeed(self.FeedURL, str(config.plugins.mytube.general.startFeed.value))
444
445
446         def handleHelpWindow(self):
447                 print "[handleHelpWindow]"
448                 if self.currList == "configlist":
449                         self.hideSuggestions()
450                         self.session.openWithCallback(self.ScreenClosed, MyTubeVideoHelpScreen, self.skin_path, wantedinfo = self.searchtext, wantedtitle = _("MyTubePlayer Help") )
451                 elif self.currList == "feedlist":
452                         self.session.openWithCallback(self.ScreenClosed, MyTubeVideoHelpScreen, self.skin_path, wantedinfo = self.feedtext, wantedtitle = _("MyTubePlayer Help") )
453                         
454         def handleFirstHelpWindow(self):
455                 print "[handleFirstHelpWindow]"
456                 if config.plugins.mytube.general.showHelpOnOpen.value is True:
457                         if self.currList == "configlist":
458                                 self.hideSuggestions()
459                                 self.session.openWithCallback(self.firstRunHelpClosed, MyTubeVideoHelpScreen, self.skin_path,wantedinfo = self.feedtext, wantedtitle = _("MyTubePlayer Help") )
460                 else:
461                         self.FirstRun = False
462                         
463         def firstRunHelpClosed(self):
464                 if self.FirstRun == True:       
465                         self.FirstRun = False
466                         self.switchToConfigList()
467
468         def handleMenu(self):
469                 print "currlist im HandleMenu:",self.currList
470                 if self.currList == "configlist":
471                         menulist = (
472                                         (_("MyTube Settings"), "settings"),
473                                 )
474                         self.hideSuggestions()
475                         self.session.openWithCallback(self.openMenu, ChoiceBox, title=_("Select your choice."), list = menulist)
476
477                 elif self.currList == "feedlist":
478                         menulist = [(_("MyTube Settings"), "settings")]
479                         menulist.extend((
480                                         (_("View related videos"), "related"),
481                                         (_("View response videos"), "response")
482                                 ))
483                         if config.usage.setup_level.index >= 2: # expert+
484                                 menulist.extend((
485                                         (_("Download Video"), "download"),
486                                         (_("View active downloads"), "downview")
487                                 ))
488                                                 
489                         self.hideSuggestions()
490                         self.session.openWithCallback(self.openMenu, ChoiceBox, title=_("Select your choice."), list = menulist)
491
492         def openMenu(self, answer):
493                 answer = answer and answer[1]
494                 print "openMenu - ANSWER",answer
495                 if answer == "settings":
496                         print "settings selected"
497                         self.session.openWithCallback(self.ScreenClosed,MyTubeSettingsScreen, self.skin_path )
498                 elif answer == "related":
499                         current = self["feedlist"].getCurrent()[0]
500                         self.setState('getFeed')
501                         self.getRelatedVideos(current)
502                 elif answer == "response":
503                         current = self["feedlist"].getCurrent()[0]
504                         self.setState('getFeed')
505                         self.getResponseVideos(current)
506                 elif answer == "download":
507                         if self.currList == "feedlist":
508                                 current = self[self.currList].getCurrent()
509                                 if current:
510                                         myentry = current[0]
511                                         if myentry:
512                                                 myurl = myentry.getVideoUrl()
513                                                 filename = str(config.plugins.mytube.general.videodir.value)+ str(myentry.getTitle()) + '.mp4'
514                                                 job_manager.AddJob(downloadJob(myurl,filename, str(myentry.getTitle())[:30]))
515                 elif answer == "downview":
516                         self.tasklist = []
517                         for job in job_manager.getPendingJobs():
518                                 self.tasklist.append((job,job.name,job.getStatustext(),int(100*job.progress/float(job.end)) ,str(100*job.progress/float(job.end)) + "%" ))
519                         self.session.open(MyTubeTasksScreen, self.skin_path , self.tasklist)            
520                 elif answer == None:
521                         print "No menuentry selected, we should just switch back to old state."
522                         self.ScreenClosed()
523         
524         def openKeyboard(self):
525                 self.hideSuggestions()
526                 self.session.openWithCallback(self.SearchEntryCallback, VirtualKeyBoard, title = (_("Enter your search term(s)")), text = config.plugins.mytube.search.searchTerm.value)
527
528         def ScreenClosed(self):
529                 print "ScreenCLosed, restoring old window state"
530                 if self.currList == "historylist":
531                         if self.HistoryWindow.status() is False:
532                                 print "status is FALSE"
533                                 self.HistoryWindow.activate()
534                                 self.HistoryWindow.instance.show()
535                 elif self.currList == "configlist":
536                         self.switchToConfigList()
537                         ConfigListScreen.keyOK(self)
538                 elif self.currList == "feedlist":
539                         self.switchToFeedList()
540
541         def SearchEntryCallback(self, callback = None):
542                 if callback is not None and len(callback):
543                         config.plugins.mytube.search.searchTerm.value = callback
544                         ConfigListScreen.keyOK(self)
545                         self["config"].getCurrent()[1].getSuggestions()
546                 current = self["config"].getCurrent()
547                 if current[1].help_window.instance is not None:
548                         current[1].help_window.instance.show()  
549                 if current[1].suggestionsWindow.instance is not None:
550                         current[1].suggestionsWindow.instance.show()
551                 self.propagateUpDownNormally = True
552
553         def openStandardFeedClosed(self, answer):
554                 answer = answer and answer[1]
555                 print "openStandardFeedClosed - ANSWER",answer
556                 if answer is not None:
557                         if answer == 'hd':
558                                 self.FeedURL = "http://gdata.youtube.com/feeds/api/videos/-/HD"
559                         else:
560                                 self.FeedURL = self.BASE_STD_FEEDURL + str(answer)
561                         self.setState('getFeed')
562                         self.appendEntries = False
563                         self.getFeed(self.FeedURL, str(answer))
564
565         def handleLeave(self, how):
566                 self.is_closing = True
567                 if how == "ask":
568                         if self.currList == "configlist":
569                                 list = (
570                                         (_("Yes"), "quit"),
571                                         (_("No"), "continue"),
572                                         (_("No, but switch to video entries."), "switch2feed")
573                                 )
574                         else:
575                                 list = (
576                                         (_("Yes"), "quit"),
577                                         (_("No"), "continue"),
578                                         (_("No, but switch to video search."), "switch2search")
579                                 )                                       
580                         self.session.openWithCallback(self.leavePlayerConfirmed, ChoiceBox, title=_("Really quit MyTube Player?"), list = list)
581                 else:
582                         self.leavePlayerConfirmed([True, how])
583
584         def leavePlayer(self):
585                 print "self.currList im leavePlayer",self.currList
586                 if self.HistoryWindow is not None:
587                         self.HistoryWindow.deactivate()
588                         self.HistoryWindow.instance.hide()
589                 if self.currList == "configlist":
590                         current = self["config"].getCurrent()
591                         if current[1].suggestionsWindow.activeState is True:
592                                 self.propagateUpDownNormally = True
593                                 current[1].deactivateSuggestionList()
594                                 self["config"].invalidateCurrent()
595                         else:
596                                 self.hideSuggestions()
597                                 self.handleLeave(config.plugins.mytube.general.on_exit.value)
598                 else:
599                         self.hideSuggestions()
600                         self.handleLeave(config.plugins.mytube.general.on_exit.value)
601
602         def leavePlayerConfirmed(self, answer):
603                 answer = answer and answer[1]
604                 print "ANSWER",answer
605                 if answer == "quit":
606                         cmd = "rm -rf /tmp/*.jpg"
607                         self.CleanupConsole = Console()
608                         self.CleanupConsole.ePopen(cmd, self.doQuit)
609                 elif answer == "continue":
610                         if self.currList == "historylist":
611                                 if self.HistoryWindow.status() is False:
612                                         print "status is FALSE"
613                                         self.HistoryWindow.activate()
614                                         self.HistoryWindow.instance.show()
615                         elif self.currList == "configlist":
616                                 self.switchToConfigList()
617                         elif self.currList == "feedlist":
618                                 self.switchToFeedList()                         
619                 elif answer == "switch2feed":
620                         self.switchToFeedList()
621                 elif answer == "switch2search":
622                         self.switchToConfigList()
623                 elif answer == None:
624                         print "No menuentry selected, we should just switch back to old state."
625                         if self.currList == "historylist":
626                                 if self.HistoryWindow.status() is False:
627                                         print "status is FALSE"
628                                         self.HistoryWindow.activate()
629                                         self.HistoryWindow.instance.show()
630                         elif self.currList == "configlist":
631                                 self.switchToConfigList()
632                         elif self.currList == "feedlist":
633                                 self.switchToFeedList()
634
635         def doQuit(self, result, retval,extra_args):
636                 if self["config"].getCurrent()[1].suggestionsWindow is not None:
637                         self.session.deleteDialog(self["config"].getCurrent()[1].suggestionsWindow)
638                 if self.HistoryWindow is not None:
639                         self.session.deleteDialog(self.HistoryWindow)
640                 if config.plugins.mytube.general.showHelpOnOpen.value is True:
641                         config.plugins.mytube.general.showHelpOnOpen.value = False
642                         config.plugins.mytube.general.showHelpOnOpen.save()
643                 print "self.History im doQuit:",self.History
644                 if not config.plugins.mytube.general.clearHistoryOnClose.value:
645                         if self.History and len(self.History):
646                                 config.plugins.mytube.general.history.value = ",".join(self.History)
647                 else:
648                         config.plugins.mytube.general.history.value = ""
649                 config.plugins.mytube.general.history.save()
650                 config.plugins.mytube.general.save()
651                 config.plugins.mytube.save()
652                 if self.CleanupConsole is not None:
653                         if len(self.CleanupConsole.appContainers):
654                                 for name in self.CleanupConsole.appContainers.keys():
655                                         self.CleanupConsole.kill(name)
656                 self.close()
657                         
658         def keyOK(self):
659                 print "self.currList----->",self.currList
660                 if self.currList == "configlist" or self.currList == "suggestionslist":
661                         self["config"].invalidateCurrent()
662                         if config.plugins.mytube.search.searchTerm.value != "":
663                                 self.add2History()
664                                 searchContext = config.plugins.mytube.search.searchTerm.value
665                                 print "Search searchcontext",searchContext
666                                 if isinstance(self["config"].getCurrent()[1], ConfigTextWithGoogleSuggestions) and not self.propagateUpDownNormally:
667                                         self.propagateUpDownNormally = True
668                                         self["config"].getCurrent()[1].deactivateSuggestionList()
669                                 self.setState('getSearchFeed')
670                                 self.runSearch(searchContext)
671                 elif self.currList == "feedlist":
672                         current = self[self.currList].getCurrent()
673                         if current:
674                                 print current
675                                 myentry = current[0]
676                                 if myentry is not None:
677                                         myurl = myentry.getVideoUrl()
678                                         print "Playing URL",myurl
679                                         if myurl is not None:
680                                                 myreference = eServiceReference(4097,0,myurl)
681                                                 myreference.setName(myentry.getTitle())
682                                                 self.session.open(MyTubePlayer, myreference, self.lastservice, infoCallback = self.showVideoInfo, nextCallback = self.getNextEntry, prevCallback = self.getPrevEntry )
683                                         else:
684                                                 self.session.open(MessageBox, _("Sorry, video is not available!"), MessageBox.TYPE_INFO)
685                 elif self.currList == "historylist":
686                         if self.HistoryWindow is not None:
687                                 config.plugins.mytube.search.searchTerm.value = self.HistoryWindow.getSelection()
688                         self["config"].invalidateCurrent()
689                         if config.plugins.mytube.search.searchTerm.value != "":
690                                 searchContext = config.plugins.mytube.search.searchTerm.value
691                                 print "Search searchcontext",searchContext
692                                 self.setState('getSearchFeed')
693                                 self.runSearch(searchContext)
694
695         def keyUp(self):
696                 print "self.currList im KeyUp",self.currList
697                 if self.currList == "suggestionslist":
698                         if config.plugins.mytube.search.searchTerm.value != "":
699                                 if not self.propagateUpDownNormally:
700                                         self["config"].getCurrent()[1].suggestionListUp()
701                                         self["config"].invalidateCurrent()
702                 elif self.currList == "feedlist":
703                         self[self.currList].selectPrevious()
704                 elif self.currList == "historylist":
705                         if self.HistoryWindow is not None and self.HistoryWindow.shown:
706                                 self.HistoryWindow.up()
707
708         def keyDown(self):
709                 print "self.currList im KeyDown",self.currList
710                 if self.currList == "suggestionslist":
711                         if config.plugins.mytube.search.searchTerm.value != "":
712                                 if not self.propagateUpDownNormally:
713                                         self["config"].getCurrent()[1].suggestionListDown()
714                                         self["config"].invalidateCurrent()
715                 elif self.currList == "feedlist":
716                         print self[self.currList].count()
717                         print self[self.currList].index
718                         if self[self.currList].index == self[self.currList].count()-1 and myTubeService.getNextFeedEntriesURL() is not None:
719                                 self.session.openWithCallback(self.getNextEntries, MessageBox, _("Do you want to see more entries?"))
720                         else:
721                                 self[self.currList].selectNext()
722                 elif self.currList == "historylist":
723                         if self.HistoryWindow is not None and self.HistoryWindow.shown:
724                                 self.HistoryWindow.down()
725         def keyRight(self):
726                 print "self.currList im KeyRight",self.currList
727                 if self.propagateUpDownNormally:
728                         ConfigListScreen.keyRight(self)
729                 else:
730                         if self.currList == "suggestionslist":
731                                 if config.plugins.mytube.search.searchTerm.value != "":
732                                         self["config"].getCurrent()[1].suggestionListPageDown()
733                                         self["config"].invalidateCurrent()
734                         elif self.currList == "historylist":
735                                 if self.HistoryWindow is not None and self.HistoryWindow.shown:
736                                         self.HistoryWindow.pageDown()
737
738         def keyLeft(self):
739                 print "self.currList im kEyLeft",self.currList
740                 if self.propagateUpDownNormally:
741                         ConfigListScreen.keyLeft(self)
742                 else:
743                         if self.currList == "suggestionslist":
744                                 if config.plugins.mytube.search.searchTerm.value != "":
745                                         self["config"].getCurrent()[1].suggestionListPageUp()
746                                         self["config"].invalidateCurrent()
747                         elif self.currList == "historylist":
748                                 if self.HistoryWindow is not None and self.HistoryWindow.shown:
749                                         self.HistoryWindow.pageDown()
750         def keyStdFeed(self):
751                 self.hideSuggestions()
752                 menulist = [(_("HD videos"), "hd")]
753                 menulist.extend((
754                         (_("Top rated"), "top_rated"),
755                         (_("Top favorites"), "top_favorites"),
756                         (_("Most viewed"), "most_viewed"),
757                         (_("Most popular"), "most_popular"),
758                         (_("Most recent"), "most_recent"),
759                         (_("Most discussed"), "most_discussed"),
760                         (_("Most linked"), "most_linked"),
761                         (_("Recently featured"), "recently_featured"),
762                         (_("Most responded"), "most_responded")
763                 ))
764                 self.session.openWithCallback(self.openStandardFeedClosed, ChoiceBox, title=_("Select new feed to view."), list = menulist)
765
766         def handleSuggestions(self):
767                 print "handleSuggestions"
768                 print "self.currList",self.currList
769                 if self.currList == "configlist":
770                         self.switchToSuggestionsList()
771                 elif self.currList == "historylist":
772                         if self.HistoryWindow is not None and self.HistoryWindow.shown:
773                                 self.HistoryWindow.down()
774
775         def switchToSuggestionsList(self):
776                 print "switchToSuggestionsList"
777                 self.currList = "suggestionslist"
778                 self["ButtonBlue"].hide()
779                 self["VKeyIcon"].hide() 
780                 self["statusactions"].setEnabled(False)
781                 self["config_actions"].setEnabled(False)        
782                 self["videoactions"].setEnabled(False)
783                 self["searchactions"].setEnabled(False)
784                 self["suggestionactions"].setEnabled(True)
785                 self["historyactions"].setEnabled(False)
786                 self["key_green"].hide()
787                 self.propagateUpDownNormally = False
788                 self["config"].invalidateCurrent()
789                 if self.HistoryWindow is not None and self.HistoryWindow.shown:
790                         self.HistoryWindow.deactivate()
791                         self.HistoryWindow.instance.hide()
792         
793         def switchToConfigList(self):
794                 print "switchToConfigList"
795                 self.currList = "configlist"
796                 self["config_actions"].setEnabled(True) 
797                 self["historyactions"].setEnabled(False)
798                 self["statusactions"].setEnabled(False)
799                 self["videoactions"].setEnabled(False)
800                 self["suggestionactions"].setEnabled(False)
801                 self["searchactions"].setEnabled(True)
802                 self["key_green"].hide()
803                 self["ButtonBlue"].show()
804                 self["VKeyIcon"].show()
805                 self["config"].invalidateCurrent()
806                 helpwindowpos = self["HelpWindow"].getPosition()
807                 current = self["config"].getCurrent()
808                 if current[1].help_window.instance is not None:
809                         current[1].help_window.instance.move(ePoint(helpwindowpos[0],helpwindowpos[1]))
810                         current[1].help_window.instance.show()
811                 if current[1].suggestionsWindow.instance is not None:
812                         current[1].suggestionsWindow.instance.show()
813                         self["config"].getCurrent()[1].getSuggestions()
814                 self.propagateUpDownNormally = True
815                 if self.HistoryWindow is not None and self.HistoryWindow.shown:
816                         self.HistoryWindow.deactivate()
817                         self.HistoryWindow.instance.hide()
818                 if self.FirstRun == True:
819                         self.handleFirstHelpWindow()
820
821         def switchToFeedList(self, append = False):
822                 print "switchToFeedList"
823                 print "switching to feedlist from:",self.currList
824                 print "len(self.videolist):",len(self.videolist)
825                 if self.HistoryWindow is not None and self.HistoryWindow.shown:
826                         self.HistoryWindow.deactivate()
827                         self.HistoryWindow.instance.hide()
828                 self.hideSuggestions()
829                 if len(self.videolist):
830                         self.currList = "feedlist"
831                         self["ButtonBlue"].hide()
832                         self["VKeyIcon"].hide() 
833                         self["videoactions"].setEnabled(True)
834                         self["suggestionactions"].setEnabled(False)
835                         self["searchactions"].setEnabled(False)
836                         self["statusactions"].setEnabled(False)
837                         self["historyactions"].setEnabled(False)
838                         self["key_green"].show()
839                         self["config_actions"].setEnabled(False)
840                         if not append:
841                                 self[self.currList].setIndex(0)
842                 else:
843                         self.setState('noVideos')
844
845
846         def switchToHistory(self):
847                 print "switchToHistory"
848                 self.oldlist = self.currList
849                 self.currList = "historylist"
850                 print "switchToHistory currentlist",self.currList
851                 print "switchToHistory oldlist",self.oldlist
852                 self.hideSuggestions()
853                 self["ButtonBlue"].hide()
854                 self["VKeyIcon"].hide() 
855                 self["key_green"].hide()
856                 self["videoactions"].setEnabled(False)
857                 self["suggestionactions"].setEnabled(False)
858                 self["searchactions"].setEnabled(False)
859                 self["statusactions"].setEnabled(False)
860                 self["config_actions"].setEnabled(False)
861                 self["historyactions"].setEnabled(True)
862                 self.HistoryWindow.activate()
863                 self.HistoryWindow.instance.show()      
864
865         def handleHistory(self):
866                 if self.HistoryWindow is None:
867                         self.HistoryWindow = self.session.instantiateDialog(MyTubeHistoryScreen)
868                 if self.currList in ("configlist","feedlist"):
869                         if self.HistoryWindow.status() is False:
870                                 print "status is FALSE,switchToHistory"
871                                 self.switchToHistory()
872                 elif self.currList == "historylist":
873                         self.closeHistory()
874
875         def closeHistory(self):
876                 print "closeHistory currentlist",self.currList
877                 print "closeHistory oldlist",self.oldlist
878                 if self.currList == "historylist":
879                         if self.HistoryWindow.status() is True:
880                                 print "status is TRUE, closing historyscreen"
881                                 self.HistoryWindow.deactivate()
882                                 self.HistoryWindow.instance.hide()
883                                 if self.oldlist == "configlist":
884                                         self.switchToConfigList()
885                                 elif self.oldlist == "feedlist":
886                                         self.switchToFeedList()
887
888         def add2History(self):
889                 if self.History is None:
890                         self.History = config.plugins.mytube.general.history.value.split(',')
891                 if self.History[0] == '':
892                         del self.History[0]
893                 print "self.History im add",self.History
894                 if config.plugins.mytube.search.searchTerm.value not in self.History:
895                         self.History.append((config.plugins.mytube.search.searchTerm.value))
896                 self.History.reverse()
897                 if len(self.History) == 15:
898                         self.History.pop()
899                 config.plugins.mytube.general.history.value = ",".join(self.History)
900                 config.plugins.mytube.general.history.save()
901                 print "configvalue",config.plugins.mytube.general.history.value
902
903         def hideSuggestions(self):
904                 current = self["config"].getCurrent()
905                 if current[1].help_window.instance is not None:
906                         current[1].help_window.instance.hide()  
907                 if current[1].suggestionsWindow.instance is not None:
908                         current[1].suggestionsWindow.instance.hide()
909                 self.propagateUpDownNormally = True
910
911         def getFeed(self, feedUrl, feedName):
912                 try:
913                         feed = myTubeService.getFeed(feedUrl)
914                 except Exception, e:
915                         feed = None
916                         print "Error querying feed :",feedName
917                         print "E-->",e
918                         self.setState('Error')
919                 if feed is not None:
920                         self.ytfeed = feed
921                 self.loadPreviewpics()
922
923         def getNextEntries(self, result):
924                 if not result:
925                         return
926                 nextUrl = myTubeService.getNextFeedEntriesURL()
927                 if nextUrl is not None:
928                         self.appendEntries = True
929                         self.getFeed(nextUrl, _("More video entries."))
930
931         def getRelatedVideos(self, myentry):
932                 if myentry:
933                         myurl =  myentry.getRelatedVideos()
934                         print "RELATEDURL--->",myurl
935                         if myurl is not None:
936                                 self.getFeed(myurl, _("Related video entries."))
937
938         def getResponseVideos(self, myentry):
939                 if myentry:
940                         myurl =  myentry.getResponseVideos()
941                         print "RESPONSEURL--->",myurl
942                         if myurl is not None:
943                                 self.getFeed(myurl, _("Response video entries."))
944
945         def runSearch(self, searchContext = None):
946                 print "[MyTubePlayer] runSearch"
947                 if searchContext is not None:
948                         print "[MyTubePlayer] searchDialogClosed: ", searchContext
949                         self.searchFeed(searchContext)
950
951         def searchFeed(self, searchContext):
952                 print "[MyTubePlayer] searchFeed"
953                 self.appendEntries = False
954                 try:
955                         feed = myTubeService.search(searchContext, 
956                                         orderby = config.plugins.mytube.search.orderBy.value,
957                                         racy = config.plugins.mytube.search.racy.value,
958                                         lr = config.plugins.mytube.search.lr.value,
959                                         categories = [ config.plugins.mytube.search.categories.value ],
960                                         sortOrder = config.plugins.mytube.search.sortOrder.value)
961                 except Exception, e:
962                         feed = None
963                         print "Error querying search for :",config.plugins.mytube.search.searchTerm.value
964                         print "E-->",e
965                         self.setState('Error')
966                 if feed is not None:
967                         self.ytfeed = feed
968                 if self.FirstRun == True:       
969                         self.FirstRun = False
970                 self.loadPreviewpics()
971
972         def loadPreviewpics(self):
973                 self.thumbnails = []
974                 self.mytubeentries = None
975                 self.index = 0
976                 self.maxentries = 0
977                 self.picloads = {}
978                 self.mytubeentries = myTubeService.getEntries()
979                 self.maxentries = len(self.mytubeentries)-1
980                 if self.mytubeentries and len(self.mytubeentries):
981                         currindex = 0
982                         for entry in self.mytubeentries:
983                                 TubeID = entry.getTubeId()
984                                 thumbnailFile = "/tmp/" + str(TubeID) + ".jpg"
985                                 currPic = [currindex,TubeID,thumbnailFile,None]
986                                 self.thumbnails.append(currPic)
987                                 thumbnailUrl = None
988                                 thumbnailUrl = entry.getThumbnailUrl(0)
989                                 if thumbnailUrl is not None:
990                                         client.downloadPage(thumbnailUrl,thumbnailFile).addCallback(self.fetchFinished,currindex,str(TubeID)).addErrback(self.fetchFailed,currindex,str(TubeID))
991                                 currindex +=1
992                 else:
993                         pass
994
995         def fetchFailed(self, string, index, id):
996                 print "[fetchFailed] for index:" + str(index) + "for YoutubeID:" + id + string.getErrorMessage()
997
998         def fetchFinished(self, string, index, id):
999                 print "[fetchFinished] for index:" + str(index) + " for YoutubeID:" + id
1000                 self.decodePic(index)
1001
1002         def decodePic(self, index):
1003                 sc = AVSwitch().getFramebufferScale()
1004                 self.picloads[index] = ePicLoad()
1005                 self.picloads[index].PictureData.get().append(boundFunction(self.finish_decode, index))
1006                 for entry in self.thumbnails:
1007                         if entry[0] == index:
1008                                 self.index = index
1009                                 thumbnailFile = entry[2]
1010                                 if (os_path.exists(thumbnailFile) == True):
1011                                         #print "[decodePic] DECODING THUMBNAIL for INDEX:"+  str(self.index) + "and file: " + thumbnailFile
1012                                         self.picloads[index].setPara((self["thumbnail"].instance.size().width(), self["thumbnail"].instance.size().height(), sc[0], sc[1], False, 1, "#00000000"))
1013                                         self.picloads[index].startDecode(thumbnailFile)
1014                                 else:
1015                                         print "[decodePic] Thumbnail file NOT FOUND !!!-->:",thumbnailFile
1016
1017         def finish_decode(self, picindex = None, picInfo=None):
1018                 #print "finish_decode - of INDEX", picindex
1019                 ptr = self.picloads[picindex].getData()
1020                 if ptr != None:
1021                         print ptr
1022                         self.thumbnails[picindex][3] = ptr
1023                         if (os_path.exists(self.thumbnails[picindex][2]) == True):
1024                                 #print "removing", self.thumbnails[picindex][2]
1025                                 remove(self.thumbnails[picindex][2])
1026                                 del self.picloads[picindex]
1027                                 if len(self.picloads) == 0:
1028                                         self.timer.startLongTimer(3)
1029
1030         def picloadTimeout(self):
1031                 self.timer.stop()
1032                 if len(self.picloads) == 0:
1033                                 print "all decodes should be now really finished"
1034                                 self.buildEntryList()
1035                 else:
1036                         self.timer.startLongTimer(2)
1037
1038         def buildEntryList(self):
1039                 myindex = 0
1040                 if self.appendEntries == False:
1041                         self.videolist = []
1042                         for entry in self.mytubeentries:
1043                                 self.videolist.append(self.buildEntryComponent(entry, myindex))
1044                                 myindex +=1
1045                         if len(self.videolist):
1046                                 self["feedlist"].style = "default"
1047                                 self["feedlist"].disable_callbacks = True
1048                                 self["feedlist"].list = self.videolist
1049                                 self["feedlist"].disable_callbacks = False
1050                                 self["feedlist"].setIndex(0)
1051                                 self["feedlist"].setList(self.videolist)
1052                                 self["feedlist"].updateList(self.videolist)
1053                                 if self.FirstRun == True:       
1054                                         self.switchToConfigList()
1055                                 else:
1056                                         self.switchToFeedList()
1057                 else:           
1058                         self.oldfeedentrycount = self["feedlist"].count()
1059                         for entry in self.mytubeentries:
1060                                 self.videolist.append(self.buildEntryComponent(entry, myindex))
1061                                 myindex +=1
1062                         if len(self.videolist):
1063                                 self["feedlist"].style = "default"
1064                                 old_index = self["feedlist"].index
1065                                 self["feedlist"].disable_callbacks = True
1066                                 self["feedlist"].list = self.videolist
1067                                 self["feedlist"].disable_callbacks = False
1068                                 self["feedlist"].setList(self.videolist)
1069                                 self["feedlist"].setIndex(old_index)
1070                                 self["feedlist"].updateList(self.videolist)
1071                                 self["feedlist"].selectNext()
1072                                 self.switchToFeedList(True)
1073
1074         
1075         def buildEntryComponent(self, entry, index):
1076                 Title = entry.getTitle()
1077                 print "Titel-->",Title
1078                 Description = entry.getDescription()
1079                 TubeID = entry.getTubeId()
1080                 PublishedDate = entry.getPublishedDate()
1081                 if PublishedDate is not "unknown":
1082                         published = PublishedDate.split("T")[0]
1083                 else:
1084                         published = "unknown"
1085                 Views = entry.getViews()
1086                 if Views is not "not available":
1087                         views = Views
1088                 else:
1089                         views = "not available"
1090                 Duration = entry.getDuration()
1091                 if Duration is not 0:
1092                         durationInSecs = int(Duration)
1093                         mins = int(durationInSecs / 60)
1094                         secs = durationInSecs - mins * 60
1095                         duration = "%d:%02d" % (mins, secs)
1096                 else:
1097                         duration = "not available"
1098                 Ratings = entry.getNumRaters()
1099                 if Ratings is not "":
1100                         ratings = Ratings
1101                 else:
1102                         ratings = ""
1103                 thumbnail = self.thumbnails[index][3]
1104                 return((entry, Title, Description, TubeID, thumbnail, _("Added: ") + str(published), _("Views: ") + str(views), _("Duration: ") + str(duration), _("Ratings: ") + str(ratings) ))       
1105
1106         def getNextEntry(self):
1107                 i = self["feedlist"].getIndex() + 1
1108                 if i < len(self.videolist):
1109                         self["feedlist"].selectNext()
1110                         current = self["feedlist"].getCurrent()
1111                         if current:
1112                                 myentry = current[0]
1113                                 if myentry:
1114                                         myurl = myentry.getVideoUrl()
1115                                         if myurl is not None:
1116                                                 print "Got a URL to stream"
1117                                                 myreference = eServiceReference(4097,0,myurl)
1118                                                 myreference.setName(myentry.getTitle())
1119                                                 return myreference,False
1120                                         else:
1121                                                 print "NoURL im getNextEntry"
1122                                                 return None,True
1123                                                 
1124                 print "no more entries to play"
1125                 return None,False
1126
1127         def getPrevEntry(self):
1128                 i = self["feedlist"].getIndex() - 1
1129                 if i >= 0:
1130                         self["feedlist"].selectPrevious()
1131                         current = self["feedlist"].getCurrent()
1132                         if current:
1133                                 myentry = current[0]
1134                                 if myentry:
1135                                         myurl = myentry.getVideoUrl()
1136                                         if myurl is not None:
1137                                                 print "Got a URL to stream"
1138                                                 myreference = eServiceReference(4097,0,myurl)
1139                                                 myreference.setName(myentry.getTitle())
1140                                                 return myreference,False
1141                                         else:
1142                                                 return None,True
1143                 return None,False
1144
1145         def showVideoInfo(self):
1146                 if self.currList == "feedlist":
1147                         cmd = "rm -rf /tmp/*.jpg"
1148                         if self.CleanupConsole is None:
1149                                 self.CleanupConsole = Console()
1150                         self.CleanupConsole.ePopen(cmd, self.openInfoScreen)
1151         
1152         def openInfoScreen(self, result, retval,extra_args):
1153                 if self.currList == "feedlist":
1154                         current = self[self.currList].getCurrent()
1155                         if current:
1156                                 myentry = current[0]
1157                                 if myentry:
1158                                         print "Title im showVideoInfo",myentry.getTitle()
1159                                         videoinfos = myentry.PrintEntryDetails()
1160                                         self.session.open(MyTubeVideoInfoScreen, self.skin_path, videoinfo = videoinfos )
1161                 
1162
1163 class MyTubeVideoInfoScreen(Screen):
1164         skin = """
1165                 <screen name="MyTubeVideoInfoScreen" flags="wfNoBorder" position="0,0" size="720,576" title="MyTubePlayerMainScreen..." >
1166                         <ePixmap position="0,0" zPosition="-1" size="720,576" pixmap="~/mytubemain_bg.png" alphatest="on" transparent="1" backgroundColor="transparent"/>
1167                         <widget name="title" position="60,50" size="600,50" zPosition="5" valign="center" halign="left" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
1168                         <widget name="starsbg" pixmap="~/starsbar_empty.png" position="560,220" zPosition="5" size="100,20" transparent="1" alphatest="on" />
1169                         <widget name="stars" pixmap="~/starsbar_filled.png" position="560,220" zPosition="6" size="100,20"  transparent="1" />
1170                         <widget source="infolist" render="Listbox" position="50,110" size="620,110" zPosition="6" scrollbarMode="showNever" selectionDisabled="1" transparent="1">
1171                                 <convert type="TemplatedMultiContent">
1172                                 {"templates":
1173                                         {"default": (110,[
1174                                                         MultiContentEntryPixmapAlphaTest(pos = (0, 4), size = (130, 98), png = 0), # index 0 is the thumbnail
1175                                                         MultiContentEntryPixmapAlphaTest(pos = (130, 4), size = (130, 98), png = 1), # index 0 is the thumbnail
1176                                                         MultiContentEntryPixmapAlphaTest(pos = (260, 4), size = (130, 98), png = 2), # index 0 is the thumbnail
1177                                                         MultiContentEntryPixmapAlphaTest(pos = (390, 4), size = (130, 98), png = 3), # index 0 is the thumbnail
1178                                                 ]),
1179                                         "state": (110,[
1180                                                         MultiContentEntryText(pos = (10, 40), size = (550, 38), font=2, flags = RT_HALIGN_LEFT | RT_VALIGN_TOP| RT_WRAP, text = 0), # index 0 is the name
1181                                                 ])
1182                                         },
1183                                         "fonts": [gFont("Regular", 20),gFont("Regular", 14),gFont("Regular", 28)],
1184                                         "itemHeight": 110
1185                                 }
1186                                 </convert>
1187                         </widget>
1188                         <widget name="author" position="60,220" size="300,20" zPosition="10" font="Regular;21" transparent="1" halign="left" valign="top" />
1189                         <widget name="duration" position="370,220" size="200,20" zPosition="10" font="Regular;21" transparent="1" halign="left" valign="top" />
1190                         <widget name="published" position="60,245" size="300,20" zPosition="10" font="Regular;21" transparent="1" halign="left" valign="top" />
1191                         <widget name="views" position="370,245" size="200,20" zPosition="10" font="Regular;21" transparent="1" halign="left" valign="top" />
1192                         <widget name="tags" position="60,270" size="600,20" zPosition="10" font="Regular;21" transparent="1" halign="left" valign="top" />
1193                         <widget name="detailtext" position="60,300" size="610,200" zPosition="10" font="Regular;21" transparent="1" halign="left" valign="top"/>
1194                         <ePixmap position="100,500" size="100,40" zPosition="0" pixmap="~/plugin.png" alphatest="on" transparent="1" />
1195                         <ePixmap position="220,500" zPosition="4" size="140,40" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
1196                         <widget name="key_red" position="220,500" zPosition="5" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
1197                         <widget name="thumbnail" position="0,0" size="130,98" alphatest="on"/> # fake entry for dynamic thumbnail resizing, currently there is no other way doing this.
1198                 </screen>"""
1199                 
1200         def __init__(self, session, plugin_path, videoinfo = None):
1201                 Screen.__init__(self, session)
1202                 self.session = session
1203                 self.skin_path = plugin_path
1204                 self.videoinfo = videoinfo
1205                 self.infolist = []
1206                 self.thumbnails = []
1207                 self.picloads = {}
1208                 self["title"] = Label()
1209                 self["key_red"] = Button(_("Close"))
1210                 self["thumbnail"] = Pixmap()
1211                 self["thumbnail"].hide()
1212                 self["detailtext"] = ScrollLabel()
1213                 self["starsbg"] = Pixmap()
1214                 self["stars"] = ProgressBar()
1215                 self["duration"] = Label()
1216                 self["author"] = Label()
1217                 self["published"] = Label()
1218                 self["views"] = Label()
1219                 self["tags"] = Label()
1220                 self["shortcuts"] = ActionMap(["ShortcutActions", "WizardActions", "MovieSelectionActions"],
1221                 {
1222                         "back": self.close,
1223                         "red": self.close,
1224                         "up": self.pageUp,
1225                         "down": self.pageDown,
1226                         "left": self.pageUp,
1227                         "right": self.pageDown,
1228                 }, -2)
1229                 
1230                 self["infolist"] = List(self.infolist)
1231                 self.timer = eTimer()
1232                 self.timer.callback.append(self.picloadTimeout)
1233                 self.onLayoutFinish.append(self.layoutFinished)
1234                 self.onShown.append(self.setWindowTitle)
1235
1236         def layoutFinished(self):
1237                 self.statuslist = []
1238                 self.statuslist.append(( _("Downloading screenshots. Please wait..." ),_("Downloading screenshots. Please wait..." ) ))
1239                 self["infolist"].style = "state"
1240                 self['infolist'].setList(self.statuslist)
1241                 self.loadPreviewpics()          
1242                 if self.videoinfo["Title"] is not None:
1243                         self["title"].setText(self.videoinfo["Title"])
1244                 Description = None
1245                 if self.videoinfo["Description"] is not None:
1246                         Description = self.videoinfo["Description"]
1247                 else:
1248                         Description = None
1249                 if Description is not None:
1250                         self["detailtext"].setText(Description.strip())
1251
1252                 if self.videoinfo["RatingAverage"] is not 0:
1253                         ratingStars = int(round(20 * float(self.videoinfo["RatingAverage"]), 0))
1254                         self["stars"].setValue(ratingStars)
1255                 else:
1256                         self["stars"].hide()
1257                         self["starsbg"].hide()
1258                 
1259                 if self.videoinfo["Duration"] is not 0:
1260                         durationInSecs = int(self.videoinfo["Duration"])
1261                         mins = int(durationInSecs / 60)
1262                         secs = durationInSecs - mins * 60
1263                         duration = "%d:%02d" % (mins, secs)
1264                         self["duration"].setText(_("Duration: ") + str(duration))
1265                 
1266                 if self.videoinfo["Author"] is not None or '':
1267                         self["author"].setText(_("Author: ") + self.videoinfo["Author"])
1268
1269                 if self.videoinfo["Published"] is not "unknown":
1270                         self["published"].setText(_("Added: ") + self.videoinfo["Published"].split("T")[0])
1271                         
1272                 if self.videoinfo["Views"] is not "not available":
1273                         self["views"].setText(_("Views: ") + str(self.videoinfo["Views"]))
1274
1275                 if self.videoinfo["Tags"] is not "not available":
1276                         self["tags"].setText(_("Tags: ") + str(self.videoinfo["Tags"]))
1277
1278         def setWindowTitle(self):
1279                 self.setTitle(_("MyTubeVideoInfoScreen"))
1280
1281         def pageUp(self):
1282                 self["detailtext"].pageUp()
1283
1284         def pageDown(self):
1285                 self["detailtext"].pageDown()
1286
1287         def loadPreviewpics(self):
1288                 self.thumbnails = []
1289                 self.mythumbubeentries = None
1290                 self.index = 0
1291                 self.maxentries = 0
1292                 self.picloads = {}
1293                 self.mythumbubeentries = self.videoinfo["Thumbnails"]
1294                 self.maxentries = len(self.mythumbubeentries)-1
1295                 if self.mythumbubeentries and len(self.mythumbubeentries):
1296                         currindex = 0
1297                         for entry in self.mythumbubeentries:
1298                                 TubeID = self.videoinfo["TubeID"]
1299                                 ThumbID = TubeID + str(currindex)
1300                                 thumbnailFile = "/tmp/" + ThumbID + ".jpg"
1301                                 currPic = [currindex,ThumbID,thumbnailFile,None]
1302                                 self.thumbnails.append(currPic)
1303                                 thumbnailUrl = None
1304                                 thumbnailUrl = entry
1305                                 if thumbnailUrl is not None:
1306                                         client.downloadPage(thumbnailUrl,thumbnailFile).addCallback(self.fetchFinished,currindex,ThumbID).addErrback(self.fetchFailed,currindex,ThumbID)
1307                                 currindex +=1
1308                 else:
1309                         pass
1310
1311         def fetchFailed(self, string, index, id):
1312                 print "[fetchFailed] for index:" + str(index) + "for ThumbID:" + id + string.getErrorMessage()
1313
1314         def fetchFinished(self, string, index, id):
1315                 print "[fetchFinished] for index:" + str(index) + " for ThumbID:" + id
1316                 self.decodePic(index)
1317
1318         def decodePic(self, index):
1319                 sc = AVSwitch().getFramebufferScale()
1320                 self.picloads[index] = ePicLoad()
1321                 self.picloads[index].PictureData.get().append(boundFunction(self.finish_decode, index))
1322                 for entry in self.thumbnails:
1323                         if entry[0] == index:
1324                                 self.index = index
1325                                 thumbnailFile = entry[2]
1326                                 if (os_path.exists(thumbnailFile) == True):
1327                                         print "[decodePic] DECODING THUMBNAIL for INDEX:"+  str(self.index) + "and file: " + thumbnailFile
1328                                         self.picloads[index].setPara((self["thumbnail"].instance.size().width(), self["thumbnail"].instance.size().height(), sc[0], sc[1], False, 1, "#00000000"))
1329                                         self.picloads[index].startDecode(thumbnailFile)
1330                                 else:
1331                                         print "[decodePic] Thumbnail file NOT FOUND !!!-->:",thumbnailFile
1332
1333         def finish_decode(self, picindex = None, picInfo=None):
1334                 print "finish_decode - of INDEX", picindex
1335                 ptr = self.picloads[picindex].getData()
1336                 if ptr != None:
1337                         print ptr
1338                         self.thumbnails[picindex][3] = ptr
1339                         if (os_path.exists(self.thumbnails[picindex][2]) == True):
1340                                 print "removing", self.thumbnails[picindex][2]
1341                                 remove(self.thumbnails[picindex][2])
1342                                 del self.picloads[picindex]
1343                                 if len(self.picloads) == 0:
1344                                         self.timer.startLongTimer(3)
1345
1346         def picloadTimeout(self):
1347                 self.timer.stop()
1348                 if len(self.picloads) == 0:
1349                                 print "all decodes should be now really finished"
1350                                 self.buildInfoList()
1351                 else:
1352                         self.timer.startLongTimer(2)
1353
1354         def buildInfoList(self):
1355                 print "blasel"
1356                 self.infolist = []
1357                 Thumbail0 = None
1358                 Thumbail1 = None
1359                 Thumbail2 = None
1360                 Thumbail3 = None
1361                 if self.thumbnails[0][3] is not None:
1362                         Thumbail0 = self.thumbnails[0][3]
1363                 if self.thumbnails[1][3] is not None:
1364                         Thumbail1 = self.thumbnails[1][3]
1365                 if self.thumbnails[2][3] is not None:
1366                         Thumbail2 = self.thumbnails[2][3]
1367                 if self.thumbnails[3][3] is not None:
1368                         Thumbail3 = self.thumbnails[3][3]
1369                 self.infolist.append(( Thumbail0, Thumbail1, Thumbail2, Thumbail3))
1370                 if len(self.infolist):
1371                         self["infolist"].style = "default"
1372                         self["infolist"].disable_callbacks = True
1373                         self["infolist"].list = self.infolist
1374                         self["infolist"].disable_callbacks = False
1375                         self["infolist"].setIndex(0)
1376                         self["infolist"].setList(self.infolist)
1377                         self["infolist"].updateList(self.infolist)
1378
1379
1380 class MyTubeVideoHelpScreen(Screen):
1381         skin = """
1382                 <screen name="MyTubeVideoHelpScreen" flags="wfNoBorder" position="0,0" size="720,576" title="MyTubePlayerMainScreen..." >
1383                         <ePixmap position="0,0" zPosition="-1" size="720,576" pixmap="~/mytubemain_bg.png" alphatest="on" transparent="1" backgroundColor="transparent"/>
1384                         <widget name="title" position="60,50" size="600,50" zPosition="5" valign="center" halign="left" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
1385                         <widget name="detailtext" position="60,120" size="610,370" zPosition="10" font="Regular;21" transparent="1" halign="left" valign="top"/>
1386                         <ePixmap position="100,500" size="100,40" zPosition="0" pixmap="~/plugin.png" alphatest="on" transparent="1" />
1387                         <ePixmap position="220,500" zPosition="4" size="140,40" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
1388                         <widget name="key_red" position="220,500" zPosition="5" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
1389                 </screen>"""
1390                 
1391         def __init__(self, session, plugin_path, wantedinfo = None, wantedtitle = None):
1392                 Screen.__init__(self, session)
1393                 self.session = session
1394                 self.skin_path = plugin_path
1395                 self.wantedinfo = wantedinfo
1396                 self.wantedtitle = wantedtitle
1397                 self["title"] = Label()
1398                 self["key_red"] = Button(_("Close"))
1399                 self["detailtext"] = ScrollLabel()
1400                 
1401                 self["shortcuts"] = ActionMap(["ShortcutActions", "WizardActions"],
1402                 {
1403                         "back": self.close,
1404                         "red": self.close,
1405                         "up": self.pageUp,
1406                         "down": self.pageDown,
1407                         "left": self.pageUp,
1408                         "right": self.pageDown,
1409                 }, -2)
1410                 
1411                 self.onLayoutFinish.append(self.layoutFinished)
1412                 self.onShown.append(self.setWindowTitle)
1413
1414         def layoutFinished(self):
1415                 if self.wantedtitle is None:
1416                         self["title"].setText(_("Help"))
1417                 else:
1418                         self["title"].setText(self.wantedtitle)
1419                 if self.wantedinfo is None:
1420                         self["detailtext"].setText(_("This is the help screen. Feed me with something to display."))
1421                 else:
1422                         self["detailtext"].setText(self.wantedinfo)
1423         
1424         def setWindowTitle(self):
1425                 self.setTitle(_("MyTubeVideohelpScreen"))
1426
1427         def pageUp(self):
1428                 self["detailtext"].pageUp()
1429
1430         def pageDown(self):
1431                 self["detailtext"].pageDown()
1432
1433
1434 class MyTubePlayer(Screen, InfoBarNotifications):
1435         STATE_IDLE = 0
1436         STATE_PLAYING = 1
1437         STATE_PAUSED = 2
1438         ENABLE_RESUME_SUPPORT = True
1439         ALLOW_SUSPEND = True
1440
1441         skin = """<screen name="MyTubePlayer" flags="wfNoBorder" position="0,380" size="720,160" title="InfoBar" backgroundColor="transparent">
1442                 <ePixmap position="0,0" pixmap="skin_default/info-bg_mp.png" zPosition="-1" size="720,160" />
1443                 <ePixmap position="29,40" pixmap="skin_default/screws_mp.png" size="665,104" alphatest="on" />
1444                 <ePixmap position="48,70" pixmap="skin_default/icons/mp_buttons.png" size="108,13" alphatest="on" />
1445                 <ePixmap pixmap="skin_default/icons/icon_event.png" position="207,78" size="15,10" alphatest="on" />
1446                 <widget source="session.CurrentService" render="Label" position="230,73" size="360,40" font="Regular;20" backgroundColor="#263c59" shadowColor="#1d354c" shadowOffset="-1,-1" transparent="1">
1447                         <convert type="ServiceName">Name</convert>
1448                 </widget>
1449                 <widget source="session.CurrentService" render="Label" position="580,73" size="90,24" font="Regular;20" halign="right" backgroundColor="#4e5a74" transparent="1">
1450                         <convert type="ServicePosition">Length</convert>
1451                 </widget>
1452                 <widget source="session.CurrentService" render="Label" position="205,129" size="100,20" font="Regular;18" halign="center" valign="center" backgroundColor="#06224f" shadowColor="#1d354c" shadowOffset="-1,-1" transparent="1">
1453                         <convert type="ServicePosition">Position</convert>
1454                 </widget>
1455                 <widget source="session.CurrentService" render="PositionGauge" position="300,133" size="270,10" zPosition="2" pointer="skin_default/position_pointer.png:540,0" transparent="1" foregroundColor="#20224f">
1456                         <convert type="ServicePosition">Gauge</convert>
1457                 </widget>
1458                 <widget source="session.CurrentService" render="Label" position="576,129" size="100,20" font="Regular;18" halign="center" valign="center" backgroundColor="#06224f" shadowColor="#1d354c" shadowOffset="-1,-1" transparent="1">
1459                         <convert type="ServicePosition">Remaining</convert>
1460                 </widget>
1461                 </screen>"""
1462
1463         def __init__(self, session, service, lastservice, infoCallback = None, nextCallback = None, prevCallback = None):
1464                 Screen.__init__(self, session)
1465                 InfoBarNotifications.__init__(self)
1466                 self.session = session
1467                 self.service = service
1468                 self.infoCallback = infoCallback
1469                 self.nextCallback = nextCallback
1470                 self.prevCallback = prevCallback
1471                 self.screen_timeout = 5000
1472                 self.nextservice = None
1473
1474                 print "evEOF=%d" % iPlayableService.evEOF
1475                 self.__event_tracker = ServiceEventTracker(screen = self, eventmap =
1476                         {
1477                                 iPlayableService.evSeekableStatusChanged: self.__seekableStatusChanged,
1478                                 iPlayableService.evStart: self.__serviceStarted,
1479                                 iPlayableService.evEOF: self.__evEOF,
1480                         })
1481                 
1482                 self["actions"] = ActionMap(["OkCancelActions", "InfobarSeekActions", "MediaPlayerActions", "MovieSelectionActions"],
1483                 {
1484                                 "ok": self.ok,
1485                                 "cancel": self.leavePlayer,
1486                                 "stop": self.leavePlayer,
1487                                 "playpauseService": self.playpauseService,
1488                                 "seekFwd": self.playNextFile,
1489                                 "seekBack": self.playPrevFile,
1490                                 "showEventInfo": self.showVideoInfo,
1491                         }, -2)
1492
1493
1494                 self.lastservice = lastservice
1495
1496                 self.hidetimer = eTimer()
1497                 self.hidetimer.timeout.get().append(self.ok)
1498                 self.returning = False
1499
1500                 self.state = self.STATE_PLAYING
1501                 self.lastseekstate = self.STATE_PLAYING
1502
1503                 self.onPlayStateChanged = [ ]
1504                 self.__seekableStatusChanged()
1505         
1506                 self.play()
1507                 self.onClose.append(self.__onClose)
1508                 
1509         def __onClose(self):
1510                 self.session.nav.stopService()
1511
1512         def __evEOF(self):
1513                 print "evEOF=%d" % iPlayableService.evEOF
1514                 print "Event EOF"
1515                 self.handleLeave(config.plugins.mytube.general.on_movie_stop.value)
1516
1517         def __setHideTimer(self):
1518                 self.hidetimer.start(self.screen_timeout)
1519
1520         def showInfobar(self):
1521                 self.show()
1522                 if self.state == self.STATE_PLAYING:
1523                         self.__setHideTimer()
1524                 else:
1525                         pass
1526
1527         def hideInfobar(self):
1528                 self.hide()
1529                 self.hidetimer.stop()
1530
1531         def ok(self):
1532                 if self.shown:
1533                         self.hideInfobar()
1534                 else:
1535                         self.showInfobar()
1536
1537         def showVideoInfo(self):
1538                 if self.shown:
1539                         self.hideInfobar()
1540                 if self.infoCallback is not None:       
1541                         self.infoCallback()
1542
1543
1544         def playNextFile(self):
1545                 print "playNextFile"
1546                 nextservice,error = self.nextCallback()
1547                 print "nextservice--->",nextservice
1548                 if nextservice is None:
1549                         self.handleLeave(config.plugins.mytube.general.on_movie_stop.value, error)
1550                 else:
1551                         self.playService(nextservice)
1552                         self.showInfobar()
1553
1554         def playPrevFile(self):
1555                 print "playPrevFile"
1556                 prevservice,error = self.prevCallback()
1557                 if prevservice is None:
1558                         self.handleLeave(config.plugins.mytube.general.on_movie_stop.value, error)
1559                 else:
1560                         self.playService(prevservice)
1561                         self.showInfobar()
1562
1563         def playagain(self):
1564                 print "playagain"
1565                 if self.state != self.STATE_IDLE:
1566                         self.stopCurrent()
1567                 self.play()
1568         
1569         def playService(self, newservice):
1570                 if self.state != self.STATE_IDLE:
1571                         self.stopCurrent()
1572                 self.service = newservice
1573                 self.play()
1574
1575         def play(self):
1576                 if self.state == self.STATE_PAUSED:
1577                         if self.shown:
1578                                 self.__setHideTimer()   
1579                 self.state = self.STATE_PLAYING
1580                 print "self.state--->",self.state
1581                 self.session.nav.playService(self.service)
1582                 if self.shown:
1583                         self.__setHideTimer()
1584
1585         def stopCurrent(self):
1586                 print "stopCurrent"
1587                 self.session.nav.stopService()
1588                 #if self.state == self.STATE_IDLE:
1589                 #       return
1590                 self.state = self.STATE_IDLE
1591                 print "self.state--->",self.state
1592                 
1593
1594         def playpauseService(self):
1595                 print "playpauseService"
1596                 #print "self.state--->",self.state
1597                 if self.state == self.STATE_PLAYING:
1598                         self.pauseService()
1599                 elif self.state == self.STATE_PAUSED:
1600                         self.unPauseService()
1601
1602         def pauseService(self):
1603                 print "pauseService"
1604                 if self.state == self.STATE_PLAYING:
1605                         #print "self.state--->",self.state
1606                         print "calling setseekstate pause"
1607                         self.setSeekState(self.STATE_PAUSED)
1608                 
1609         def unPauseService(self):
1610                 print "unPauseService"
1611                 if self.state == self.STATE_PAUSED:
1612                         #print "self.state--->",self.state
1613                         print "calling setseekstate playing"
1614                         self.setSeekState(self.STATE_PLAYING)
1615
1616
1617         def getSeek(self):
1618                 service = self.session.nav.getCurrentService()
1619                 if service is None:
1620                         return None
1621
1622                 seek = service.seek()
1623
1624                 if seek is None or not seek.isCurrentlySeekable():
1625                         return None
1626
1627                 return seek
1628
1629         def isSeekable(self):
1630                 if self.getSeek() is None:
1631                         return False
1632                 return True
1633
1634         def __seekableStatusChanged(self):
1635                 print "seekable status changed!"
1636                 if not self.isSeekable():
1637                         #self["SeekActions"].setEnabled(False)
1638                         print "not seekable, return to play"
1639                         self.setSeekState(self.STATE_PLAYING)
1640                 else:
1641 #                       self["SeekActions"].setEnabled(True)
1642                         print "seekable"
1643
1644         def __serviceStarted(self):
1645                 self.state = self.STATE_PLAYING
1646                 self.__seekableStatusChanged()
1647
1648         def setSeekState(self, wantstate):
1649                 print "setSeekState"
1650                 #print "current state--->",self.state
1651                 #print " wanted state--->",wantstate
1652                 if wantstate == self.STATE_PAUSED:
1653                         print "trying to switch to Pause- state:",self.STATE_PAUSED
1654                 elif wantstate == self.STATE_PLAYING:
1655                         print "trying to switch to playing- state:",self.STATE_PLAYING
1656                 service = self.session.nav.getCurrentService()
1657                 if service is None:
1658                         print "No Service found"
1659                         return False
1660                 pauseable = service.pause()
1661                 if pauseable is None:
1662                         print "not pauseable."
1663                         self.state = self.STATE_PLAYING
1664
1665                 if pauseable is not None:
1666                         print "service is pausable"
1667                         if wantstate == self.STATE_PAUSED:
1668                                 print "WANT TO PAUSE"
1669                                 print "current state --->",self.state
1670                                 print "wanted state  --->",wantstate
1671                                 pauseable.pause()
1672                                 self.state = self.STATE_PAUSED
1673                                 if not self.shown:
1674                                         self.hidetimer.stop()
1675                                         self.show()
1676                         elif wantstate == self.STATE_PLAYING:
1677                                 print "WANT TO PLAY"
1678                                 print "current state --->",self.state
1679                                 print "wanted state  --->",wantstate
1680                                 pauseable.unpause()
1681                                 self.state = self.STATE_PLAYING
1682                                 if self.shown:
1683                                         self.__setHideTimer()
1684
1685                 for c in self.onPlayStateChanged:
1686                         c(self.state)
1687                 
1688                 return True
1689
1690         def handleLeave(self, how, error = False):
1691                 self.is_closing = True
1692                 if how == "ask":
1693                         list = (
1694                                 (_("Yes"), "quit"),
1695                                 (_("No, but play video again"), "playagain"),
1696                                 (_("Yes, but play next video"), "playnext"),
1697                                 (_("Yes, but play previous video"), "playprev"),
1698                         )
1699                         if error is False:
1700                                 self.session.openWithCallback(self.leavePlayerConfirmed, ChoiceBox, title=_("Stop playing this movie?"), list = list)
1701                         else:
1702                                 self.session.openWithCallback(self.leavePlayerConfirmed, ChoiceBox, title=_("No playable video found! Stop playing this movie?"), list = list)
1703                 else:
1704                         self.leavePlayerConfirmed([True, how])
1705
1706         def leavePlayer(self):
1707                 self.handleLeave(config.plugins.mytube.general.on_movie_stop.value)
1708
1709         def leavePlayerConfirmed(self, answer):
1710                 answer = answer and answer[1]
1711                 print "ANSWER im player leave",answer
1712                 if answer == "quit":
1713                         self.close()
1714                 elif answer == "playnext":
1715                         self.playNextFile()
1716                 elif answer == "playprev":
1717                         self.playPrevFile()
1718                 elif answer == "playagain":
1719                         self.playagain()
1720                         
1721         def doEofInternal(self, playing):
1722                 if not self.execing:
1723                         return
1724                 if not playing :
1725                         return
1726                 self.handleLeave(config.usage.on_movie_eof.value)
1727
1728
1729 def MyTubeMain(session, **kwargs):
1730         Console().ePopen(("rm -rf /tmp/*.jpg"))
1731         session.open(MyTubePlayerMainScreen)
1732
1733
1734 def Plugins(path, **kwargs):
1735         global plugin_path
1736         plugin_path = path
1737         return PluginDescriptor(
1738                 name=_("My TubePlayer"),
1739                 description=_("Play YouTube movies"),
1740                 where = [ PluginDescriptor.WHERE_EXTENSIONSMENU, PluginDescriptor.WHERE_PLUGINMENU ],
1741                 icon = "plugin.png", fnc = MyTubeMain)