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

PlayStream.py 50KB

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