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

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