Enigma2 plugin to to play various online streams (mostly Latvian).

PlayStream.py 48KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  1. #!/usr/bin/env python
  2. # coding=utf8
  3. # This file is part of PlayStream - enigma2 plugin to play video streams from various sources
  4. # Copyright (c) 2016 ivars777 (ivars777@gmail.com)
  5. # Distributed under the GNU GPL v3. For full terms see http://www.gnu.org/licenses/gpl-3.0.en.html
  6. # Used fragments of code from enigma2-plugin-tv3play by Taapat (https://github.com/Taapat/enigma2-plugin-tv3play)
  7. #
  8. __version__ = "0.6l"
  9. __id__ = "playstream"
  10. __title__ = "PlayStream"
  11. __author__ = "ivars777@gmail.com"
  12. __desc__ = "Play online video streams from various sources"
  13. import os,time,sys,os,os.path
  14. import datetime,re
  15. import urllib2
  16. from Plugins.Plugin import PluginDescriptor
  17. from enigma import ePicLoad, eServiceReference, eTimer, getDesktop
  18. from Screens.Screen import Screen
  19. from Screens.InfoBarGenerics import InfoBarShowHide
  20. from Screens.InfoBar import MoviePlayer
  21. from Screens.MessageBox import MessageBox
  22. from Screens.LocationBox import LocationBox
  23. from Screens.ChoiceBox import ChoiceBox
  24. from Screens.VirtualKeyBoard import VirtualKeyBoard
  25. from Screens.Console import Console
  26. from Screens.Standby import TryQuitMainloop
  27. #from Screens.InputBox import InputBox
  28. from Components.AVSwitch import AVSwitch
  29. from Components.ActionMap import ActionMap, HelpableActionMap
  30. from Components.Label import Label
  31. from Components.ScrollLabel import ScrollLabel
  32. from Components.Input import Input
  33. from Components.MenuList import MenuList
  34. from Components.Pixmap import Pixmap
  35. from Components.Sources.List import List
  36. from Components.Sources.StaticText import StaticText
  37. from Components.Button import Button
  38. from Components.Task import job_manager
  39. from Components.config import config, ConfigSubsection, ConfigText, ConfigInteger, ConfigLocations, ConfigDirectory, ConfigSet, ConfigYesNo, ConfigSelection, getConfigListEntry, ConfigSelectionNumber, ConfigNumber
  40. from Components.config import config, ConfigSubsection, ConfigYesNo, getConfigListEntry, ConfigSelection, ConfigNumber, ConfigDirectory,ConfigText, ConfigSubDict
  41. from Components.ConfigList import ConfigListScreen
  42. #from Screens.LocationBox import LocationBox
  43. from Tools import Notifications
  44. from Tools.BoundFunction import boundFunction
  45. from Tools.Directories import resolveFilename, SCOPE_PLUGINS
  46. from Tools.LoadPixmap import LoadPixmap
  47. from skin import loadSkin
  48. from twisted.web.client import downloadPage,defer,reactor
  49. from plugin_locale import _
  50. import ContentSources
  51. import util
  52. from VideoDownload import downloadJob, HLSDownloadJob,VideoDownloadList
  53. #import enigma2_api
  54. e2 = None
  55. cur_directory = os.path.dirname(os.path.realpath(__file__))
  56. loadSkin(os.path.join(cur_directory, "skin.xml"))
  57. #####################################################################################################################
  58. config.plugins.playstream = ConfigSubsection()
  59. config.plugins.playstream.locations = ConfigLocations(default=["/media/hdd/movie/"])
  60. config.plugins.playstream.download_dir = ConfigDirectory(default="/media/hdd/movie/")
  61. config.plugins.playstream.tmp_dir = ConfigDirectory(default="/tmp/playstream/")
  62. config.plugins.playstream.streamproxy_start = ConfigYesNo(default = True)
  63. config.plugins.playstream.overwrite_download = ConfigYesNo(default = False)
  64. #config.plugins.playstream.size = ConfigSelection({"400x240":"400x240","220x132":"220x132","100x60":"100x60"}, default="220x132")
  65. config.plugins.playstream.clear_tmp = ConfigYesNo(default = True)
  66. config.plugins.playstream.check_update = ConfigYesNo(default = True)
  67. #####################################################################################################################
  68. class MainScreen(Screen):
  69. def __init__(self, session):
  70. Screen.__init__(self, session)
  71. self.skinName = ["PSMain"]
  72. self.session = session
  73. self.e2 = None
  74. self["key_red"] = Button(_("Exit"))
  75. self["key_green"] = Button(_("Select"))
  76. self["key_yellow"] = Button(_("Options"))
  77. self["key_blue"] = Button(_("Config"))
  78. self["key_menu"] = Button("Menu")
  79. self["key_exit"] = Button("Back")
  80. self["actions"] = ActionMap(["OkCancelActions", "ColorActions","MenuActions", "NumberActions",
  81. "WizardActions","ButtonSetupActions"], {
  82. #"cancel": self.Cancel,
  83. "ok": self.ok,
  84. "green": self.ok,
  85. "red": self.cancel,
  86. "yellow": self.options_screen,
  87. "blue": self.config_screen,
  88. "menu": self.item_menu,
  89. "cancel": self.back,
  90. "info": self.show_info,
  91. "pageup": self.page_up,
  92. "channelup":self.page_up,
  93. "pagedown": self.page_down,
  94. "channeldown":self.page_down,
  95. })
  96. self["list"] = List([])
  97. self["list"].onSelectionChanged.append(self.selection_changed)
  98. self["pic"] = Pixmap()
  99. self["cur"] = ScrollLabel()
  100. self["title"] = Label()
  101. self.downloading = 0
  102. self.active_downloads = 0
  103. if not os.path.exists(config.plugins.playstream.tmp_dir.value):
  104. os.mkdir(config.plugins.playstream.tmp_dir.value)
  105. self.onLayoutFinish.append(self.layout_finished)
  106. def layout_finished(self):
  107. self.defimage = LoadPixmap(os.path.join(cur_directory,"PlayStream.png"))
  108. #self.defimage = None
  109. #sc = AVSwitch().getFramebufferScale()
  110. #self.defimage0 = ePicLoad()
  111. #self.defimage0.PictureData.get().append(boundFunction(self.FinishDecodeDef, os.path.join(cur_directory,"PlayStream.png")))
  112. #self.defimage0.setPara((self["pic"].instance.size().width(),self["pic"].instance.size().height(),sc[0], sc[1], False, 0, "#00000000"))
  113. #self.defimage0.startDecode("default")
  114. self.active_downloads = 0
  115. self.images = {}
  116. self.images_url = {}
  117. self.picloads = {}
  118. self.history = []
  119. reload(ContentSources)
  120. self.sources = ContentSources.ContentSources(os.path.join(cur_directory,"sources"))
  121. self.config = self.sources.plugins["config"]
  122. self.cur_menu = ("Home","config::home","","Sākums") #
  123. self.content = self.sources.get_content(self.cur_menu[1])
  124. #print self.content
  125. self["list"].setList(self.content)
  126. self["cur"].setText(self.content[0][3])
  127. self.setTitle2(self.cur_menu[0])
  128. self.show_picture(self.content[0][2])
  129. reactor.callLater(1,self.check_update)
  130. def check_update(self):
  131. #print "Check PlayStream for update"
  132. if config.plugins.playstream.check_update:
  133. self.cver = util.check_version("enigma2-plugin-extensions-playstream")
  134. if self.cver and self.cver>__version__:
  135. txt = "New version of plugin available for update - %s\nCurrent version - %s\nDo you want to upgrade?"%(self.cver,__version__)
  136. mbox = self.session.openWithCallback(self.update, MessageBox, txt, MessageBox.TYPE_YESNO)
  137. mbox.setTitle("Upgrade plugin?")
  138. def update(self,answer):
  139. if answer:
  140. plugin_update(self.session)
  141. def page_down(self):
  142. self["cur"].pageDown()
  143. def page_up(self):
  144. self["cur"].pageUp()
  145. def selection_changed(self):
  146. current = self["list"].getCurrent()
  147. print "[PlayStream] SelectionChanged: current=",current
  148. if not current: return
  149. self["cur"].setText(current[3]) if current[3] else self["cur"].setText("")
  150. if current[2]:
  151. self.show_picture(current[2])
  152. else:
  153. self.show_default_picture()
  154. def setTitle2(self,title):
  155. #print self.keys()
  156. self["title"].setText(title)
  157. def show_default_picture(self):
  158. if self.defimage:
  159. self["pic"].instance.setPixmap(self.defimage)
  160. def show_picture(self, image_url):
  161. if image_url == "default":
  162. self.show_default_picture()
  163. return
  164. elif self.images.has_key(image_url):
  165. if self.images[image_url] in (-1,-2):
  166. return
  167. elif self.images[image_url] == -3:
  168. self.show_default_picture()
  169. return
  170. else:
  171. self["pic"].instance.setPixmap(self.images[image_url])
  172. else:
  173. if image_url.startswith("http"):
  174. fname = image_url.replace(":","-").replace("/","_")
  175. image_path = os.path.join(config.plugins.playstream.tmp_dir.value, fname)
  176. self.download_image(image_path, image_url)
  177. else: # local file
  178. image_path = os.path.join(cur_directory,image_url)
  179. self.start_decode(image_path,image_url)
  180. def start_decode(self,image_path,image_url):
  181. self.images[image_url] = -2
  182. self.images_url[image_path] = image_url
  183. sc = AVSwitch().getFramebufferScale()
  184. if not self.picloads.has_key(image_path):
  185. self.picloads[image_path] = ePicLoad()
  186. self.picloads[image_path].PictureData.get().append(boundFunction(self.decode_finished, image_path))
  187. self.picloads[image_path].setPara((self["pic"].instance.size().width(),
  188. self["pic"].instance.size().height(),
  189. sc[0], sc[1], True, 0, "#00000000"))
  190. #print image_path,image_url
  191. self.picloads[image_path].startDecode(image_path)
  192. def decode_finished(self, image_path, picInfo = None):
  193. image_url = self.images_url[image_path]
  194. del self.images_url[image_path] #III
  195. self.images[image_url] = self.picloads[image_path].getData()
  196. self["pic"].instance.setPixmap(self.images[image_url])
  197. del self.picloads[image_path]
  198. if len(self.images)>30:
  199. del self.images[self.images.keys()[0]]
  200. # self.images.pop()
  201. #def FinishDecodeDef(self, image_path,picInfo = None):
  202. # self.defimage = self.defimage0.getData()
  203. # del self.defimage0
  204. # self["pic"].instance.setPixmap(self.defimage)
  205. def download_image(self,image_path,image_url):
  206. #print "Image download started",self.downloading,image_path,image_url
  207. self.downloading += 1
  208. self.images[image_url] = -1
  209. downloadPage(image_url, image_path).addCallback(boundFunction(self.download_image_finished, image_path, image_url)).addErrback(boundFunction(self.download_image_failed, image_path, image_url))
  210. def download_image_finished(self, image_path, image_url, result):
  211. self.downloading -= 1
  212. #print "[ Play] Image downloaded finished ",self.downloading,image_path, image_url,result
  213. self.start_decode(image_path,image_url)
  214. def download_image_failed(self, image_path, image_url, result):
  215. self.downloading -= 1
  216. print "[TV Play] Image downloaded failed ",self.downloading,image_path, image_url,result
  217. self.images[image_url] = -3
  218. def ok(self):
  219. current = self["list"].getCurrent()
  220. self.current = current
  221. index = self["list"].getIndex()
  222. self.index = index
  223. print "[PlayStream] - menu selected ", current
  224. data = current[1].split("::")[1] if "::" in current[1] else current[1]
  225. if not data:
  226. return
  227. elif self.sources.is_video(current[1]):
  228. if self.sources.stream_type(current[1]):
  229. stream = util.item()
  230. stream["url"] = current[1]
  231. stream["name"] = current[0]
  232. streams = [stream]
  233. else:
  234. try:
  235. streams = self.sources.get_streams(current[1])
  236. except Exception,e:
  237. print str(e)
  238. self.session. open(MessageBox, "Error - %s"%str(e) , MessageBox.TYPE_INFO)
  239. return
  240. if streams:
  241. #print streams
  242. for s in streams:
  243. if not s["name"]: s["name"] = current[0]
  244. if not s["img"]: s["img"] = current[2]
  245. if not s["desc"]: s["desc"] = current[3]
  246. try:
  247. self.session.open(PSPlayer, streams)
  248. except Exception as e:
  249. self.msg("Error launching player - " + str(e))
  250. return
  251. else:
  252. self.msg("No stream found - %s"%(self.current[1]))
  253. return
  254. elif current[1] == "back":
  255. cur_menu_old = self.cur_menu
  256. self.cur_menu = self.history.pop()
  257. new_content = self.sources.get_content(self.cur_menu[1])
  258. try:
  259. index = zip(*new_content)[1].index(cur_menu_old[1])
  260. except:
  261. index = 0
  262. self.setTitle2(self.cur_menu[0])
  263. self.show_content(new_content,index)
  264. else:
  265. print "selected=",current
  266. if "{0}" in current[1]:
  267. self.session.openWithCallback(self.cb_input,VirtualKeyBoard, title="Enter value", text="")
  268. #a = raw_input("Enter value:")
  269. #a = "big bang"
  270. #current = (current[0],current[1].format(a),current[2],current[3])
  271. #self.get_content(current)
  272. else:
  273. self.get_content(current)
  274. def show_info(self):
  275. self.current = self["list"].getCurrent()
  276. data = self.current[1]
  277. source = data.split("::")[0]
  278. if self.sources.is_video(data) and "get_info" in dir(self.sources.plugins[source]):
  279. self.sources.plugins
  280. try:
  281. nfo = self.sources.get_info(self.current[1])
  282. except Exception, e:
  283. print str(e)
  284. self.session.open(MessageBox, "Error - %s" % str(e), MessageBox.TYPE_INFO)
  285. return
  286. else:
  287. nfo = {"movie": {"title": self.current[0], "thumb": self.current[2], "plot": self.current[3]}}
  288. self.session.open(StreamInfo, nfo)
  289. def cb_input(self,value):
  290. if not value:
  291. return
  292. current = self.current
  293. current = (current[0],current[1].format(value),current[2],current[3])
  294. self.get_content(current)
  295. def get_content(self,current):
  296. self.history.append(self.cur_menu)
  297. self.cur_menu = current
  298. try:
  299. new_content = self.sources.get_content(self.cur_menu[1])
  300. except Exception,e:
  301. self.cur_menu = self.history.pop()
  302. self.session. open(MessageBox, "Error - %s"%str(e) , MessageBox.TYPE_INFO)
  303. return
  304. self.setTitle2(self.cur_menu[0])
  305. self.show_content(new_content)
  306. def back(self):
  307. self["list"].setIndex(0)
  308. self.ok()
  309. def show_content(self,content,index=0):
  310. self["list"].setList(content)
  311. self["list"].setIndex(index)
  312. self.selection_changed()
  313. def cancel(self):
  314. print "Exiting PlayStream"
  315. if config.plugins.playstream.clear_tmp.value and os.path.exists(config.plugins.playstream.tmp_dir.value):
  316. for name in os.listdir(config.plugins.playstream.tmp_dir.value):
  317. #print "remove "+os.path.join(config.plugins.playstream.tmp_dir.value, name)
  318. os.remove(os.path.join(config.plugins.playstream.tmp_dir.value, name))
  319. #os.rmdir(config.plugins.playstream.tmp_dir.value)
  320. self.close()
  321. def item_menu(self):
  322. print "\n[PlayStream] options\n"
  323. self.current = self["list"].getCurrent()
  324. self.index = self["list"].getIndex()
  325. #self.session. open(MessageBox, "Item options - %s"%current[0] , MessageBox.TYPE_INFO)
  326. #args=[current,self.cur_menu]
  327. #self.session.open(ItemMenuScreen,current,index,self)
  328. lst = [
  329. ("Aditional information","info","Display additional information about item"),
  330. ("Add to bouquet","bouquet","Add current item to Enigma2 bouquet"),
  331. ("Add to favorites","favorites","Add current item to PlayStrem favorites"),
  332. ("Show active downloads","download_list","Show active downloads list"),
  333. ("Set download folder","download_folder","Set download folder")
  334. ]
  335. if self.sources.is_video(self.current[1]):
  336. lst.extend([
  337. ("Download video to default folder","download","Download video to default folder"),
  338. ("Download video, ask folder","download2","Download video, ask download folder"),
  339. ("Download video to subfolder, ask parent folder","download3","Download video to subfolder, ask download folder"),
  340. ])
  341. else:
  342. lst.extend([
  343. ("Download list to default folder","download","Download videos in list (if any)"),
  344. ("Download list, ask folder","download2","Download videos in list (if any), ask download folder"),
  345. ])
  346. if "config::" in self.cur_menu[1]:
  347. lst.extend([
  348. ("Rename item","rename","Rename list item"),
  349. ("Move item","move","Move list item"),
  350. ("Delete item","delete","Delete list item"),
  351. ("Add submenu","add_list","Add submenu before selected item"),
  352. ])
  353. title = self.current[0]
  354. self.session.openWithCallback(self.cb_item_menu, ChoiceBox, title = title, list = lst) #TODO
  355. def cb_item_menu(self,answer):
  356. #print "item_menu_selected",answer
  357. if not answer:
  358. return
  359. self.answer = answer[1]
  360. if answer[1] == "info":
  361. #self.show_nfo()
  362. #self.session.open(MessageBox, "Not yet implemented!", MessageBox.TYPE_INFO)
  363. self.show_info()
  364. elif answer[1] == "bouquet":
  365. #if not e2:
  366. #e2 = enigma2_api.DBServices()
  367. #print "load_buuquets - ",e2._load_bouquets()
  368. self.session.open(MessageBox, "Not yet implemented!", MessageBox.TYPE_INFO)
  369. elif answer[1] == "favorites":
  370. lists = self.config.get_lists()
  371. lists2 = [(self.config.get_title(l),l) for l in lists]
  372. print lists2
  373. self.session.openWithCallback(self.cb_favorites, ChoiceBox, title="Selected menu item will be added",list = lists2)
  374. elif answer[1] in ("download2","download3"): # ask download folder before
  375. self.session.openWithCallback(self.download_prepare, LocationBox,"Select download folder","",config.plugins.playstream.download_dir.value,config.plugins.playstream.locations,False,"Select folder",None,True,True)
  376. elif answer[1] == 'download':
  377. self.download_prepare(config.plugins.playstream.download_dir.value)
  378. elif answer[1] == 'download_list':
  379. self.download_list()
  380. elif answer[1] == 'download_folder':
  381. #downloadDir = "/media/hdd/movie" #config.plugins.playstream.downloadDir.value TODO
  382. self.session.openWithCallback(self.cb_download_dir, LocationBox,"Select download folder","",config.plugins.playstream.download_dir.value,config.plugins.playstream.locations,False,"Select folder",None,True,True)
  383. elif answer[1] == "delete":
  384. lst = self.cur_menu[1].replace("config::","")
  385. #print lst
  386. self.config.del_item(lst,self.index)
  387. self.config.write_streams()
  388. txt = "'%s' deleted from favourite stream list '%s'"%(self.current[0],lst)
  389. self.session.open(MessageBox, txt, MessageBox.TYPE_INFO,timeout=5)
  390. elif answer[1] == "rename":
  391. #name2 = "Renamed"
  392. self.session.openWithCallback(self.cb_rename,VirtualKeyBoard, title="Enter new item name", text=self.current[0])
  393. elif answer[1] == "add_list":
  394. self.session.open(MessageBox, "Not yet implemented!", MessageBox.TYPE_INFO,timeout=5)
  395. pass #TODO
  396. return
  397. def download_prepare(self, download_dir=""):
  398. current = self.current
  399. if not download_dir:
  400. return
  401. #download_dir = config.plugins.playstream.download_dir.value
  402. title = re.sub("\[.+?\]","", util.make_fname(current[0])).strip()
  403. download_dir2 = os.path.join(download_dir, title)
  404. if not self.sources.is_video(current[1]):
  405. #self.msg("Can not download listst (yet) - %s"%(current[1]))
  406. n = 0
  407. for current2 in self.sources.get_content(current[1]):
  408. if self.sources.is_video(current2[1]):
  409. n += 1
  410. self.download_video(current2,download_dir2)
  411. if n>0:
  412. self.msg("%s videos download started to %s"%(n,download_dir2))
  413. else:
  414. self.msg("No videos to download")
  415. else:
  416. if self.answer == "download":
  417. download_dir2 = download_dir
  418. if self.download_video(current,download_dir2):
  419. self.msg("Video download started to %s"%download_dir2)
  420. def cb_download_dir(self, downloadDir, select=None):
  421. if not downloadDir:
  422. return
  423. print "Folder selected - %s"%downloadDir
  424. config.plugins.playstream.download_dir.setValue(downloadDir)
  425. config.plugins.playstream.download_dir.save()
  426. config.plugins.playstream.locations.save()
  427. config.save()
  428. def download_list(self):
  429. self.session.open(VideoDownloadList)
  430. def download_video(self,current, download_dir=""):
  431. if self.sources.stream_type(current[1]):
  432. stream = util.item()
  433. stream["url"] = current[1]
  434. stream["name"] = current[0]
  435. streams = [stream]
  436. else:
  437. try:
  438. streams = self.sources.get_streams(current[1])
  439. except Exception,e:
  440. print "Error - %s"%str(e)
  441. self.session. open(MessageBox, "Error - %s"%str(e) , MessageBox.TYPE_INFO)
  442. return
  443. if not streams:
  444. self.msg("No stream found to download - %s"%(self.current[1]))
  445. return
  446. for s in streams:
  447. if not s["name"]: s["name"] = current[0]
  448. if not s["img"]: s["img"] = current[2]
  449. if not s["desc"]: s["desc"] = current[3]
  450. if len(streams)>1:
  451. stream = streams[0] # TODO iespeja izvelēties strīmu, ja to ir vairāki
  452. else:
  453. stream = streams[0]
  454. stream = util.stream_change(stream)
  455. return self.download_stream(stream, download_dir)
  456. def download_stream(self,stream,download_dir=""):
  457. print "download stream",stream
  458. #self.msg("Start downloading..")
  459. self.stream = stream
  460. stream_type = self.stream["type"] #self.sources.stream_type(stream["url"])
  461. if not stream_type: #
  462. print "Not supported stream type found to download - %s"%(self.current[1])
  463. self.msg("Not supported stream type found to download - %s"%(self.current[1]))
  464. return
  465. title = self.stream["name"].strip()
  466. url = self.stream["url"]
  467. stream_type = self.stream["type"] #self.sources.stream_type(stream["url"])
  468. downloadDir = config.plugins.playstream.download_dir.value if not download_dir else download_dir
  469. if not os.path.exists(downloadDir):
  470. try:
  471. os.mkdir(downloadDir)
  472. except Exception as e:
  473. print 'Error creating download directory "%s"!\nPlease specify in the settings existing directory\n%s'%(downloadDir,str(e))
  474. self.msg('Error creating download directory "%s"!\nPlease specify in the settings existing directory\n%s'%(downloadDir,str(e)))
  475. return
  476. fname0 = util.make_fname(title)
  477. fname = fname0 +".mp4"
  478. outputfile = os.path.join(downloadDir, fname)
  479. #print "Trying to download - ", current
  480. if self.stream["img"]:
  481. try:
  482. thumb = urllib2.urlopen(stream["img"]).read()
  483. except:
  484. thumb = ""
  485. if thumb:
  486. imgext = ".jpg"
  487. m = re.search("(\.\w{3})$",stream["img"])
  488. if m:
  489. imgext = m.group(1)
  490. imgfile = os.path.join(downloadDir,fname0+imgext)
  491. with open(imgfile,"wb") as f:
  492. f.write(thumb)
  493. if self.stream["subs"]:
  494. suburl = self.stream["subs"][0]["url"]
  495. print "\n**Download subtitles %s - %s"%(title,suburl)
  496. subs = urllib2.urlopen(suburl).read()
  497. if subs:
  498. #fname0 = re.sub("[/\n\r\t,:]"," ",title)
  499. subext = ".srt"
  500. subfile = os.path.join(downloadDir,fname0+subext)
  501. if ".xml" in suburl:
  502. subs = util.ttaf2srt(subs)
  503. with open(subfile,"w") as f:
  504. f.write(subs)
  505. else:
  506. print "\n Error downloading subtitle %s"%suburl
  507. if "nfo" in self.stream and self.stream["nfo"]:
  508. nfofile = subfile = os.path.join(downloadDir,fname0+".nfo")
  509. with open(nfofile,"w") as f:
  510. nfo_txt = util.nfo2xml(self.stream["nfo"])
  511. f.write()
  512. overwrite = config.plugins.playstream.overwrite_download.value
  513. if not overwrite and os.path.exists(outputfile):
  514. self.msg( _('Sorry, this file already exists:\n%s') % outputfile)
  515. return False
  516. #os.remove(outputfile)
  517. if stream_type in ("http","https"):
  518. print "\n**Download %s - %s"%(title,url)
  519. #reload(downloadJob)
  520. job_manager.AddJob(downloadJob(url, outputfile, title[:20], self.video_download_stop))
  521. self.active_downloads += 1
  522. #self.msg(_('Video download started!'))
  523. return True
  524. elif stream_type == "hls":
  525. #self.msg("HLS stream download not yet implemented!")
  526. print "\n**Download %s - %s"%(title,url)
  527. #reload(HLSDownloadJob)
  528. print "HLSDownload", url,outputfile
  529. job_manager.AddJob(HLSDownloadJob(url, outputfile, title[:20], self.video_download_stop))
  530. self.active_downloads += 1
  531. #self.msg(_('Video download started!'))
  532. return True
  533. elif stream_type == "rstp":
  534. self.msg("RSTP stream download not yet implemented!")
  535. return False
  536. else:
  537. self.msg("Unkown stream type!")
  538. return False
  539. def cb_rename(self,value):
  540. if not value:
  541. return
  542. lst = self.cur_menu[1].replace("config::","")
  543. pos = self.index
  544. print value
  545. item2 = list(self.current)
  546. item2[0]=value
  547. item2 = tuple(item2)
  548. self.config.replace_item(lst,item2,pos)
  549. self.config.write_streams()
  550. txt = "'%s' renamed to '%s'"%(self.current[0],value)
  551. self.session.open(MessageBox, txt, MessageBox.TYPE_INFO,timeout=5)
  552. def cb_favorites(self,answer):
  553. print "cb_favorites",answer,self.current
  554. if not answer:
  555. return
  556. value = answer[1]
  557. self.config.add_item(value,self.current)
  558. self.config.write_streams()
  559. txt = "'%s' added to favourite stream list '%s'"%(self.current[0],value)
  560. self.session.open(MessageBox, txt, MessageBox.TYPE_INFO,timeout=3)
  561. #self.session.openWithCallback(self.callMyMsg, MessageBox, _("Do you want to exit the plugin?"), MessageBox.TYPE_INFO)
  562. def config_screen(self):
  563. self.session.open(ConfigScreen,self)
  564. def options_screen(self):
  565. source = self.cur_menu[1].split("::")[0]
  566. options = self.sources.options_read(source)
  567. print source
  568. if not options:
  569. self.session. open(MessageBox, "No options available for source %s (%s)"%(self.cur_menu[0],source) , MessageBox.TYPE_INFO)
  570. else:
  571. self.session.open(OptionsScreen,self)
  572. def video_download_stop(self,title):
  573. #self.activeDownloads -= 1
  574. #self.msg("Download '%s'finished!"%title)
  575. print "video_download_stop ", title
  576. def msg2(self,msg,timeout=10,mtype = None):
  577. mtype=mtype if mtype else MessageBox.TYPE_INFO
  578. Notifications.AddPopup(text = msg, type=mtype, timeout=timeout)
  579. def msg(self,msg,timeout=10):
  580. self.session.open(MessageBox, msg, MessageBox.TYPE_INFO, timeout)
  581. def make_service(stream):
  582. url = stream["url"]
  583. headers = []
  584. if stream.has_key("headers"):
  585. for h in stream["headers"]:
  586. headers.append("%s=%s"%(h,stream["headers"][h]))
  587. if headers:
  588. headers ="&".join(headers)
  589. url = url+"#"+headers
  590. print "stream_url with headers=",headers
  591. url = url.encode("utf8")
  592. if "|" in url:
  593. url = url.replace("|","#")
  594. service_type = 4097
  595. if re.search("\.ts$",url.split("?")[0],re.IGNORECASE):
  596. service_type = 1
  597. if "resolver" in stream and stream["resolver"] in ("hqq","viaplay","filmas"):
  598. url = util.streamproxy_encode(stream["url"], stream["headers"])
  599. #if os.path.exists("/usr/bin/exteplayer3"): # problem playing hqq streams with gstreamer, use exteplayer3
  600. #service_type = 5002
  601. print "service_type=",service_type
  602. print "stream_url=",url
  603. service = eServiceReference(service_type, 0, url)
  604. service.setName( stream["name"])
  605. return service
  606. def plugin_update(session):
  607. feed_file = "/etc/opkg/ivars777-feed.conf"
  608. if not os.path.exists(feed_file):
  609. with open(feed_file, "w") as f:
  610. f.write("src/gz ivars777 http://feed.blue.lv")
  611. cmdlist = [
  612. "opkg update",
  613. "opkg install enigma2-plugin-extensions-playstream",
  614. "echo Restart Enigma after upgrade!"
  615. ]
  616. # os.chmod(cmd, 493)
  617. session.open(Console, "Update PlayStream plugin", cmdlist)
  618. #####################################################################################################################
  619. class PSSubs(Screen):
  620. def __init__(self, session):
  621. desktopWidth = getDesktop(0).size().width()
  622. desktopHeight = getDesktop(0).size().height()
  623. offset = 20
  624. screenWidth = desktopWidth - (2 * offset)
  625. widgetWidth = screenWidth / 2 - 5
  626. self.skin = """
  627. <screen position="%d,%d" size="%d,140" zPosition="2" backgroundColor="transparent" flags="wfNoBorder">
  628. <widget name="subtitle" position="0,0" size="%d,140" valign="center" halign="center" font="Regular;36" transparent="1" foregroundColor="white" shadowColor="#40101010" shadowOffset="2,2" />
  629. </screen>""" % (offset, desktopHeight-offset-140, screenWidth, screenWidth)
  630. self['subtitle'] = Label()
  631. Screen.__init__(self, session)
  632. #####################################################################################################################
  633. class PSPlayer(MoviePlayer):
  634. def __init__(self, session, streams):
  635. print "PSPlayer init: ",streams
  636. self.session = session
  637. self.streams = streams
  638. self.cur_stream = self.streams[0] # TODO
  639. self.selected = 0
  640. self.resume_pos = 0
  641. service = make_service(self.cur_stream)
  642. MoviePlayer.__init__(self, session, service)
  643. self.skinName = "MoviePlayer"
  644. self["actions"] = ActionMap(["MediaPlayerActions","MediaPlayerSeekActions","MoviePlayerActions","InfobarSeekActions","MovieSelectionActions","ColorActions"], {
  645. "stop":self.leavePlayer,
  646. "leavePlayer":self.leavePlayer,
  647. "audio":self.select_stream,
  648. "AudioSelection":self.select_stream,
  649. "green":self.select_stream,
  650. "subtitles":self.select_captions,
  651. "text":self.select_captions,
  652. "yellow_key":self.select_captions,
  653. "yellow":self.select_captions,
  654. "pauseServiceYellow":self.select_captions,
  655. "pause":self.select_captions,
  656. "showEventInfo":self.service_info,
  657. "info":self.service_info
  658. })
  659. self.stimer = eTimer()
  660. if "callback" in dir(self.stimer):
  661. self.stimer.callback.append(self.update_subtitles)
  662. elif "timeout" in dir(self.stimer):
  663. self.stimer_conn = self.stimer.timeout.connect(self.update_subtitles)
  664. else:
  665. self.stimer = None
  666. self.stimer_step = 500
  667. if self.cur_stream["subs"]:
  668. self.subs = self.cur_stream["subs"]
  669. self.cur_subs = 0 # TODO - no konfigurācijas
  670. self.svisible = True # TODO - no konfigurācijas
  671. self.sind = 0
  672. self.get_subs_current()
  673. else:
  674. self.subs = []
  675. self.cur_subs = 0
  676. self.svisible = False
  677. self.subtitle_window = self.session.instantiateDialog (PSSubs)
  678. self.onLayoutFinish.append(self.start_subtitles_timer)
  679. def start_subtitles_timer0(self):
  680. if self.stimer:
  681. self.subtitle_window.show()
  682. print "start_subtitles_timer"
  683. self.stimer.start(self.stimer_step)
  684. def start_subtitles_timer(self):
  685. self.stimer.start(self.stimer_step)
  686. def get_sub_pts(self,pts):
  687. sc = self.get_sub_ind(self.sind) # current subbtitle
  688. while True:
  689. if not sc:
  690. return "Error - no subs find" # TODO
  691. if pts > sc["end"]:
  692. self.sind += 1
  693. sc = self.get_sub_ind(self.sind)
  694. continue
  695. else:
  696. if pts <sc["begin"]:
  697. return " "
  698. else:
  699. txt = sc["text"] if sc["text"] else " "
  700. return txt
  701. def get_sub_ind(self,ind):
  702. subs_object = self.get_subs_current() # current subs object
  703. if subs_object:
  704. return subs_object.subs[ind] if ind<len(subs_object.subs) else None
  705. else:
  706. return None
  707. def get_subs_current(self):
  708. "Return current sub_object"
  709. if not "subs" in self.subs[self.cur_subs]:
  710. print "===== Captions to download", self.subs[self.cur_subs]["url"]
  711. subs_object = util.Captions(self.subs[self.cur_subs]["url"])
  712. print len(subs_object.subs), "items"
  713. self.subs[self.cur_subs]["subs"] = subs_object
  714. if not subs_object:
  715. return None
  716. else:
  717. return subs_object
  718. else:
  719. return self.subs[self.cur_subs]["subs"]
  720. def update_subtitles(self):
  721. if not self.shown and self.svisible:
  722. seek = self.getSeek()
  723. pos = seek.getPlayPosition()
  724. pts = pos[1]/90
  725. txt0 = "%d:%02d (%i)" % (pts/60/1000, (pts/1000)%60, pts)
  726. #print "Update_subtitles", txt0
  727. if not self.subtitle_window.shown:
  728. self.subtitle_window.show()
  729. if not self.subs:
  730. return
  731. txt = self.get_sub_pts(pts)
  732. #print "Show subtitle",txt
  733. #txt = txt0+": "+ txt
  734. self.subtitle_window["subtitle"].setText(txt)
  735. elif self.shown and self.svisible:
  736. if self.subtitle_window.shown:
  737. self.subtitle_window.hide()
  738. elif not self.svisible:
  739. if self.subtitle_window.shown:
  740. self.subtitle_window.hide()
  741. # struct SubtitleTrack
  742. # int type;
  743. # int pid;
  744. # int page_number;
  745. # int magazine_number;
  746. # std::string language_code;
  747. #selectedSubtitle = ???
  748. #self.enableSubtitle(selectedSubtitle)
  749. def play_service(self,service):
  750. self.movieSelected(service)
  751. #def doShow(self):
  752. #self.svisible = False
  753. #InfoBarShowHide.doShow(self)
  754. #def doHide(self):
  755. #self.svisible = True
  756. #InfoBarShowHide.doHide(self)
  757. def service_info(self):
  758. print "########[MoviePlayer] service_info"
  759. text = "%s\n%s %s\n%s"%(self.cur_stream["name"],self.cur_stream["lang"],self.cur_stream["quality"],self.cur_stream["desc"])
  760. text = text.encode("utf8")
  761. #print text
  762. #mtype = MessageBox.TYPE_INFO
  763. #Notifications.AddPopup(text = text, type=mtype, timeout = 10)
  764. print "StreamInfo", self.cur_stream
  765. nfo = self.cur_stream["nfo"] if "nfo" in self.cur_stream else {"movie":{"title":self.current[0],"thumb":self.current[1],"plot":self.current[3]}}
  766. self.session.open(StreamInfo, nfo)
  767. def select_stream(self):
  768. print "########[MoviePlayer] select_stream"
  769. lst = []
  770. title = "Select stream"
  771. for i,s in enumerate(self.streams):
  772. lst.append(("[%s,%s] %s"%(s["lang"],s["quality"],s["name"]),i))
  773. self.session.openWithCallback(self.cb_select_stream, ChoiceBox, title = title, list = lst,selection = self.selected)
  774. def cb_select_stream(self,answer):
  775. #print "item_menu_selected",answer
  776. if not answer:
  777. return
  778. self.selected = answer[1]
  779. service = make_service(self.streams[self.selected])
  780. self.resume_pos = self.getSeek().getPlayPosition()[1]
  781. self.play_service(service)
  782. def serviceStarted(self):
  783. print "serviceStarted"
  784. if not self.resume_pos:
  785. self.resume_pos = 0
  786. print "doSeek",self.resume_pos
  787. #self.doSeek(self.resume_pos)
  788. def select_captions(self):
  789. print "########[MoviePlayer] select_caption"
  790. lst = []
  791. title = "Select subtitles"
  792. for i,s in enumerate(self.subs):
  793. lst.append((("%s - %s"%(s["lang"],s["name"])).encode("utf8"),i))
  794. if self.svisible:
  795. selection = self.cur_subs
  796. else:
  797. selection = len(lst)
  798. lst.append(("No captions",-1))
  799. self.session.openWithCallback(self.cb_select_captions, ChoiceBox, title = title, list = lst,selection = selection)
  800. def cb_select_captions(self,answer):
  801. #print "item_menu_selected",answer
  802. if not answer:
  803. return
  804. if answer[1] == -1:
  805. self.svisible = False
  806. else:
  807. self.cur_subs = answer[1]
  808. self.svisible = True
  809. def leavePlayer(self):
  810. self.close()
  811. #self.session.openWithCallback(self.leavePlayerConfirmed, MessageBox, _("Stop playing?"))
  812. def leavePlayerConfirmed(self, answer):
  813. if answer:
  814. self.close()
  815. def doEofInternal(self, playing):
  816. self.close()
  817. #def getPluginList(self):
  818. #from Components.PluginComponent import plugins
  819. #list = []
  820. #for p in plugins.getPlugins(where = PluginDescriptor.WHERE_EXTENSIONSMENU):
  821. #if p.name != _("TV Play"):
  822. #list.append(((boundFunction(self.getPluginName, p.name),
  823. #boundFunction(self.runPlugin, p), lambda: True), None))
  824. #return list
  825. #def showMovies(self):
  826. #pass
  827. #####################################################################################################################
  828. class ConfigScreen(ConfigListScreen,Screen):
  829. def __init__(self, session, args = 0):
  830. self.session = session
  831. #self.setup_title = "Options"
  832. Screen.__init__(self, session)
  833. self.skinName = ["PSConfig"]
  834. self.list = [
  835. getConfigListEntry(_("Download folder"), config.plugins.playstream.download_dir),
  836. getConfigListEntry(_("Overwrite download video"), config.plugins.playstream.overwrite_download),
  837. getConfigListEntry(_("TMP folder"), config.plugins.playstream.tmp_dir),
  838. getConfigListEntry(_("Clear tmp folder on exit"), config.plugins.playstream.clear_tmp),
  839. getConfigListEntry(_("Start playstreamproxy"), config.plugins.playstream.streamproxy_start),
  840. getConfigListEntry(_("Check new plugin version in feed"), config.plugins.playstream.check_update)
  841. ]
  842. ConfigListScreen.__init__(self, self.list, session = self.session)
  843. self["title"] = Label()
  844. self["key_red"] = Button(_("Cancel"))
  845. self["key_green"] = Button(_("Save"))
  846. self["key_yellow"] = Button("Update")
  847. self["key_blue"] = Button("Downloads")
  848. self["setupActions"] = ActionMap(["SetupActions", "ColorActions"],
  849. {
  850. "red": self.cancel,
  851. "green": self.save,
  852. "yellow": self.update_plugin,
  853. "blue": self.downloads,
  854. "save": self.save,
  855. "cancel": self.cancel,
  856. "ok": self.ok,
  857. }, -2)
  858. self["title"].setText("Version %s, ivars777@gmail.com"%__version__)
  859. def getCurrentEntry(self):
  860. return self["config"].getCurrent()[0]
  861. def getCurrentValue(self):
  862. return str(self["config"].getCurrent()[1].getText())
  863. def ok(self):
  864. if self["config"].getCurrent()[1] == config.plugins.playstream.download_dir:
  865. folder = config.plugins.playstream.download_dir.value
  866. #self.session.openWithCallback(self.cb_download_dir, LocationBox,"Select Folder")
  867. self.session.openWithCallback(self.cb_download_dir, LocationBox,"Select download folder","",config.plugins.playstream.download_dir.value,config.plugins.playstream.locations,False,"Select folder",None,True,True)
  868. elif self["config"].getCurrent()[1] == config.plugins.playstream.tmp_dir:
  869. self.session.openWithCallback(self.select_tmp_dir, LocationBox,"Select tmp folder","",config.plugins.playstream.download_dir.value,config.plugins.playstream.locations,False,"Select folder",None,True,True)
  870. else:
  871. self.save()
  872. def cb_download_dir(self, folder, select=None):
  873. if not folder:
  874. return
  875. print "Folder selected - %s"%folder
  876. config.plugins.playstream.download_dir.setValue(folder)
  877. config.plugins.playstream.download_dir.save()
  878. config.plugins.playstream.locations.save()
  879. config.save()
  880. def select_tmp_dir(self, folder, select=None):
  881. if not folder:
  882. return
  883. print "Folder selected - %s"%folder
  884. config.plugins.playstream.tmp_dir.setValue(folder)
  885. config.plugins.playstream.tmp_dir.save()
  886. config.plugins.playstream.locations.save()
  887. config.save()
  888. def save(self):
  889. print "saving"
  890. self.saveAll()
  891. self.close(True,self.session)
  892. def cancel(self):
  893. #print "cancel"
  894. self.close(False,self.session)
  895. def downloads(self):
  896. self.session.open(VideoDownloadList)
  897. def update_plugin(self):
  898. #print "Check PlayStream for update"
  899. self.cver = util.check_version("enigma2-plugin-extensions-playstream")
  900. if self.cver and self.cver>__version__:
  901. txt = "New version of plugin available for update - %s\nCurrent version - %s\nDo you want to upgrade?"%(self.cver,__version__)
  902. else:
  903. txt = "No new version of plugin available for update - %s\nCurrent version - %s\nDo you want to upgrade?"%(self.cver,__version__)
  904. mbox = self.session.openWithCallback(self.update, MessageBox, txt, MessageBox.TYPE_YESNO)
  905. mbox.setTitle("Upgrade plugin?")
  906. def update(self,answer):
  907. if answer:
  908. plugin_update(self.session)
  909. def restart_dialog(self):
  910. self.session.openWithCallback(self.restart, MessageBox, _("Restart Enigma2?"),MessageBox.TYPE_YESNO)
  911. def restart(self, answer):
  912. if answer:
  913. self.session.open(TryQuitMainloop, retvalue=3)
  914. else:
  915. return
  916. #####################################################################################################################
  917. class OptionsScreen(ConfigListScreen,Screen):
  918. def __init__(self, session,*args):
  919. self.session = session
  920. Screen.__init__(self, session)
  921. self.skinName = ["PSOptions"]
  922. self.main = args[0]
  923. self.setTitle("Source options")
  924. self.source = self.main.cur_menu[1].split("::")[0]
  925. self.cfg = ConfigSubDict() #config.plugins.playstream
  926. self.list = []
  927. self.options = self.main.sources.options_read(self.source)
  928. if not self.options:
  929. #self.session. open(MessageBox, "No options available for source %s (%s)"%(self.main.cur_menu[0],self.source) , MessageBox.TYPE_INFO)
  930. self.close(False,self.session)
  931. for k in self.options:
  932. self.cfg[k]=ConfigText(default=self.options[k],fixed_size=False)
  933. self.list.append(getConfigListEntry(k, self.cfg[k]))
  934. ConfigListScreen.__init__(self, self.list, session = self.session)
  935. self["title"] = Label()
  936. self["key_red"] = Button(_("Cancel"))
  937. self["key_green"] = Button("Save")
  938. self["key_yellow"] = Button("")
  939. self["key_blue"] = Button("")
  940. self["setupActions"] = ActionMap(["SetupActions", "ColorActions"],
  941. {
  942. "red": self.cancel,
  943. "green": self.save,
  944. "save": self.save,
  945. "cancel": self.cancel,
  946. "ok": self.ok,
  947. }, -2)
  948. self["title"].setText(self.main.sources.plugins[self.source].title)
  949. def getCurrentEntry(self):
  950. return self["config"].getCurrent()[0]
  951. def getCurrentValue(self):
  952. return str(self["config"].getCurrent()[1].getText())
  953. def ok(self):
  954. self.save()
  955. #if self["config"].getCurrent()[1] == config.plugins.getpicons.folder:
  956. #folder = config.plugins.getpicons.folder.value
  957. #self.session.openWithCallback(self.change_dir, LocationBox,"Select Folder")
  958. #else:
  959. #def change_dir(self, folder, select=None):
  960. #if folder:
  961. ##print "change_dir to %s"%folder
  962. #config.plugins.getpicons.folder.value = folder
  963. def save(self):
  964. print "saving"
  965. #self.saveAll()
  966. for k in self.options.keys():
  967. self.options[k]=self.cfg[k].value
  968. print "%s=%s"%(k,self.cfg[k].value)
  969. self.main.sources.options_write(self.source,self.options)
  970. self.close(True,self.session)
  971. def cancel(self):
  972. print "cancel"
  973. self.close(False,self.session)
  974. #####################################################################################################################
  975. class StreamInfo(Screen):
  976. def __init__(self, session, nfo):
  977. if not nfo:
  978. return
  979. Screen.__init__(self, session)
  980. self.skinName = ["PSStreamInfo"]
  981. self.session = session
  982. self["key_red"] = Button(_("Exit"))
  983. self["actions"] = ActionMap(["OkCancelActions", "ColorActions","ButtonSetupActions"], {
  984. "ok": self.cancel,
  985. "red": self.cancel,
  986. "cancel": self.cancel,
  987. "pageup": self.page_up,
  988. "channelup":self.page_up,
  989. "pagedown": self.page_down,
  990. "channeldown":self.page_down,
  991. })
  992. self["pic"] = Pixmap()
  993. self["info"] = ScrollLabel()
  994. self["title"] = Label()
  995. self.nfo = nfo
  996. self.onLayoutFinish.append(self.layout_finished)
  997. def cancel(self):
  998. #print "cancel"
  999. self.close(False,self.session)
  1000. def layout_finished(self):
  1001. nfo = self.nfo
  1002. print "StreamInfo nfo", nfo
  1003. if not "title" in nfo:
  1004. nfo_type, nfo = next(nfo.iteritems())
  1005. title = util.nfo2title(nfo)
  1006. desc = util.nfo2desc(nfo)
  1007. self["title"].setText(title)
  1008. self["info"].setText(desc)
  1009. image_url = nfo["thumb"]
  1010. if image_url and image_url.startswith("http"):
  1011. fname = image_url.replace(":", "-").replace("/", "_")
  1012. image_path = os.path.join(config.plugins.playstream.tmp_dir.value, fname)
  1013. if not os.path.exists(image_path):
  1014. downloadPage(image_url, image_path).addCallback(boundFunction(self.download_finished, image_path,image_url)).addErrback(boundFunction(self.download_failed, image_path,image_url))
  1015. else:
  1016. self.download_finished(image_path, image_url)
  1017. elif image_url:
  1018. image_path = os.path.join(cur_directory, image_url)
  1019. self.download_finished(image_path,"")
  1020. def download_finished(self, image_path,image_url):
  1021. sc = AVSwitch().getFramebufferScale()
  1022. self.picloads = ePicLoad()
  1023. self.picloads.PictureData.get().append(boundFunction(self.finish_decode, image_path))
  1024. # 0=Width 1=Height 2=Aspect 3=use_cache 4=resize_type 5=Background(#AARRGGBB)
  1025. self.picloads.setPara((self["pic"].instance.size().width(), self["pic"].instance.size().height(),
  1026. sc[0], sc[1], True, 0, "#00000000"))
  1027. print image_path,image_url
  1028. self.picloads.startDecode(image_path.encode("utf8"))
  1029. def download_failed(self, image_path,image_url):
  1030. print "[PlayStream] Image downloaded failed ",image_url
  1031. def finish_decode(self, image_path,picInfo = None):
  1032. ptr = self.picloads.getData()
  1033. self["pic"].instance.setPixmap(ptr)
  1034. def page_down(self):
  1035. self["info"].pageDown()
  1036. def page_up(self):
  1037. self["info"].pageUp()