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