modified: Makefile.am
[enigma2-plugins.git] / SubsDownloader2 / src / plugin.py
1 import shutil
2 import os
3 try:
4         is_libmediainfo = True
5         from Plugins.Extensions.SubsDownloader2.SourceCode.GetFPS_MI import GetFPS
6 except:
7         is_libmediainfo = False
8         from Plugins.Extensions.SubsDownloader2.SourceCode.GetFPS import GetFPS
9 from Plugins.Extensions.SubsDownloader2.SourceCode import chardet
10
11 from Plugins.Extensions.SubsDownloader2.SourceCode.anysub2srt import SubConv
12 # jak zmienie sciezke SubsDownloader2 (nazwe katalogu to trzeba ja tez zmienic w pliku OpenSubtitles.py
13 #from Plugins.Extensions.SubsDownloader2.SourceCode.periscope.services.OpenSubtitle.services import OpenSubtitle
14 from Plugins.Extensions.SubsDownloader2.SourceCode.xbmc_subtitles.XBMC_search import list_XBMC_Periscope_plugins
15 from Plugins.Extensions.SubsDownloader2.SourceCode.periscope import SubtitleDatabase
16 from Plugins.Extensions.SubsDownloader2.SourceCode.NapiProjekt import NapiProjekt #*
17 from Plugins.Extensions.SubsDownloader2.SourceCode.Napisy24_pl import Napisy24_pl
18 from Plugins.Extensions.SubsDownloader2.SourceCode.chardet_OutpuyTranslation import chardetOutputTranslation
19 from Plugins.Extensions.SubsDownloader2.SourceCode.myFileList import EXTENSIONS, FileList #*
20 from Plugins.Extensions.SubsDownloader2.pluginOnlineContent import IsNewVersionCheck, zlib_link, libmediainfo_link, PluginIpkUpdate, InstallDownloadableContent, flagcounetr
21 from Screens.VirtualKeyBoard import VirtualKeyBoard
22 from os import stat as os_stat
23 from os import walk as os_walk
24 from Screens.Screen import Screen
25 from Components.config import config, ConfigSubList, ConfigSubsection, ConfigInteger, ConfigYesNo, ConfigText, getConfigListEntry, ConfigDirectory, ConfigSelection
26 from Components.ConfigList import ConfigListScreen
27 from Components.MenuList import MenuList
28 from Components.Label import Label
29 from Components.Pixmap import Pixmap
30 from Components.Sources.StaticText import StaticText
31 from Screens.MessageBox import MessageBox
32 from Screens.InfoBar import MoviePlayer as MP_parent
33 from Components.AVSwitch import AVSwitch
34 from Components.ActionMap import ActionMap
35 from Plugins.Plugin import PluginDescriptor
36 from Tools.HardwareInfo import HardwareInfo
37 from time import strftime as time_strftime
38 from time import localtime as time_localtime
39 from re import compile as re_compile
40 from os import path as os_path, listdir
41 from enigma import eConsoleAppContainer, eServiceReference, ePicLoad, getDesktop, eServiceCenter
42
43 #import players like Picture player, dvd player, music palyer
44 if os.path.exists("/usr/lib/enigma2/python/Plugins/Extensions/PicturePlayer/plugin.pyo") or os.path.exists("/usr/lib/enigma2/python/Plugins/Extensions/PicturePlayer/plugin.pyc"):
45         from Plugins.Extensions.PicturePlayer.plugin import Pic_Thumb, picshow
46         PicPlayerAviable = True
47 else:
48         PicPlayerAviable = False
49 if os.path.exists("/usr/lib/enigma2/python/Plugins/Extensions/DVDPlayer/plugin.pyo") or os.path.exists("/usr/lib/enigma2/python/Plugins/Extensions/DVDPlayer/plugin.pyc"):
50         from Plugins.Extensions.DVDPlayer.plugin import DVDPlayer
51         DVDPlayerAviable = True
52 else:
53         DVDPlayerAviable = False
54 if os.path.exists("/usr/lib/enigma2/python/Plugins/Extensions/MerlinMusicPlayer/plugin.pyo") or os.path.exists("/usr/lib/enigma2/python/Plugins/Extensions/MerlinMusicPlayer/plugin.pyc"):
55         from Plugins.Extensions.MerlinMusicPlayer.plugin import MerlinMusicPlayerScreen, Item
56         MMPavaiable = True
57 else:
58         MMPavaiable = False
59 # END of import players like Picture player, dvd player, music palyer
60
61
62 ###########################################################################
63
64 #define config:
65 config.plugins.subsdownloader = ConfigSubsection()
66 config.plugins.subsdownloader.path = ConfigText(default = "/", fixed_size = False)
67 config.plugins.subsdownloader.pathSave = ConfigYesNo(default = True)
68 config.plugins.subsdownloader.BlueButtonMenu = ConfigYesNo(default = True)
69 config.plugins.subsdownloader.AutoUpdate = ConfigYesNo(default = True)
70 config.plugins.subsdownloader.pathUseMediaPaternFilter = ConfigYesNo(default = False)
71 config.plugins.subsdownloader.extendedMenuConfig = ConfigYesNo(default = False)
72 #config.plugins.subsdownloader.del_sub_after_conv = ConfigYesNo(default = False)
73
74 #Create Subtitle Server plugin list
75 PERISCOPE_PLUGINS = list_XBMC_Periscope_plugins('/usr/lib/enigma2/python/Plugins/Extensions/SubsDownloader2/SourceCode/periscope/services/')
76 SUBTITLE_SERVER_LIST = [(("NapiProjekt"),"NapiProjekt"), (("Napisy24"),"Napisy24")]
77 for server in PERISCOPE_PLUGINS :
78         SUBTITLE_SERVER_LIST.append((server,server))
79 XBMC_PLUGINS = list_XBMC_Periscope_plugins('/usr/lib/enigma2/python/Plugins/Extensions/SubsDownloader2/SourceCode/xbmc_subtitles/services/')
80 for server in XBMC_PLUGINS:
81         SUBTITLE_SERVER_LIST.append((server,server))
82 config.plugins.subsdownloader.subtitleserver = ConfigSelection(default = "OpenSubtitle", choices = SUBTITLE_SERVER_LIST)
83 #Create Subtitle Server plugin list
84 #config.plugins.subsdownloader.subtitleserver = ConfigSelection(default = "OpenSubtitle", choices = [(("OpenSubtitle"),"OpenSubtitle"), (("NapiProjekt"),"NapiProjekt"), (("Napisy24"),"Napisy24")])
85
86 #Create Subtitle language list
87 from Plugins.Extensions.SubsDownloader2.SourceCode.xbmc_subtitles.utilities import toScriptLang
88 SubsDownloaderLangs = []
89 SubsDownloaderLangs.append(getConfigListEntry("None","None"))
90 for x in range(0,43):
91         SubsDownloaderLangs.append(getConfigListEntry(toScriptLang(str(x)),toScriptLang(str(x))))
92 SubsDownloaderLangs.append(getConfigListEntry("All","All"))
93 config.plugins.subsdownloader.SubsDownloader1stLang = ConfigSelection(default ="English", choices = SubsDownloaderLangs)
94 config.plugins.subsdownloader.SubsDownloader2ndLang = ConfigSelection(default ="Polish", choices = SubsDownloaderLangs)
95 config.plugins.subsdownloader.SubsDownloader3rdLang = ConfigSelection(default ="German", choices = SubsDownloaderLangs)
96 config.plugins.subsdownloader.Napisy24SearchMethod = ConfigSelection(default = "IMDB", choices = [(_("IMDB"),"IMDB"), (_("IMDB then movie filname"),"IMDB then movie filname"), (_("movie filname"),"movie filname")])
97
98
99 class SubsDownloaderApplication(Screen):
100         def __init__(self, session, args = 0):
101                 
102                 global Skin_width
103                 global Skin_height
104                 global Screen_width
105                 global Screen_height
106                 global is_libmediainfo
107                 
108                 Screen_width= getDesktop(0).size().width() #1280                
109                 Screen_height = getDesktop(0).size().height() #720              
110                 Skin_width = int(0.9*Screen_width) # 1152
111                 Skin_height = int(0.9*Screen_height) #648               
112                 widget_name_height = int(0.3* Skin_height)
113                 widget_name_width = int(0.74827* Skin_width)
114                 widget_name_x_position = int(0.0087*Skin_width)
115                 widget_name_y_position = int(0.0156 * Skin_height)
116                 widget_source_x_position = int(0.766 * Skin_width)
117                 widget_source_y_position = int(0.1081*Skin_height)
118                 widget_source_x_size = int(0.191*Skin_width)
119                 widget_source_y_size = int (26)
120                 font_size = int(int(0.0174*Skin_width))
121                 
122                 self.skin = "<screen position=\"center,"+str(int(0.078*Skin_height))+"\" size=\"" + str(Skin_width) + "," + str(Skin_height) +"\" title= \"Subtitle downloader\" > \
123                 <widget name=\"fileList\" position=\"" +str(widget_name_x_position)+","+str(1*widget_name_y_position)+"\" size=\""+str(widget_name_width)+","+str(widget_name_height)+"\" scrollbarMode=\"showOnDemand\" /> \
124                 <widget name=\"subsList\" position=\"" +str(widget_name_x_position)+","+str(2*widget_name_y_position+1*widget_name_height)+"\" size=\""+str(widget_name_width)+","+str(widget_name_height)+"\" scrollbarMode=\"showOnDemand\" /> \
125                 <widget name=\"commertialPicture\" position=\"" +str(widget_name_x_position)+","+str(3*widget_name_y_position+2*widget_name_height)+"\" size=\""+str(int(0.98*Skin_width))+","+str(widget_name_height)+"\" zPosition=\"1\" alphatest=\"on\" /> \
126                 <widget name=\"serverPicture\" position=\"" +str(widget_source_x_position)+","+str(widget_name_x_position)+"\" size=\""+str(int(0.252*Skin_width))+","+str(int(0.0849 * Skin_height))+"\" zPosition=\"1\" alphatest=\"on\" /> \
127                 <ePixmap pixmap=\"/usr/lib/enigma2/python/Plugins/Extensions/SubsDownloader2/pic/buttons/HD/key_menu.png\" position=\""+str(widget_source_x_position)+","+str(widget_source_y_position)+"\" size=\"36,26\" zPosition=\"1\" alphatest=\"on\" /> \
128                 <widget source=\"key_menu\" render=\"Label\" position=\""+str(widget_source_x_position+43)+","+str(widget_source_y_position)+"\" zPosition=\"1\" size=\""+str(widget_source_x_size)+","+str(widget_source_y_size)+"\" font=\"Regular;"+str(font_size)+"\" halign=\"left\" valign=\"center\" transparent=\"1\" /> \
129                 <ePixmap pixmap=\"/usr/lib/enigma2/python/Plugins/Extensions/SubsDownloader2/pic/buttons/HD/key_help.png\" position=\""+str(widget_source_x_position)+","+str(widget_source_y_position+widget_source_y_size)+"\" size=\"36,"+str(widget_source_y_size)+"\" zPosition=\"1\" alphatest=\"on\" /> \
130                 <widget source=\"key_help\" render=\"Label\" position=\""+str(widget_source_x_position+43)+","+str(widget_source_y_position+widget_source_y_size)+"\" zPosition=\"1\" size=\""+str(widget_source_x_size)+","+str(widget_source_y_size)+"\" font=\"Regular;"+str(font_size)+"\" halign=\"left\" valign=\"center\" transparent=\"1\" /> \
131                 <ePixmap pixmap=\"/usr/lib/enigma2/python/Plugins/Extensions/SubsDownloader2/pic/buttons/HD/key_text.png\" position=\""+str(widget_source_x_position)+","+str(widget_source_y_position+widget_source_y_size*2)+"\" size=\"36,"+str(widget_source_y_size)+"\" zPosition=\"1\" alphatest=\"on\" /> \
132                 <widget source=\"key_text\" render=\"Label\" position=\""+str(widget_source_x_position+43)+","+str(widget_source_y_position+widget_source_y_size*2)+"\" zPosition=\"1\" size=\""+str(widget_source_x_size)+","+str(widget_source_y_size)+"\" font=\"Regular;"+str(font_size)+"\" halign=\"left\" valign=\"center\" transparent=\"1\" /> \
133                 <ePixmap pixmap=\"/usr/lib/enigma2/python/Plugins/Extensions/SubsDownloader2/pic/buttons/HD/key_next.png\" position=\""+str(widget_source_x_position)+","+str(widget_source_y_position+widget_source_y_size*3)+"\" size=\"36,"+str(widget_source_y_size)+"\" zPosition=\"1\" alphatest=\"on\" /> \
134                 <widget source=\"key_next\" render=\"Label\" position=\""+str(widget_source_x_position+43)+","+str(widget_source_y_position+widget_source_y_size*3)+"\" zPosition=\"1\" size=\""+str(widget_source_x_size)+","+str(widget_source_y_size)+"\" font=\"Regular;"+str(font_size)+"\" halign=\"left\" valign=\"center\" transparent=\"1\" /> \
135                 <ePixmap pixmap=\"/usr/lib/enigma2/python/Plugins/Extensions/SubsDownloader2/pic/buttons/HD/key_last.png\" position=\""+str(widget_source_x_position)+","+str(widget_source_y_position+widget_source_y_size*4)+"\" size=\"36,"+str(widget_source_y_size)+"\" zPosition=\"1\" alphatest=\"on\" /> \
136                 <widget source=\"key_last\" render=\"Label\" position=\""+str(widget_source_x_position+43)+","+str(widget_source_y_position+widget_source_y_size*4)+"\" zPosition=\"1\" size=\""+str(widget_source_x_size)+","+str(widget_source_y_size)+"\" font=\"Regular;"+str(font_size)+"\" halign=\"left\" valign=\"center\" transparent=\"1\" /> \
137                 <ePixmap pixmap=\"/usr/lib/enigma2/python/Plugins/Extensions/SubsDownloader2/pic/buttons/HD/key_info.png\" position=\""+str(widget_source_x_position)+","+str(widget_source_y_position+widget_source_y_size*5)+"\" size=\"36,"+str(widget_source_y_size)+"\" zPosition=\"1\" alphatest=\"on\" /> \
138                 <widget source=\"key_info\" render=\"Label\" position=\""+str(widget_source_x_position+43)+","+str(widget_source_y_position+widget_source_y_size*5)+"\" zPosition=\"1\" size=\""+str(widget_source_x_size)+","+str(widget_source_y_size)+"\" font=\"Regular;"+str(font_size)+"\" halign=\"left\" valign=\"center\" transparent=\"1\" /> \
139                 </screen>"
140                 
141                 os.system('mkdir /tmp/SubsDownloader_cache')
142                 self.subsListDownloaded=0
143                 self.movie_fps=0
144                 self.localConvertion = False
145                 #self.subtitleExtention = "srt|txt|sub|nfo" #add other if someone gives remark
146                 self.MyBox = HardwareInfo().get_device_name()
147                 self.textEXTENSIONS = {
148                         "srt": "text",
149                         "txt": "text",
150                         "sub": "text",
151                         "nfo": "text",
152                         "cuts": "movie_timer",
153                         "zip": "package"
154                         }
155                 #self.mediaPatern = "^.*\.(jpe|)"
156                 #TODO OBSLUGA PLIKOW BZIP, ZIP, RAR
157                 #TODO Auto plugin update
158                 #TODO File manager (delete, copy, move, rename
159                 #TODO COMERTIAL for sponsor
160                 #TODO OTHER SUBTITLE FEEDERS
161                 #TODO VERSION CHANGE
162                 #TODO Think about automatic media patern make based on FileList module
163                 self["key_menu"] = StaticText("Config menu")
164                 self["key_help"] = StaticText("About...")
165                 self["key_text"] = StaticText("Subtitle download")
166                 self["key_next"] = StaticText("SubsList enable")
167                 self["key_last"] = StaticText("FileList enable")
168                 self["key_info"] = StaticText("File size")
169                 self.mediaPatern = self.make_media_patern()
170                 
171                 try:
172                         fileListPath = config.plugins.subsdownloader.path.value
173                 except:
174                         fileListPath = "/"
175                                 
176                 self.session = session
177                 Screen.__init__(self, session)
178                 self.altservice = self.session.nav.getCurrentlyPlayingServiceReference()
179                 list = []
180                 if config.plugins.subsdownloader.pathUseMediaPaternFilter.value == True:
181                         self["fileList"] = FileList(fileListPath, matchingPattern = None)
182                 else:
183                         self["fileList"] = FileList(fileListPath, matchingPattern = self.mediaPatern)
184                 self.selectedList = self["fileList"]
185                 self["subsList"] = MenuList(list)
186                 self.clearSubList()
187                 self.set_listFile_enabled()
188                 
189                 self["myActionMap"] = ActionMap(["ChannelSelectBaseActions","WizardActions", "DirectionActions","MenuActions","NumberActions","ColorActions","SubsDownloaderApplication_actions"],                            
190                 {
191                         "ok": self.ok,
192                         "back": self.closeApplication,
193                         "about": self.showAboutScreen,
194                         "subSelect": self.downloadSubtitle,
195                         "menu": self.showConfigScreen,
196                         "nextMarker": self.set_listSubs_enabled,
197                         "prevMarker": self.set_listFile_enabled,
198                         "up": self.goUp,
199                         "down": self.goDown,
200                         "left": self.goLeft,
201                         "right": self.goRight,
202                         "info": self.FM_file_Info, 
203                         "localConv": self.localConvertionSublist,
204                         #"0": self.show_hide_skin,
205                         #"red": self.goRed,
206                         #"green": self.goGreen,
207                         #"yellow": self.goYellow,
208                         #"blue": self.goBlue,                   
209                 }, -2)
210                 
211         
212                 
213                 #PICTURE INITIALIZATION
214                 self.EXscale = (AVSwitch().getFramebufferScale())
215                 #1st picture 
216                 self.ServerPicture = ePicLoad()
217                 self["serverPicture"] = Pixmap()
218                 self.ServerPicture.PictureData.get().append(self.DecodeServerPictureAction)
219                 self.serverPicturePath = "/usr/lib/enigma2/python/Plugins/Extensions/SubsDownloader2/pic/none1.jpg"
220                 self.onLayoutFinish.append(self.Show_Server_Picture)
221                 
222                 self.display_Server_Picture()
223         
224                 #2nd picture
225                 self.CommertialPicture = ePicLoad()
226                 self["commertialPicture"] = Pixmap()
227                 self.CommertialPicture.PictureData.get().append(self.DecodeCommertialPictureAction)
228                 #self.CommertialPicturePath = "/usr/lib/enigma2/python/Plugins/Extensions/SubsDownloader2/pic/none1.jpg"
229                 flagcounetr() #remove it in next veriosn
230                 self.CommertialPicturePath = "/usr/lib/enigma2/python/Plugins/Extensions/SubsDownloader2/pic/commertial_banner.jpg"
231                 self.onLayoutFinish.append(self.Show_Commertial_Picture)
232
233                 """Oczywiscie trzeba stworzyc widget i pokopiowac odpowiednie funkcje inicjalizujace"""
234                 #PICTURE INITIALIZATION
235                 self.set_title()
236                 
237                               
238         def call(c = None):
239                 pass
240                 
241         def set_title(self):
242                 if is_libmediainfo == False:
243                         self.setTitle("Subtitle downloader (without libmediainfo)")
244                 elif is_libmediainfo == True:
245                         self.setTitle("Subtitle downloader (with libmediainfo)")
246
247
248 #!!!!!!!!!!!! file manager functions!!!!!!#
249         def FM_file_Info(self):
250                 if self["fileList"].canDescent():
251                         if self["fileList"].getSelectionIndex()!=0:
252                                 curSelDir = self["fileList"].getSelection()[0]
253                                 dir_stats = os_stat(curSelDir)
254                                 dir_infos = "DIR:    size "+str(self.FM_Humanizer(dir_stats.st_size))+"    "
255                                 #dir_infos = dir_infos+"last-mod "+time_strftime("%d.%m.%Y %H:%M:%S",time_localtime(dir_stats.st_mtime))+"    "
256                                 #dir_infos = dir_infos+"mode "+str(dir_stats.st_mode)
257                                 self.setTitle(_(dir_infos))
258                         else:
259                                 dei = self.session.open(MessageBox, _("Dreambox: " + self.MyBox + "\n\n"), MessageBox.TYPE_INFO)
260                                 dei.setTitle(_("Device"))                               
261                                                                 
262                 else:
263                         curSelFile = self["fileList"].getCurrentDirectory() + self["fileList"].getFilename()
264                         file_stats = os_stat(curSelFile)
265                         file_infos = self.return_media_kind(self.return_extention(curSelFile)).upper() + ":    "
266                         file_infos = file_infos + "size "+str(self.FM_Humanizer(file_stats.st_size))#+"    "
267                         #file_infos = file_infos+"last-mod "+time_strftime("%d.%m.%Y %H:%M:%S",time_localtime(file_stats.st_mtime))+"    "
268                         #file_infos = file_infos+"mode "+str(file_stats.st_mode)
269                         self.setTitle(_(file_infos))
270
271         def FM_Humanizer(self, size):
272                 if (size < 1024):
273                         humansize = str(size)+" B"
274                 elif (size < 1048576):
275                         humansize = str(size/1024)+" KB"
276                 else:
277                         humansize = str(size/1048576)+" MB"
278                 return humansize        
279
280
281 #!!!!!!!!!!!! file manager functionS!!!!!!#
282
283
284 # !!!!!!!!!!!! PICTURE FUNCTIONS !!!!!!!!!!!!!! 
285         def display_Server_Picture(self):
286                 """Function display suittalbe picture in ["serverPicture"] (based on subtitle server)""" 
287                 self.serverPicturePath = "/usr/lib/enigma2/python/Plugins/Extensions/SubsDownloader2/pic/%s.jpg" % config.plugins.subsdownloader.subtitleserver.value
288                 #if config.plugins.subsdownloader.subtitleserver.value == "OpenSubtitle":
289                 #       self.serverPicturePath = "/usr/lib/enigma2/python/Plugins/Extensions/SubsDownloader2/pic/OpenSubtitle.jpg"
290                 #if config.plugins.subsdownloader.subtitleserver.value == "NapiProjekt":
291                 #       self.serverPicturePath = "/usr/lib/enigma2/python/Plugins/Extensions/SubsDownloader2/pic/NapiProject.jpg"
292                 #if config.plugins.subsdownloader.subtitleserver.value == "Napisy24":
293                 #       self.serverPicturePath = "/usr/lib/enigma2/python/Plugins/Extensions/SubsDownloader2/pic/Napisy24.jpg"          
294                 self.ServerPicture.startDecode(self.serverPicturePath)
295                 
296         def Show_Server_Picture(self):
297                 """This function is required to init witget ["serverPicture"] and picture class [self.ServerPicture]"""
298                 self.ServerPicture.setPara([self["serverPicture"].instance.size().width(), self["serverPicture"].instance.size().height(), self.EXscale[0], self.EXscale[1], 0, 1, "#002C2C39"])
299                 self.ServerPicture.startDecode(self.serverPicturePath)
300                 
301         def DecodeServerPictureAction(self, pictureInfo=""):
302                 """This function is required to init witget ["serverPicture"] and picture class [self.ServerPicture]"""
303                 ptr = self.ServerPicture.getData()
304                 self["serverPicture"].instance.setPixmap(ptr)
305                 #text = picInfo.split('\n',1)    #WYSWIETLA INFORMACJE NA TEMAT OBRAZKA
306                 #self["label"].setText(text[1])  #WYSWIETLA INFORMACJE NA TEMAT OBRAZKA
307         
308         def Show_Commertial_Picture(self):
309                 """This function is required to init witget ["commertialPicture"] and picture class self.CommertialPicture"""
310                 self.CommertialPicture.setPara([self["commertialPicture"].instance.size().width(), self["commertialPicture"].instance.size().height(), self.EXscale[0], self.EXscale[1], 0, 1, "#002C2C39"])
311                 self.CommertialPicture.startDecode(self.CommertialPicturePath)
312                 
313         def DecodeCommertialPictureAction(self, pictureInfo=""):
314                 """This function is required to init witget ["serverPicture"] and picture class [self.ServerPicture]"""
315                 ptr = self.CommertialPicture.getData()
316                 self["commertialPicture"].instance.setPixmap(ptr)
317                 #text = picInfo.split('\n',1)    #WYSWIETLA INFORMACJE NA TEMAT OBRAZKA
318                 #self["label"].setText(text[1])  #WYSWIETLA INFORMACJE NA TEMAT OBRAZKA         
319                 
320         def display_Commmertial_Picture(self):
321                 pass
322                 
323         
324 # !!!!!!!!!!!! PICTURE FUNCTIONS !!!!!!!!!!!!!! 
325                 
326                 
327         def clearSubList(self):
328                 """Clear subList and prevent to download unwanted subtitle"""
329                 self.serverAvailableSubtitles=[]
330                 self["subsList"].setList(self.serverAvailableSubtitles)
331                 self.subsListDownloaded=0
332                 self.set_listFile_enabled()
333                 
334         def setServerAvailableSubtitles_for_PERISCOPE(self,serverList):
335                 """Function preper (appends) serverAvailableSubtitles which is seted by 
336                 comend self["subsList"].setList(self.serverAvailableSubtitles)"""
337                 self.serverAvailableSubtitles=[]
338                 position = 0
339                 for x  in serverList:
340                         self.serverAvailableSubtitles.append((_("["+str(x['lang'])+"]___"+str(x['release'])), str(position))) #makes list of subtitles
341                         position = position +1
342                 self.subsListDownloaded=1
343                 self["subsList"].setList(self.serverAvailableSubtitles)
344                 self.set_listSubs_enabled()
345                         
346         def setServerAvailableSubtitles_for_Napisy24(self,serverList):
347                 """Function preper (appends) serverAvailableSubtitles which is seted by 
348                 comend self["subsList"].setList(self.serverAvailableSubtitles)"""
349                 self.serverAvailableSubtitles=[]
350                 position = 0
351                 for x  in serverList:
352                         self.serverAvailableSubtitles.append((str(x['language']).replace("u'","").replace("'","")+"_" \
353                                                               +str(x['cd']).replace("u'","").replace("'","")+"cd"+"__"\
354                                                               +str(x['title']).replace("u'","").replace("'","")+" "\
355                                                               +str(x['release']).replace("u'","").replace("'",""), position)) #makes list of subtitles
356                         position = position +1
357                 self.subsListDownloaded=1
358                 self["subsList"].setList(self.serverAvailableSubtitles)
359                 self.set_listSubs_enabled()
360                 
361         def saveSubtitleasSRT(self, subtitleFile, fps, subtitleCodePage):
362                 """Function converts and saves downloaded subtitle in suitable ditectory"""
363                 #codePageDecoded= self.chardetOutputTranslation(subtitleCodePage)
364                 self.subtitle_codepade = codePageDecoded= chardetOutputTranslation(subtitleCodePage)
365                 convertedSubtitle = SubConv(subtitleFile, codePageDecoded)
366                 #convertedSubtitle.subs_file = convertedSubtitle.to_utf_8(convertedSubtitle.subs_file,codePageDecoded)
367                 #convertedSubtitle.subs_file = convertedSubtitle.to_utf_8(convertedSubtitle.subs_file)
368                 subtitleFormat = convertedSubtitle.detect_format(convertedSubtitle.subs_file)
369                 #TODO IN TERMINAF SHOW PROGRESS
370                 if subtitleFile != "None" and fps != "None" and codePageDecoded != "None" and subtitleFormat != "None":
371                         progress_message="Saved subtitle file: %s \nDetected oryginal subtitle format:  %s \nDetected subtitle CodePage: %s (%s) with probability %s \nDetected movie FPS: %s \n   PRES OK KEY TO CONTINUE..." % (subtitleFile, subtitleFormat, subtitleCodePage['encoding'],codePageDecoded, subtitleCodePage['confidence'],fps)
372                         self.session.open(MessageBox, _(progress_message),  MessageBox.TYPE_INFO)
373                         if subtitleFormat == "mdvd":
374                                 convertedSubtitle.subs_file = convertedSubtitle.read_mdvd(convertedSubtitle.subs_file,fps)
375                         elif subtitleFormat == "tmp":
376                                 convertedSubtitle.subs_file = convertedSubtitle.read_tmp(convertedSubtitle.subs_file)
377                         elif subtitleFormat == "sub2":
378                                 convertedSubtitle.subs_file = convertedSubtitle.read_sub2(convertedSubtitle.subs_file)
379                         elif subtitleFormat == "srt":
380                                 convertedSubtitle.subs_file = convertedSubtitle.read_srt(convertedSubtitle.subs_file)
381                         elif subtitleFormat == "mpl2":
382                                 #convertedSubtitle.subs_file = convertedSubtitle.read_mpl2(convertedSubtitle.subs_file, fps)
383                                 convertedSubtitle.subs_file = convertedSubtitle.read_mpl2(convertedSubtitle.subs_file)
384                         convertedSubtitle.subs_file = convertedSubtitle.check_subs_long(convertedSubtitle.subs_file, fps)
385                         #convertedSubtitle.save_subtitle(subtitleFile, convertedSubtitle.subs_file)
386                         convertedSubtitle.save_subtitle(convertedSubtitle.subs_file)
387                 else:
388                         if subtitleFile == "None":
389                                 self.session.open(MessageBox,_("Can't find subtitle file on storage device.\n Check:\n -network connection,\n - subtitle server availability,\n - storage device access."), MessageBox.TYPE_INFO)
390                         if fps == "None":
391                                 self.session.open(MessageBox,_("Can't detect movie FPS. Please install libMediaInfor from ConfigurationMenu."), MessageBox.TYPE_INFO)
392                                 #TODO automatic send email with: subtitle, filn hash sume to developer - if user allow for this - for developement reaseons
393                         if codePageDecoded == "None":
394                                 self.session.open(MessageBox,_("Can't detect downloaded subtitle code page. Please contact with developer to correct this in future versions."), MessageBox.TYPE_INFO)
395                                 #TODO automatic send email with: subtitle, filn hash sume to developer - if user allow for this - for developement reaseons
396                                 self.session.open(MessageBox,_("Can't detect downloaded subtitle format. Please contact with developer to correct this in future versions."), MessageBox.TYPE_INFO)
397                                 #TODO automatic send email with: subtitle, filn hash sume to developer - if user allow for this - for developement reaseons     
398                 return subtitleFormat
399                                 
400         def getSubtitleCodepade(self, subtitle):
401                 """Function gets subtitle file codepage using Chardet library"""
402                 subtitleFile = open(subtitle, 'r')
403                 data = subtitleFile.read()
404                 subtitleFile.close()
405                 return chardet.detect(data)
406         
407         def goLeft(self):
408                 self.selectedList.pageUp()
409                 
410         def goRight(self):
411                 self.selectedList.pageDown()    
412         
413         def getMovieFPS(self, movie):
414                 try:
415                         choosen_movie = GetFPS(movie)
416                         #return float(str(round(choosen_movie.fps(),3))[0:-1])
417                         return round(choosen_movie.fps(),3) #JESLI NAPISY NIE BEDA W CZASIE PADSOWAC TO POKOMBINOWAC Z TA LINIJKA
418                 except:
419                         self.session.open(MessageBox,_("I can't detect movie FPS!!!"), MessageBox.TYPE_INFO, timeout = 5)
420                         return "None"
421
422         def __defaults_before_subtitle_download_and_convertion(self):
423                 self.subtitle_database = 0
424                 self.movie_filename = 0
425                 self.subtitles = 0
426                 self.subtitle_filename = 0
427                 self.clearSubList()
428                 
429         def localConvertionSublist(self):
430                 """Search dir for subtitle file and converts it to given movie file"""
431                 selected_movie_dir = self["fileList"].getCurrentDirectory()
432                 selected_movie_file = self["fileList"].getFilename()
433                 self.local_subtitle = []
434                 if self.selectedList == self["fileList"] and self.return_media_kind(self.return_extention(selected_movie_file))=="movie":
435                         self.localConvertion = True
436                         self.session.open(MessageBox,_("Local subtitle convertion for:\n%s." % (str(selected_movie_file))), MessageBox.TYPE_INFO, timeout = 15)
437                         self.__defaults_before_subtitle_download_and_convertion()
438                         self.movie_filename = selected_movie_dir+selected_movie_file
439                         file_list = self["fileList"].getFileList()
440                         for x  in file_list:
441                                 if x[0][-1] != True: #not directory
442                                         if self.return_media_kind(self.return_extention(x[0][0]))=="text":# and LocalConvertedSubtitle.detect_format(LocalConvertedSubtitle.subs_file) != "None":
443                                                 #localCodePageDecoded= self.chardetOutputTranslation(self.getSubtitleCodepade(selected_movie_dir+x[0][0]))
444                                                 self.subtitle_codepade = localCodePageDecoded = chardetOutputTranslation(self.getSubtitleCodepade(selected_movie_dir+x[0][0]))
445                                                 LocalConvertedSubtitle = SubConv((selected_movie_dir + x[0][0]), localCodePageDecoded)
446                                                 if LocalConvertedSubtitle.detect_format(LocalConvertedSubtitle.subs_file) != "None":
447                                                         self.local_subtitle.append((_(x[0][0]), str(selected_movie_dir+x[0][0]))) #makes list of subtitles"""
448                                                         self.subsListDownloaded = 1                                                     
449                         self["subsList"].setList(self.local_subtitle)
450                         self.set_listSubs_enabled()
451                 else:
452                         self.session.open(MessageBox,_("I can't convert subtitle for this kind of media!!!"), MessageBox.TYPE_INFO, timeout = 5)
453                 
454         def localConvertionFileConvert(self,callbackAnswer):
455                 if callbackAnswer is True:
456                         try:
457                                 if self.whichSubtitleDownload != self.subtitle_filename:
458                                         shutil.copy2(str(self.whichSubtitleDownload), str(self.subtitle_filename))
459                                 self.subtitle_codepade = self.getSubtitleCodepade(self.subtitle_filename)
460                                 self.movie_fps = self.getMovieFPS(self.movie_filename)
461                                 self.subtitle_filename_type = self.saveSubtitleasSRT(self.subtitle_filename, self.movie_fps, self.subtitle_codepade)
462                                 self["fileList"].refresh()
463                         except:
464                                 self.failed_to_download_subtitle_nfo(self.subtitle_filename,self.subtitle_codepade,self.subtitle_filename_type,self.movie_fps)          
465                 
466         def downloadSubtitle(self):
467                 """Download Subtitle for movie variable self.textEXTENSIONS has defived all supported files and their king.
468                 Variable self.textEXTENSIONS is self.textEXTENSIONS and EXTENSIONS union"""
469
470                 self.__defaults_before_subtitle_download_and_convertion()
471                 self.localConvertion = False
472                 if self["fileList"].canDescent():
473                         self.session.open(MessageBox,_("I can't download subtitle for this kind of media!!!"), MessageBox.TYPE_INFO, timeout = 5)
474                 else:
475                         self.movie_filename = self["fileList"].getCurrentDirectory() + self["fileList"].getFilename()
476                         if self.return_media_kind(self.return_extention(self.movie_filename))=="movie":
477                                 if config.plugins.subsdownloader.subtitleserver.value in PERISCOPE_PLUGINS: #== "OpenSubtitle":
478                                         exec('from Plugins.Extensions.SubsDownloader2.SourceCode.periscope.services.%s.services import %s as SERVICE') % (config.plugins.subsdownloader.subtitleserver.value,config.plugins.subsdownloader.subtitleserver.value)
479                                         self.subtitles = SERVICE(None,'/tmp/SubsDownloader_cache/')
480                                         try:
481                                                 self.subtitle_database=self.subtitles.process(self.movie_filename,[config.plugins.subsdownloader.SubsDownloader1stLang.value,config.plugins.subsdownloader.SubsDownloader2ndLang.value,config.plugins.subsdownloader.SubsDownloader3rdLang.value])
482                                         except:
483                                                 pass
484                                         #TODO TU BY SIE PRZYDALA OBSLUGA WYJATKOW Z KOMENDY POWYZEJ
485                                         if len(self.subtitle_database) == 0:
486                                                 self.clearSubList()
487                                                 self.session.open(MessageBox,_("There is no subtitle on this server to Your movie. \nPlease try another language or subtitle server.\n\nIf error still appears please check network connection with server."), MessageBox.TYPE_INFO, timeout = 5)
488                                         else:
489                                                 self.setServerAvailableSubtitles_for_PERISCOPE(self.subtitle_database)
490                                 elif config.plugins.subsdownloader.subtitleserver.value == "NapiProjekt":
491                                         self.isSubtitleDowloaded=0
492                                         self.whichSubtitleDownload="None"
493                                         self.subtitle_filename = "None"
494                                         self.movie_fps = "None"
495                                         self.subtitle_codepade = "None"
496                                         self.subtitle_filename_type = "None"
497                                         
498                                         self.movie_filename = self["fileList"].getCurrentDirectory() + self["fileList"].getFilename()
499                                         self.NapiSubtitle = NapiProjekt()
500                                         try:
501                                                 self.NapiSubtitle.getnapi(self.movie_filename)
502                                                 self.subtitle_filename = self.NapiSubtitle.save()
503                                                 self.subtitle_codepade = self.getSubtitleCodepade(self.subtitle_filename)
504                                                 self.movie_fps = self.getMovieFPS(self.movie_filename)
505                                                 self.subtitle_filename_type = self.saveSubtitleasSRT(self.subtitle_filename, self.movie_fps, self.subtitle_codepade)
506                                         except:
507                                                 self.failed_to_download_subtitle_nfo(self.subtitle_filename,self.subtitle_codepade,self.subtitle_filename_type,self.movie_fps)
508                                         self["fileList"].refresh()
509                                         #TODO SUBTITLE SELECTION AND DOWNLOAD OTHER SERVERS
510                                         pass
511                                 elif config.plugins.subsdownloader.subtitleserver.value == "Napisy24":
512                                         N24_movie_name = None
513                                         N24_imdb_search = None
514                                         self.virtualKeyboardOpen()
515                         elif config.plugins.subsdownloader.subtitleserver.value == "Napisy24":
516                                 pass
517                         else:
518                                 self.session.open(MessageBox,_("I can't download subtitle for this kind of media!!!"), MessageBox.TYPE_INFO, timeout = 5)
519
520         def virtualKeyboardOpen(self):
521                 if config.plugins.subsdownloader.Napisy24SearchMethod.value == "IMDB then movie filname" or config.plugins.subsdownloader.Napisy24SearchMethod.value == "movie filname":
522                         self.session.openWithCallback(self.VirtualKeyboartCallback, VirtualKeyBoard, title = ("Search subtitle(s) for:\n%s" % self["fileList"].getFilename()), text = self["fileList"].getFilename().rsplit(".",1)[0])
523                 else:
524                         self.VirtualKeyboartCallback(callback = None)
525                                                         
526         def VirtualKeyboartCallback(self, callback = None):
527                 N24_movie_name = None
528                 N24_imdb_search = None
529                 IMDM_results = None
530                 if config.plugins.subsdownloader.Napisy24SearchMethod.value == "IMDB":
531                         N24_imdb_search = True
532                         #N24_movie_name = None
533                 elif config.plugins.subsdownloader.Napisy24SearchMethod.value == "IMDB then movie filname":
534                         N24_imdb_search = True
535                         N24_movie_name = callback
536                 elif config.plugins.subsdownloader.Napisy24SearchMethod.value == "movie filname" and callback != None:
537                         N24_imdb_search = False                                         
538                         N24_movie_name = callback
539                 self.subtitles = Napisy24_pl(self.movie_filename, N24_movie_name)
540                 if N24_imdb_search == True:
541                         #IMDB search method - seek NFO file
542                         IMDM_results = self.subtitles.IMDB_idenifier_search()
543                         if IMDM_results != False:
544                                 #IMDB search method - if NFO contains IMBD try to download XML by IMBD number
545                                 if self.subtitles.getNapisy24_SubtitleListXML("downloada_subtitle_list_by_IMDB") ==  False and N24_movie_name != None:
546                                         #IMDB then movie filname dearch method - If XML download by IMBD number fails try to download by movie name
547                                         self.subtitles.getNapisy24_SubtitleListXML("downloada_subtitle_list_by_film_name")
548                         elif IMDM_results == False:
549                                 #IMDB then movie filname dearch method - in case there is no NFO file
550                                 self.subtitles.getNapisy24_SubtitleListXML("downloada_subtitle_list_by_film_name")
551                 if N24_imdb_search == False and N24_movie_name != None:
552                         #movie filname search method
553                         self.subtitles.getNapisy24_SubtitleListXML("downloada_subtitle_list_by_film_name")
554                 if self.subtitles.subtitle_dict != []:
555                         self.setServerAvailableSubtitles_for_Napisy24(self.subtitles.subtitle_dict)
556                 else:
557                         if (IMDM_results == False or IMDM_results ==None) and N24_movie_name == None:
558                                 if config.plugins.subsdownloader.Napisy24SearchMethod.value == "IMDB":
559                                         self.session.open(MessageBox,_("NAPISY24 searching method error:\n\nCan't find IMDB identifier for this movie.\nPlease try another searching method."), MessageBox.TYPE_INFO, timeout = 10)
560                                 elif config.plugins.subsdownloader.Napisy24SearchMethod.value == "IMDB then movie filname":
561                                         self.session.open(MessageBox,_("NAPISY24 searching method error:\n\nBoth IMDB and movie name haven't values. \nPlease give at least one correct searching value."), MessageBox.TYPE_INFO, timeout = 10)
562                                 elif config.plugins.subsdownloader.Napisy24SearchMethod.value == "movie filname":
563                                         self.session.open(MessageBox,_("NAPISY24 searching method error:\n\nPlease enter movie name to search."), MessageBox.TYPE_INFO, timeout = 10)
564                         else:
565                                 self.session.open(MessageBox,_("There is no subtitle on this server to Your movie. \nPlease try another search method or subtitle server.\n\nIf error still appears please check network connection with server."), MessageBox.TYPE_INFO, timeout = 10)
566
567         def failed_to_download_subtitle_nfo(self,subtitle_filename,subtitle_codepade_,subtitle_filename_type,movie_fps):
568                 self.session.open(MessageBox,_("Failed to download or save file.\nPossible problems:\n- Subtitle filname:\n%s\n- Subtitle codepage:\n%s\n- Subtitle filetype:\n%s\n- Movie fsp:\n%s\n.") % (subtitle_filename,subtitle_codepade_,subtitle_filename_type,movie_fps), MessageBox.TYPE_INFO, timeout = 15)
569                 
570         def make_media_patern(self):
571                 """Creare media patern to file browser based on self.textEXTENSIONS from this module
572                 and EXTENSIONS fron FileList module"""
573                 self.textEXTENSIONS.update(EXTENSIONS)
574                 return "^.*\.(" + str.join('|',self.textEXTENSIONS.keys()) + ")"
575         
576         def return_extention(self, file_path):
577                 """get filename and return file extention"""
578                 extention = file_path
579                 return extention.split('.')[-1]
580         
581         def return_media_kind(self,file_extention):
582                 """Function returns what kind of file is it: text, movie, sysyem, picture"""
583                 try:
584                         return self.textEXTENSIONS[file_extention]
585                 except:
586                         return 'not_supported'
587         
588         def showConfigScreen(self):
589                 """ Display config screen for Subs Downloader"""
590                 self.set_listFile_enabled()
591                 self.subsListDownloaded=0
592                 self.serverAvailableSubtitles=[]
593                 self["subsList"].setList(self.serverAvailableSubtitles)
594                 #self.session.open(SubsDownloaderConfig)
595                 #self.session.openWithCallback(self.display_Server_Picture, SubsDownloaderConfig)
596                 self.session.openWithCallback(self.MainMenuCallback, SubsDownloaderConfig)
597                 
598                 #TODO POPRAWIC TO PONIEWAZ NIE ZMIENIA SIE PO POWROCIE Z self.session.open(SubsDownloaderConfig)
599                 #self.display_Server_Picture()
600
601         def MainMenuCallback(self):
602                 self.display_Server_Picture()
603                 if config.plugins.subsdownloader.pathUseMediaPaternFilter.value == True:
604                         self["fileList"].matchingPattern = self.mediaPatern
605                 else:
606                         self["fileList"].matchingPattern = None
607                 self["fileList"].refresh()
608                 
609         def set_listFile_enabled(self):
610                 """Function makes self["fileList"] as active"""
611                 self["fileList"].selectionEnabled(1)
612                 self["subsList"].selectionEnabled(0)
613                 self.selectedList = self["fileList"]
614                 
615         def set_listSubs_enabled(self):
616                 """If subtitle was found and list was generated function makes self["subsList"] as active.
617                 The condition is that self.subsListDownloaded is "1". Condition is seted in downloadSubtitle function.
618                 Not alvays seting of self["subsList"] is required."""
619                 if self.subsListDownloaded ==1:
620                         self.localConvertion == True
621                         self["fileList"].selectionEnabled(0)
622                         self["subsList"].selectionEnabled(1)
623                         self.selectedList = self["subsList"]
624         
625         def __pass__(self):
626                 pass
627         
628         def ok(self):
629                 global DVDPlayerAviable
630                 if self.selectedList == self["fileList"]:
631                         if self["fileList"].canDescent():
632                                 """If dir makes cd"""
633                                 self["fileList"].descent()
634                         else:
635                                 filename = self["fileList"].getCurrentDirectory() + self["fileList"].getFilename()
636                                 testFileName = self["fileList"].getFilename()
637                                 testFileName = testFileName.lower()
638                                 if filename != None:
639                                         """if self.return_media_kind(self.return_extention(filename))=="movie":
640                                                 #try:
641                                                         #check if its GP3 if yes use ExMoviePlayer
642                                                 from Plugins.Bp.geminimain.gMoviePlayer import ExMoviePlayer
643                                                 self.session.open(ExMoviePlayer, "/hdd/Net_HDD/Filmy/Hop/Hop 2011 PLDUBB.720p.BluRay.x264-DiAM0ND.mkv")
644                                                 #except:
645                                                         #if it's not GP3 use Dream Explorer II exxecution mode
646                                                 #       pass"""
647                                         if testFileName.endswith(".ts"):
648                                                 fileRef = eServiceReference("1:0:0:0:0:0:0:0:0:0:" + filename)
649                                                 self.session.open(MoviePlayer, fileRef)
650                                         elif (testFileName.endswith(".mpg")) or (testFileName.endswith(".mpeg")) or (testFileName.endswith(".mkv")) or (testFileName.endswith(".m2ts")) or (testFileName.endswith(".vob")) or (testFileName.endswith(".mod")):
651                                                 fileRef = eServiceReference("4097:0:0:0:0:0:0:0:0:0:" + filename)
652                                                 self.session.open(MoviePlayer, fileRef)
653                                         elif (testFileName.endswith(".avi")) or (testFileName.endswith(".mp4")) or (testFileName.endswith(".divx")) or (testFileName.endswith(".mov")) or (testFileName.endswith(".flv")) or (testFileName.endswith(".3gp")):
654                                                 if not(self.MyBox=="dm7025"):   
655                                                         fileRef = eServiceReference("4097:0:0:0:0:0:0:0:0:0:" + filename)
656                                                         self.session.open(MoviePlayer, fileRef)                                         
657                                         elif (testFileName.endswith(".mp3")) or (testFileName.endswith(".wav")) or (testFileName.endswith(".ogg")) or (testFileName.endswith(".m4a")) or (testFileName.endswith(".mp2")) or (testFileName.endswith(".flac")):
658                                                 if (self.MyBox=="dm7025") and ((testFileName.endswith(".m4a")) or (testFileName.endswith(".mp2")) or (testFileName.endswith(".flac"))):
659                                                         return
660                                                 if MMPavaiable:
661                                                         SongList,SongIndex = self.searchMusic()
662                                                         try:
663                                                                 self.session.open(MerlinMusicPlayerScreen, SongList, SongIndex, False, self.altservice, None)
664                                                         except:
665                                                                 self.session.open(MessageBox, _("Incompatible MerlinMusicPlayer version!"), MessageBox.TYPE_INFO, timeout = 5)
666                                                 else:
667                                                         fileRef = eServiceReference("4097:0:0:0:0:0:0:0:0:0:" + filename)
668                                                         m_dir = self["fileList"].getCurrentDirectory()
669                                                         self.session.open(MusicExplorer, fileRef, m_dir, testFileName)
670                                         elif (testFileName.endswith(".jpg")) or (testFileName.endswith(".jpeg")) or (testFileName.endswith(".jpe")) or (testFileName.endswith(".png")) or (testFileName.endswith(".bmp")):
671                                                 if self["fileList"].getSelectionIndex()!=0:
672                                                         Pdir = self["fileList"].getCurrentDirectory()
673                                                         self.session.open(PictureExplorerII, filename, Pdir)
674                                         elif (testFileName.endswith(".mvi")):
675                                                 self.session.nav.stopService()
676                                                 self.session.open(MviExplorer, filename)
677                                         elif (testFileName == "video_ts.ifo"):
678                                                 if DVDPlayerAviable:
679                                                         if (self["fileList"].getCurrentDirectory()).lower().endswith("video_ts/"):
680                                                                 self.session.open(DVDPlayer, dvd_filelist=[self["fileList"].getCurrentDirectory()])
681                                         elif testFileName.endswith(".iso"):
682                                                 if DVDPlayerAviable:
683                                                         self.session.open(DVDPlayer, dvd_filelist=[filename])
684                                         elif testFileName.endswith(".tar.gz"):
685                                                 self.commando = [ "tar -xzvf " + filename + " -C /" ]
686                                                 askList = [(_("Cancel"), "NO"),(_("Install this package"), "YES")]
687                                                 dei = self.session.openWithCallback(self.SysExecution, ChoiceBox, title=_("GZ-package:\\n"+filename), list=askList)
688                                                 dei.setTitle(_("Subtitle Downloader : Install..."))
689                                         elif testFileName.endswith(".tar.bz2"):
690                                                 self.commando = [ "tar -xjvf " + filename + " -C /" ]
691                                                 askList = [(_("Cancel"), "NO"),(_("Install this package"), "YES")]
692                                                 dei = self.session.openWithCallback(self.SysExecution, ChoiceBox, title=_("BZ2-package:\\n"+filename), list=askList)
693                                                 dei.setTitle(_("SubsDownloader : Install..."))
694                                         elif testFileName.endswith(".ipk"):
695                                                 if fileExists("/usr/bin/opkg"):
696                                                         self.commando = [ "opkg install " + filename ]
697                                                 else:
698                                                         self.commando = [ "ipkg install " + filename ]
699                                                         askList = [(_("Cancel"), "NO"),(_("Install this package"), "YES")]
700                                                         dei = self.session.openWithCallback(self.SysExecution, ChoiceBox, title=_("IPKG-package:\\n"+filename), list=askList)
701                                                         dei.setTitle(_("SubsDownloader : Install..."))
702                                         elif testFileName.endswith(".sh"):
703                                                 self.commando = [ filename ]
704                                                 askList = [(_("Cancel"), "NO"),(_("View this shell-script"), "VIEW"),(_("Start execution"), "YES")]
705                                                 self.session.openWithCallback(self.SysExecution, ChoiceBox, title=_("Do you want to execute?\\n"+filename), list=askList)
706                                         else:
707                                                 xfile=os_stat(filename)
708                                                 if (xfile.st_size < 61440):
709                                                         self.session.open(vEditor, filename)
710                                                 else:
711                                                         self.session.open(MessageBox, _("File size is bigger than 61440.\n\n Subs Downloader can't manage it with vEditor."), MessageBox.TYPE_INFO, timeout = 5)
712                 if self.selectedList == self["subsList"]:
713                         self.isSubtitleDowloaded=0
714                         self.whichSubtitleDownload="None"
715                         self.subtitle_filename = "None"
716                         self.movie_fps = "None"
717                         self.subtitle_codepade = "None"
718                         self.subtitle_filename_type = "None"
719                         self.is_subtitle_saved = "None"
720                         if self.localConvertion == False:
721                                 #download subtitle from server
722                                 if config.plugins.subsdownloader.subtitleserver.value in PERISCOPE_PLUGINS: #== "OpenSubtitle":
723                                         self.whichSubtitleDownload = self["subsList"].getCurrent()[1]
724                                         self.subtitle_filename = self.subtitles.createFile(self.subtitle_database[int(self.whichSubtitleDownload)],self.movie_filename)
725                                         #self["fileList"].refresh()
726                                         try:
727                                                 self.subtitle_codepade = self.getSubtitleCodepade(self.subtitle_filename)
728                                                 self.movie_fps = self.getMovieFPS(self.movie_filename)
729                                                 self.subtitle_filename_type = self.saveSubtitleasSRT(self.subtitle_filename, self.movie_fps, self.subtitle_codepade)
730                                         except:
731                                                 self.failed_to_download_subtitle_nfo(self.subtitle_filename,self.subtitle_codepade,self.subtitle_filename_type,self.movie_fps)
732                                         """if self.subtitle_filename == "None":
733                                                 self.failed_to_download_subtitle_nfo()
734                                         else:   
735                                                 self.subtitle_codepade = self.getSubtitleCodepade(self.subtitle_filename)
736                                                 self.movie_fps = self.getMovieFPS(self.movie_filename)
737                                                 self.saveSubtitleasSRT(self.subtitle_filename, self.movie_fps, self.subtitle_codepade)"""
738                                 if config.plugins.subsdownloader.subtitleserver.value == "NapiProjekt":
739                                         pass #PASS BECAUDE NAPI PROJECT DOWNLOAD ONLY PL FILE AND IT'S DIRECTLY IN DOWNLOAD SUBTITLE FUNCTION.
740                                 if config.plugins.subsdownloader.subtitleserver.value == "Napisy24":
741                                         self.whichSubtitleDownload = self["subsList"].getCurrent()[1]
742                                         if self.subtitles.save_downloaded_zip (self.whichSubtitleDownload)== True:
743                                                 extracted_file_path = self.subtitles.extract_zip_file()
744                                                 #Tutaj trzeba zrobic if dla configu dotyczacego autousuwania sciagfnietego pliku ZIP
745                                                 try:
746                                                         os.remove(self.subtitles.ZipFilePath) #remove downloaded zip file
747                                                 except:
748                                                         print "Can't delete file: %s" % self.subtitles.ZipFilePath
749                                                 if extracted_file_path != False:
750                                                         #auto konwerjsa sciagnietych z Napisy24 plikow
751                                                         if len(extracted_file_path) == 1:
752                                                                 
753                                                                 # ##### TO potem ubrac w jedna funkjce jak dorobie automatyczne wykrywanie ilosci sciagnietych plikow i  ilosci epizodow filmu
754                                                                 self.whichSubtitleDownload = extracted_file_path[0]
755                                                                 self.session.open(MessageBox, _("File path: \n %s") % (extracted_file_path[0]) , MessageBox.TYPE_INFO, timeout = 5)
756                                                                 self.subtitle_codepade = self.getSubtitleCodepade(self.whichSubtitleDownload)
757                                                                 self.movie_fps = self.getMovieFPS(self.movie_filename)                                                          
758                                                                 self.subtitle_filename = (str(self.movie_filename).rsplit(".", 1)[0])+".srt"
759                                                                 self.localConvertionFileConvert(True)
760                                                                 try:
761                                                                         os.remove(self.subtitles.ZipFilePath) #remove downloaded zip file
762                                                                 except:
763                                                                         print "Can't delete file: %s" % self.subtitles.ZipFilePath
764                                                                 # ##### TO potem ubrac w jedna funkjce jak dorobie automatyczne wykrywanie ilosci sciagnietych plikow i  ilosci epizodow filmu
765                                                                 
766                                                                 
767                                                         #elif jesli ilosc sciagnietych i rozpakowanyc plikow jest rowna ilosci plikow w katalogu i wtedy skasowac ELSA ponizej
768                                                         #elif jesli ilosc sciagnietych i rozpakowanyc plikow jest rowna ilosci plikow w katalogu i wtedy skasowac ELSA ponizej
769                                                         else:
770                                                                 self.session.open(MessageBox, _("%i file(s) was extracted: \n Please make local convertion (long TXEXT).\n\n Automatic option will be implemented ASAP.") % (len(extracted_file_path)) , MessageBox.TYPE_INFO, timeout = 5)
771                                                         
772                                         else:
773                                                 self.session.open(MessageBox, _("There is problem with downloading or saveing subtitles on storage device."), MessageBox.TYPE_INFO, timeout = 5)
774                                 self["fileList"].refresh()
775                         else:
776                                 #local convertion in progress
777                                 self.whichSubtitleDownload = self["subsList"].getCurrent()[1]
778                                 self.subtitle_filename = (str(self.movie_filename).rsplit(".", 1)[0])+".srt"
779                                 if os.path.isfile(self.subtitle_filename) == True:
780                                         self.session.openWithCallback(self.localConvertionFileConvert, MessageBox,(_("It seems that subtitle file: %s exists. \n Should I overwrite it and continue anyway?") % self.subtitle_filename), MessageBox.TYPE_YESNO, default = False)
781                                 else:
782                                         self.localConvertionFileConvert(True)
783                         #TODO OTHER SUBTITLE SERVERS HANDLE
784                                 
785         def closeApplication(self):
786                 os.system('rm -r /tmp/SubsDownloader_cache')
787                 print "\n[SubsDownloaderApplication] cancel\n"
788                 self.session.nav.playService(self.altservice)
789                 if config.plugins.subsdownloader.pathSave.value == True:
790                         config.plugins.subsdownloader.path.value = self["fileList"].getCurrentDirectory()
791                         config.plugins.subsdownloader.path.save()
792                 self.close(None)
793         
794         def goUp(self):
795                 self.set_title()
796                 self.selectedList.up()
797                 
798         def goDown(self):
799                 self.set_title()
800                 self.selectedList.down()
801         
802         def showAboutScreen(self):
803                 #self.session.open(SubsDownloaderAboutScreen) #nie wiem czy nie with callback
804                 self.session.open(vEditor, '/usr/lib/enigma2/python/Plugins/Extensions/SubsDownloader2/about.nfo')
805
806         def searchMusic(self):
807                 slist = []
808                 foundIndex = 0
809                 index = 0
810                 files = os_listdir(self["fileList"].getCurrentDirectory())
811                 files.sort()
812                 for name in files:
813                         testname = name.lower()
814                         if testname.endswith(".mp3") or name.endswith(".m4a") or name.endswith(".ogg") or name.endswith(".flac"):
815                                 slist.append((Item(text = name, filename = os_path.join(self["fileList"].getCurrentDirectory(),name)),))
816                                 if self["fileList"].getFilename() == name:
817                                         foundIndex = index
818                                 index = index + 1
819                 return slist,foundIndex         
820         
821 class SubsDownloaderConfig(ConfigListScreen, Screen):   
822         def __init__(self, session):
823                 self.skin = "<screen position=\"center,80\" size=\""+str(int(0.644*Skin_width))+","+str(int(0.644*Skin_height))+"\" title=\"Subtitle downloader: Configuration screen\" > \
824                 <widget name=\"config\" position=\"10,10\" size=\""+str(int(0.625*Skin_width))+","+str(int(0.385*Skin_height))+"\" scrollbarMode=\"showOnDemand\" /> \
825                 <widget name=\"extendLibMediaInfo\" position=\""+str(int(0.0434*Skin_width))+","+str(int(0.6095*Skin_height))+"\" size=\""+str(int(0.6076*Skin_width))+",26\" valign=\"center\" halign=\"left\" zPosition=\"2\"  foregroundColor=\"yellow\" font=\"Regular;20\"/> \
826                 </screen>"
827                 self.session = session
828                 Screen.__init__(self, session)
829                 self["extendLibMediaInfo"] = Label()
830                 if is_libmediainfo == False:
831                         self["extendLibMediaInfo"].setText("Press YELLOW button to install libmediainfo.")
832                 else:
833                         self["extendLibMediaInfo"].setText("")
834                 self.list = []
835                 ConfigListScreen.__init__(self, self.list, session)
836                 self["setupActions"] = ActionMap(["SetupActions","DirectionActions","WizardActions","SubsDownloaderConfig_actions"],
837                 {
838                         "left": self.keyLeft,
839                         "right": self.keyRight,
840                         "ok": self.saveConfig,
841                         "yellow": self.installLibMediaInfo,
842                         #"cancel": self.canceWithoutSaveMsg
843                         #"cancel": self.session.openWithCallback(self.cancelWithoutSave,MessageBox,_("Do you realy want to exit without configuration saving?"), MessageBox.TYPE_YESNO)
844                         "cancel": self.cancelWithoutSave # add the RC Command "cancel" to close your Screen
845                 }, -1)
846                 self.createConfigMenu()
847                 
848         def installLibMediaInfo(self):
849                 if is_libmediainfo == False:
850                         self.libmediaInfoInstallation = InstallDownloadableContent(self.session, [zlib_link,libmediainfo_link])
851                         self.libmediaInfoInstallation.__install__()
852
853         def keyLeft(self): #ABY DZIALALA AUTOMATYCZNA ZMIANA LIST WYSWIETLANEJ TA FUNKCJA MUSI SIE TAK NAZYWAC
854                 ConfigListScreen.keyLeft(self)
855                 self.createConfigMenu()
856         
857         def keyRight(self): #ABY DZIALALA AUTOMATYCZNA ZMIANA LIST WYSWIETLANEJ TA FUNKCJA MUSI SIE TAK NAZYWAC
858                 ConfigListScreen.keyRight(self)
859                 self.createConfigMenu()
860                 
861         def createConfigMenu(self):
862                 self.list = []
863                 self.list.append(getConfigListEntry(_("Choose subtitle server:"), config.plugins.subsdownloader.subtitleserver))
864                 if config.plugins.subsdownloader.subtitleserver.value in PERISCOPE_PLUGINS or config.plugins.subsdownloader.subtitleserver.value in XBMC_PLUGINS: #== "OpenSubtitle":
865                         #TODO LOGIN AND PASSWORD TO OPENSUBTITLE
866                         self.list.append(getConfigListEntry(_("1st subtitle language:"), config.plugins.subsdownloader.SubsDownloader1stLang))
867                         self.list.append(getConfigListEntry(_("2nd subtitle language:"), config.plugins.subsdownloader.SubsDownloader2ndLang))
868                         self.list.append(getConfigListEntry(_("3rd subtitle language:"), config.plugins.subsdownloader.SubsDownloader3rdLang))                  
869                 if config.plugins.subsdownloader.subtitleserver.value == "NapiProjekt":
870                         pass
871                 if config.plugins.subsdownloader.subtitleserver.value == "Napisy24":
872                         self.list.append(getConfigListEntry(_("Choose Napisy24 search method:"), config.plugins.subsdownloader.Napisy24SearchMethod))
873                         pass 
874                 self.list.append(getConfigListEntry(_("Extended configuratin menu:"), config.plugins.subsdownloader.extendedMenuConfig))
875                 if config.plugins.subsdownloader.extendedMenuConfig.value == True:
876                         self.list.append(getConfigListEntry(_("Save last FileList path:"), config.plugins.subsdownloader.pathSave))
877                         self.list.append(getConfigListEntry(_("Use media patern filter in FileList:"), config.plugins.subsdownloader.pathUseMediaPaternFilter))
878                         self.list.append(getConfigListEntry(_("Add Subs Downloader to BlueButton menu:"), config.plugins.subsdownloader.BlueButtonMenu))
879                         #self.list.append(getConfigListEntry(_("Delete oryginal subtitle after local convertion:"), config.plugins.subsdownloader.del_sub_after_conv))
880                         self.list.append(getConfigListEntry(_("Plugin autoupdate:"), config.plugins.subsdownloader.AutoUpdate))
881                 self["config"].list = self.list
882                 self["config"].setList(self.list)
883                 
884         """def canceWithoutSaveMsg(self):
885                 dei = self.session.openWithCallback(self.cancelWithoutSave(),MessageBox,_("Do you realy want to exit without configuration saving?"), MessageBox.TYPE_YESNO)
886                 dei.setTitle(_("Exit without saveing ..."))"""
887                 
888         def cancelWithoutSave(self):
889                 #TODO RETURN TO APPLICATION AND NOTIFICATRION ABOIUT NOT SAVEING
890                 for x in self["config"].list:
891                         x[1].cancel()
892                 self.close ()
893         
894         def saveConfig(self):
895                 for x in self["config"].list:
896                         x[1].save()
897                 self.close ()
898
899                 
900 #######################################################################
901 #
902 #    Dream-ExplorerII for Dreambox-Enigma2
903 #    Coded by Vali (c)2009-2011
904 #    Support: www.dreambox-tools.info
905 #
906 #    This program is free software; you can redistribute it and/or
907 #    modify it under the terms of the GNU General Public License
908 #    as published by the Free Software Foundation; either version 2
909 #    of the License, or (at your option) any later version.
910 #
911 #    This program is distributed in the hope that it will be useful,
912 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
913 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
914 #    GNU General Public License for more details.
915 #
916 #######################################################################
917                         
918 class vEditor(Screen):
919         def __init__(self, session, file):
920                 self.skin = '<screen position="center,center" size="'+str(int(0.9*Screen_width))+','+str(int(0.9*Screen_height))+'" title="File-Explorer"> \
921                 <widget name="filedata" position="5,7" size="'+str(int(0.85*Screen_width))+','+str(int(0.85*Screen_height))+'" itemHeight="25"/> \
922                 </screen>'
923                 Screen.__init__(self, session)
924                 self.session = session
925                 self.file_name = file
926                 self.list = []
927                 self["filedata"] = MenuList(self.list)
928                 self["actions"] = ActionMap(["WizardActions"],
929                 {
930                         "ok": self.editLine,
931                         "back": self.exitEditor
932                 }, -1)
933                 self.selLine = None
934                 self.oldLine = None
935                 self.isChanged = False
936                 self.GetFileData(file)
937
938         def exitEditor(self):
939                 if self.isChanged:
940                         warningtext = "\nhave been CHANGED! Do you want to save it?\n\nWARNING!"
941                         warningtext = warningtext + "\n\nThe Editor-Funktions are beta (not full tested) !!!"
942                         warningtext = warningtext + "\nThe author are NOT RESPONSIBLE\nfor DATA LOST OR DISORDERS !!!"
943                         dei = self.session.openWithCallback(self.SaveFile, MessageBox,_(self.file_name+warningtext), MessageBox.TYPE_YESNO)
944                         dei.setTitle(_("Dream-Explorer..."))
945                 else:
946                         self.close()
947
948         def GetFileData(self, fx):
949                 try:
950                         flines = open(fx, "r")
951                         for line in flines:
952                                 self.list.append(line)
953                         flines.close()
954                         self.setTitle(fx)
955                 except:
956                         pass
957
958         def editLine(self):
959                 try:
960                         self.selLine = self["filedata"].getSelectionIndex()
961                         self.oldLine = self.list[self.selLine]
962                         editableText = self.list[self.selLine][:-1]
963                         self.session.openWithCallback(self.callbackEditLine, vInputBox, title=_("old:  "+self.list[self.selLine]), windowTitle=_("Edit line "+str(self.selLine+1)), text=editableText)
964                 except:
965                         dei = self.session.open(MessageBox, _("This line is not editable!"), MessageBox.TYPE_ERROR)
966                         dei.setTitle(_("Error..."))
967
968         def callbackEditLine(self, newline):
969                 if newline is not None:
970                         for x in self.list:
971                                 if x == self.oldLine:
972                                         self.isChanged = True
973                                         self.list.remove(x)
974                                         self.list.insert(self.selLine, newline+'\n')
975                 self.selLine = None
976                 self.oldLine = None
977
978         def SaveFile(self, answer):
979                 if answer is True:
980                         try:
981                                 eFile = open(self.file_name, "w")
982                                 for x in self.list:
983                                         eFile.writelines(x)
984                                 eFile.close()
985                         except:
986                                 pass
987                         self.close()
988                 else:
989                         self.close()
990
991 class MviExplorer(Screen):
992         skin = """
993                 <screen position="-300,-300" size="10,10" title="mvi-Explorer">
994                 </screen>"""
995         def __init__(self, session, file):
996                 self.skin = MviExplorer.skin
997                 Screen.__init__(self, session)
998                 self.file_name = file
999                 self["actions"] = ActionMap(["WizardActions"],
1000                 {
1001                         "ok": self.close,
1002                         "back": self.close
1003                 }, -1)
1004                 self.onLayoutFinish.append(self.showMvi)
1005         def showMvi(self):
1006                 os_system("/usr/bin/showiframe " + self.file_name)
1007
1008
1009
1010 class PictureExplorerII(Screen):
1011         def __init__(self, session, whatPic = None, whatDir = None):
1012                 self.skin = '<screen flags="wfNoBorder" position="0,0" size="'+str(Screen_width)+','+str(Screen_height)+'" title="Picture-Explorer" backgroundColor="#00121214"> \
1013                 <widget name="Picture" position="0,0" size="'+str(Screen_width)+','+str(Screen_height)+'" zPosition="1" alphatest="on" /> \
1014                 <widget name="State" font="Regular;20" halign="center" position="0,'+str(int(0.904*720))+'" size="'+str(Screen_width)+',70" backgroundColor="#01080911" foregroundColor="#fcc000" transparent="0" zPosition="9"/> \
1015                 </screen>'
1016                 Screen.__init__(self, session)
1017                 self.session = session
1018                 self.whatPic = whatPic
1019                 self.whatDir = whatDir
1020                 self.picList = []
1021                 self.Pindex = 0
1022                 self.EXscale = (AVSwitch().getFramebufferScale())
1023                 self.EXpicload = ePicLoad()
1024                 self["Picture"] = Pixmap()
1025                 self["State"] = Label(_('loading... '+self.whatPic))
1026                 self["actions"] = ActionMap(["WizardActions", "DirectionActions"],
1027                 {
1028                         "ok": self.info,
1029                         "back": self.close,
1030                         "up": self.info,
1031                         "down": self.close,
1032                         "left": self.Pleft,
1033                         "right": self.Pright
1034                 }, -1)
1035                 self.EXpicload.PictureData.get().append(self.DecodeAction)
1036                 self.onLayoutFinish.append(self.Show_Picture)
1037
1038         def Show_Picture(self):
1039                 if self.whatPic is not None:
1040                         self.EXpicload.setPara([self["Picture"].instance.size().width(), self["Picture"].instance.size().height(), self.EXscale[0], self.EXscale[1], 0, 1, "#002C2C39"])
1041                         self.EXpicload.startDecode(self.whatPic)
1042                 if self.whatDir is not None:
1043                         pidx = 0
1044                         for root, dirs, files in os_walk(self.whatDir ):
1045                                 for name in files:
1046                                         if name.endswith(".jpg") or name.endswith(".jpeg") or name.endswith(".Jpg") or name.endswith(".Jpeg") or name.endswith(".JPG") or name.endswith(".JPEG"):
1047                                                 self.picList.append(name)
1048                                                 if name in self.whatPic:
1049                                                         self.Pindex = pidx
1050                                                 pidx = pidx + 1
1051                         files.sort()
1052
1053         def DecodeAction(self, pictureInfo=""):
1054                 if self.whatPic is not None:
1055                         self["State"].setText(_("ready..."))
1056                         self["State"].visible = False
1057                         ptr = self.EXpicload.getData()
1058                         self["Picture"].instance.setPixmap(ptr)
1059
1060         def Pright(self):
1061                 if len(self.picList)>2:
1062                         if self.Pindex<(len(self.picList)-1):
1063                                 self.Pindex = self.Pindex + 1
1064                                 self.whatPic = self.whatDir + str(self.picList[self.Pindex])
1065                                 self["State"].visible = True
1066                                 self["State"].setText(_('loading... '+self.whatPic))
1067                                 self.EXpicload.startDecode(self.whatPic)
1068                         else:
1069                                 self["State"].setText(_("wait..."))
1070                                 self["State"].visible = False
1071                                 self.session.open(MessageBox,_('No more picture-files.'), MessageBox.TYPE_INFO)
1072
1073         def Pleft(self):
1074                 if len(self.picList)>2:
1075                         if self.Pindex>0:
1076                                 self.Pindex = self.Pindex - 1
1077                                 self.whatPic = self.whatDir + str(self.picList[self.Pindex])
1078                                 self["State"].visible = True
1079                                 self["State"].setText(_('loading... '+self.whatPic))
1080                                 self.EXpicload.startDecode(self.whatPic)
1081                         else:
1082                                 self["State"].setText(_("wait..."))
1083                                 self["State"].visible = False
1084                                 self.session.open(MessageBox,_('No more picture-files.'), MessageBox.TYPE_INFO)
1085
1086         def info(self):
1087                 if self["State"].visible:
1088                         self["State"].setText(_("wait..."))
1089                         self["State"].visible = False
1090                 else:
1091                         self["State"].visible = True
1092                         self["State"].setText(_(self.whatPic))
1093
1094
1095
1096 class MoviePlayer(MP_parent):
1097         def __init__(self, session, service):
1098                 self.session = session
1099                 self.WithoutStopClose = False
1100                 MP_parent.__init__(self, self.session, service)
1101                                 
1102         def leavePlayer(self):
1103                 self.is_closing = True
1104                 self.close()
1105
1106         def leavePlayerConfirmed(self, answer):
1107                 pass
1108
1109         def doEofInternal(self, playing):
1110                 if not self.execing:
1111                         return
1112                 if not playing :
1113                         return
1114                 self.leavePlayer()
1115
1116         def showMovies(self):
1117                 self.WithoutStopClose = True
1118                 self.close()
1119
1120         def movieSelected(self, service):
1121                 self.leavePlayer(self.de_instance)
1122
1123         def __onClose(self):
1124                 if not(self.WithoutStopClose):
1125                         self.session.nav.playService(self.lastservice)
1126
1127
1128
1129 class MusicExplorer(MoviePlayer):
1130         def __init__(self, session, service, MusicDir, theFile):
1131                 self.skin = '<screen backgroundColor="#50070810" flags="wfNoBorder" name="MusicExplorer" position="center,center" size="720,30"> \
1132                 <widget font="Regular;24" halign="right" position="50,0" render="Label" size="100,30" source="session.CurrentService" transparent="1" valign="center" zPosition="1"> \
1133                 <convert type="ServicePosition">Remaining</convert> \
1134                 </widget> \
1135                 <widget font="Regular;24" position="170,0" render="Label" size="650,30" source="session.CurrentService" transparent="1" valign="center" zPosition="1"> \
1136                 <convert type="ServiceName">Name</convert> \
1137                 </widget> \
1138                 </screen>'
1139                 self.session = session
1140                 MoviePlayer.__init__(self, session, service)
1141                 self.MusicDir = MusicDir
1142                 self.musicList = []
1143                 self.Mindex = 0
1144                 self.curFile = theFile
1145                 self.searchMusic()
1146                 self.onLayoutFinish.append(self.showMMI)
1147                 MoviePlayer.WithoutStopClose = False
1148
1149         def showMMI(self):
1150                 try:
1151                         os_system("/usr/bin/showiframe /usr/lib/enigma2/python/Plugins/Extensions/DreamExplorer/res/music.mvi")
1152                         #TODO DAC wlasna
1153                 except:
1154                         pass #TU DOROBIC WLASNA TAPETE
1155                         
1156         def searchMusic(self):
1157                 midx = 0
1158                 for root, dirs, files in os_walk(self.MusicDir ):
1159                         for name in files:
1160                                 name = name.lower()
1161                                 if name.endswith(".mp3") or name.endswith(".mp2") or name.endswith(".ogg") or name.endswith(".wav") or name.endswith(".flac") or name.endswith(".m4a"):
1162                                         self.musicList.append(name)
1163                                         if self.curFile in name:
1164                                                 self.Mindex = midx
1165                                         midx = midx + 1
1166
1167         def seekFwd(self):
1168                 if len(self.musicList)>2:
1169                         if self.Mindex<(len(self.musicList)-1):
1170                                 self.Mindex = self.Mindex + 1
1171                                 nextfile = self.MusicDir + str(self.musicList[self.Mindex])
1172                                 nextRef = eServiceReference("4097:0:0:0:0:0:0:0:0:0:" + nextfile)
1173                                 self.session.nav.playService(nextRef)
1174                         else:
1175                                 self.session.open(MessageBox,_('No more playable files.'), MessageBox.TYPE_INFO)
1176
1177         def seekBack(self):
1178                 if len(self.musicList)>2:
1179                         if self.Mindex>0:
1180                                 self.Mindex = self.Mindex - 1
1181                                 nextfile = self.MusicDir + str(self.musicList[self.Mindex])
1182                                 nextRef = eServiceReference("4097:0:0:0:0:0:0:0:0:0:" + nextfile)
1183                                 self.session.nav.playService(nextRef)
1184                         else:
1185                                 self.session.open(MessageBox,_('No more playable files.'), MessageBox.TYPE_INFO)
1186
1187         def doEofInternal(self, playing):
1188                 if not self.execing:
1189                         return
1190                 if not playing :
1191                         return
1192                 self.seekFwd()
1193
1194 ###########################################################################
1195
1196 def main(session, **kwargs):
1197         print "\n[SubsDownloaderApplication] start\n"   
1198         if config.plugins.subsdownloader.AutoUpdate.value == True:
1199                 session.open(SubsDownloaderApplication)
1200                 autoupdate = IsNewVersionCheck()
1201                 if autoupdate.run() != False:
1202                         session.open(PluginIpkUpdate)           
1203         else:
1204                 session.open(SubsDownloaderApplication)
1205
1206
1207         
1208         
1209 #########################################################################
1210
1211
1212 def Plugins(**kwargs):
1213         desc_plugin_menu = PluginDescriptor(name="SubsDownloader",description="Download subtitle to any movie",where = PluginDescriptor.WHERE_PLUGINMENU,icon="subsdownloader.png",fnc=main)
1214         desc_menu_Blue_button_menu = PluginDescriptor(name="SubsDownloader",description="Download subtitle to any movie",where = PluginDescriptor.WHERE_EXTENSIONSMENU,fnc=main)
1215         list = []
1216         list.append(desc_plugin_menu)
1217         if config.plugins.subsdownloader.BlueButtonMenu.value == True:
1218                 list.append(desc_menu_Blue_button_menu)
1219         return list