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

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