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

PlayStream.py 40KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  1. #!/usr/bin/env python
  2. # coding=utf8
  3. #
  4. #
  5. # This file is part of PlayStream - enigma2 plugin to play video streams from various sources
  6. # Copyright (c) 2016 ivars777 (ivars777@gmail.com)
  7. # Distributed under the GNU GPL v3. For full terms see http://www.gnu.org/licenses/gpl-3.0.en.html
  8. # Used fragments of code from enigma2-plugin-tv3play by Taapat (https://github.com/Taapat/enigma2-plugin-tv3play)
  9. #
  10. import os,time,sys,os,os.path
  11. import datetime,re
  12. import urllib2
  13. from enigma import ePicLoad, eServiceReference, eTimer, getDesktop
  14. from Components.ActionMap import ActionMap,HelpableActionMap
  15. from Screens.InfoBarGenerics import InfoBarShowHide
  16. from Components.AVSwitch import AVSwitch
  17. from Components.Label import Label
  18. from Components.MenuList import MenuList
  19. from Components.Pixmap import Pixmap
  20. from Components.Sources.List import List
  21. from Components.Sources.StaticText import StaticText
  22. from Components.Button import Button
  23. from Plugins.Plugin import PluginDescriptor
  24. from Screens.InfoBar import MoviePlayer
  25. from Screens.MessageBox import MessageBox
  26. from Tools import Notifications
  27. from Screens.LocationBox import LocationBox
  28. #from Screens.InputBox import InputBox
  29. from Screens.ChoiceBox import ChoiceBox
  30. from Screens.VirtualKeyBoard import VirtualKeyBoard
  31. from Components.Input import Input
  32. from Screens.Screen import Screen
  33. from Tools.BoundFunction import boundFunction
  34. from Tools.Directories import resolveFilename, SCOPE_PLUGINS
  35. from Tools.LoadPixmap import LoadPixmap
  36. from twisted.web.client import downloadPage,defer,reactor
  37. from Components.Task import job_manager
  38. from Components.config import config, ConfigSubsection, ConfigText, ConfigInteger, ConfigLocations, ConfigDirectory, ConfigSet, ConfigYesNo, ConfigSelection, getConfigListEntry, ConfigSelectionNumber
  39. import ContentSources
  40. import util
  41. from sources.SourceBase import stream0
  42. from VideoDownload import downloadJob, HLSDownloadJob,VideoDownloadList
  43. #import enigma2_api
  44. TMPDIR = "/tmp/playstream/"
  45. e2 = None
  46. config.playstream = ConfigSubsection()
  47. config.playstream.locations = ConfigLocations(default=["/media/hdd/movie/"])
  48. config.playstream.download_dir = ConfigText(default="/media/hdd/movie/")
  49. def make_service(stream):
  50. url = stream["url"]
  51. headers = []
  52. if stream.has_key("headers"):
  53. for h in stream["headers"]:
  54. headers.append("%s=%s"%(h,stream["headers"][h]))
  55. if headers:
  56. headers ="&".join(headers)
  57. url = url+"#"+headers
  58. print "stream_url with headers=",headers
  59. url = url.encode("utf8")
  60. if "|" in url:
  61. url = url.replace("|","#")
  62. #url = url.replace(":","%3a")
  63. print "stream_url=",url
  64. service = eServiceReference(4097, 0, url)
  65. service.setName( stream["name"])
  66. return service
  67. #####################################################################################################################
  68. class PSSubs(Screen):
  69. def __init__(self, session):
  70. desktopWidth = getDesktop(0).size().width()
  71. desktopHeight = getDesktop(0).size().height()
  72. offset = 20
  73. screenWidth = desktopWidth - (2 * offset)
  74. widgetWidth = screenWidth / 2 - 5
  75. self.skin = """
  76. <screen position="%d,%d" size="%d,140" zPosition="2" backgroundColor="transparent" flags="wfNoBorder">
  77. <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" />
  78. </screen>""" % (offset, desktopHeight-offset-140, screenWidth, screenWidth)
  79. self['subtitle'] = Label()
  80. Screen.__init__(self, session)
  81. #####################################################################################################################
  82. class PSPlayer(MoviePlayer):
  83. def __init__(self, session, streams):
  84. print "PSPlayer init: ",streams
  85. self.session = session
  86. self.streams = streams
  87. self.cur_stream = self.streams[0] # TODO
  88. self.selected = 0
  89. self.resume_pos = 0
  90. service = make_service(self.cur_stream)
  91. MoviePlayer.__init__(self, session, service)
  92. self.skinName = "MoviePlayer"
  93. self["actions"] = ActionMap(["MediaPlayerActions","MediaPlayerSeekActions","MoviePlayerActions","InfobarSeekActions","MovieSelectionActions","ColorActions"], {
  94. "stop":self.leavePlayer,
  95. "leavePlayer":self.leavePlayer,
  96. "audio":self.select_stream,
  97. "AudioSelection":self.select_stream,
  98. "green":self.select_stream,
  99. "subtitles":self.select_captions,
  100. "text":self.select_captions,
  101. "yellow_key":self.select_captions,
  102. "yellow":self.select_captions,
  103. "pauseServiceYellow":self.select_captions,
  104. "pause":self.select_captions,
  105. "showEventInfo":self.service_info,
  106. "info":self.service_info
  107. })
  108. self.stimer = eTimer()
  109. if "callback" in dir(self.stimer):
  110. self.stimer.callback.append(self.update_subtitles)
  111. elif "timeout":
  112. self.stimer_conn = self.stimer.timeout.connect(self.update_subtitles)
  113. else:
  114. self.stimer = None
  115. self.stimer_step = 500
  116. if self.cur_stream["subs"]:
  117. self.subs = self.cur_stream["subs"]
  118. self.cur_subs = 0 # TODO - no konfiguracijas
  119. self.svisible = True # TODO - no konfiguracija
  120. self.sind = 0
  121. self.get_subs_current()
  122. else:
  123. self.subs = []
  124. self.cur_subs = 0
  125. self.svisible = False
  126. self.subtitle_window = self.session.instantiateDialog (PSSubs)
  127. self.onLayoutFinish.append(self.start_subtitles_timer)
  128. def start_subtitles_timer(self):
  129. if self.stimer:
  130. self.subtitle_window.show()
  131. print "start_subtitles_timer"
  132. self.stimer.start(self.stimer_step)
  133. def get_sub_pts(self,pts):
  134. sc = self.get_sub_ind(self.sind) # current subbtitle
  135. while True:
  136. if not sc:
  137. return "Error - no subs find" # TODO
  138. if pts > sc["end"]:
  139. self.sind += 1
  140. sc = self.get_sub_ind(self.sind)
  141. continue
  142. else:
  143. if pts <sc["begin"]:
  144. return " "
  145. else:
  146. txt = sc["text"] if sc["text"] else " "
  147. return txt
  148. def get_sub_ind(self,ind):
  149. subs_object = self.get_subs_current() # current subs object
  150. if subs_object:
  151. return subs_object.subs[ind] if ind<len(subs_object.subs) else None
  152. else:
  153. return None
  154. def get_subs_current(self):
  155. "Return current sub_object"
  156. if not "subs" in self.subs[self.cur_subs]:
  157. print "===== Captions to download", self.subs[self.cur_subs]["url"]
  158. subs_object = util.Captions(self.subs[self.cur_subs]["url"])
  159. print len(subs_object.subs), "items"
  160. self.subs[self.cur_subs]["subs"] = subs_object
  161. if not subs_object:
  162. return None
  163. else:
  164. return subs_object
  165. else:
  166. return self.subs[self.cur_subs]["subs"]
  167. def update_subtitles(self):
  168. if not self.shown and self.svisible:
  169. seek = self.getSeek()
  170. pos = seek.getPlayPosition()
  171. pts = pos[1]/90
  172. txt0 = "%d:%02d (%i)" % (pts/60/1000, (pts/1000)%60, pts)
  173. #print "Update_subtitles", txt0
  174. if not self.subtitle_window.shown:
  175. self.subtitle_window.show()
  176. if not self.subs:
  177. return
  178. txt = self.get_sub_pts(pts)
  179. #print "Show subtitle",txt
  180. #txt = txt0+": "+ txt
  181. self.subtitle_window["subtitle"].setText(txt)
  182. elif self.shown and self.svisible:
  183. if self.subtitle_window.shown:
  184. self.subtitle_window.hide()
  185. elif not self.svisible:
  186. if self.subtitle_window.shown:
  187. self.subtitle_window.hide()
  188. # struct SubtitleTrack
  189. # int type;
  190. # int pid;
  191. # int page_number;
  192. # int magazine_number;
  193. # std::string language_code;
  194. #selectedSubtitle = ???
  195. #self.enableSubtitle(selectedSubtitle)
  196. def start_subtitles_timer(self):
  197. self.stimer.start(self.stimer_step)
  198. def play_service(self,service):
  199. self.movieSelected(service)
  200. #def doShow(self):
  201. #self.svisible = False
  202. #InfoBarShowHide.doShow(self)
  203. #def doHide(self):
  204. #self.svisible = True
  205. #InfoBarShowHide.doHide(self)
  206. def service_info(self):
  207. print "########[MoviePlayer] service_info"
  208. text = "%s\n%s %s\n%s"%(self.cur_stream["name"],self.cur_stream["lang"],self.cur_stream["quality"],self.cur_stream["desc"])
  209. text = text.encode("utf8")
  210. #print text
  211. mtype = MessageBox.TYPE_INFO
  212. Notifications.AddPopup(text = text, type=mtype, timeout = 10)
  213. #Notifications.MessageBox(self.session, text=text, type=MessageBox.TYPE_INFO, timeout=10,
  214. #close_on_any_key=True,
  215. #default=True,
  216. #enable_input=True,
  217. #msgBoxID=None,
  218. #picon=False,
  219. #simple=False,
  220. #wizard=False,
  221. #list=None,
  222. #skin_name=None,
  223. #timeout_default=None)
  224. #return True
  225. def select_stream(self):
  226. print "########[MoviePlayer] select_stream"
  227. lst = []
  228. title = "Select stream"
  229. for i,s in enumerate(self.streams):
  230. lst.append(("[%s,%s] %s"%(s["lang"],s["quality"],s["name"]),i))
  231. self.session.openWithCallback(self.cb_select_stream, ChoiceBox, title = title, list = lst,selection = self.selected)
  232. def cb_select_stream(self,answer):
  233. #print "item_menu_selected",answer
  234. if not answer:
  235. return
  236. self.selected = answer[1]
  237. service = make_service(self.streams[self.selected])
  238. self.resume_pos = self.getSeek().getPlayPosition()[1]
  239. self.play_service(service)
  240. def serviceStarted(self):
  241. print "serviceStarted"
  242. if not self.resume_pos:
  243. self.resume_pos = 0
  244. print "doSeek",self.resume_pos
  245. #self.doSeek(self.resume_pos)
  246. def select_captions(self):
  247. print "########[MoviePlayer] select_caption"
  248. lst = []
  249. title = "Select subtitles"
  250. for i,s in enumerate(self.subs):
  251. lst.append((("%s - %s"%(s["lang"],s["name"])).encode("utf8"),i))
  252. if self.svisible:
  253. selection = self.cur_subs
  254. else:
  255. selection = len(lst)
  256. lst.append(("No captions",-1))
  257. self.session.openWithCallback(self.cb_select_captions, ChoiceBox, title = title, list = lst,selection = selection)
  258. def cb_select_captions(self,answer):
  259. #print "item_menu_selected",answer
  260. if not answer:
  261. return
  262. if answer[1] == -1:
  263. self.svisible = False
  264. else:
  265. self.cur_subs = answer[1]
  266. self.svisible = True
  267. def leavePlayer(self):
  268. self.close()
  269. #self.session.openWithCallback(self.leavePlayerConfirmed, MessageBox, _("Stop playing?"))
  270. def leavePlayerConfirmed(self, answer):
  271. if answer:
  272. self.close()
  273. def doEofInternal(self, playing):
  274. self.close()
  275. #def getPluginList(self):
  276. #from Components.PluginComponent import plugins
  277. #list = []
  278. #for p in plugins.getPlugins(where = PluginDescriptor.WHERE_EXTENSIONSMENU):
  279. #if p.name != _("TV Play"):
  280. #list.append(((boundFunction(self.getPluginName, p.name),
  281. #boundFunction(self.runPlugin, p), lambda: True), None))
  282. #return list
  283. #def showMovies(self):
  284. #pass
  285. #####################################################################################################################
  286. class MainScreen(Screen):
  287. skin = """
  288. <screen position="center,center" size="1015,570" title="Play Stream">
  289. <eLabel position="5,0" size="1000,2" backgroundColor="#aaaaaa" />
  290. <widget name="title" position="10,2" size="1000,38" font="Regular;30" />
  291. <widget source="list" render="Listbox" position="10,55" size="580,470" \
  292. scrollbarMode="showOnDemand" >
  293. <convert type="TemplatedMultiContent" >
  294. {
  295. "template": [MultiContentEntryText(pos=(10, 1), size=(560, 30), \
  296. font=0, flags=RT_HALIGN_LEFT, text=0)],
  297. "fonts": [gFont("Regular", 20)],
  298. "itemHeight": 30
  299. }
  300. </convert>
  301. </widget>
  302. <widget name="pic" position="646,55" size="327,250" alphatest="on" />
  303. <widget name="cur" position="610,300" size="400,250" halign="center" font="Regular;20"/>
  304. <ePixmap name="exit" position="10,540" zPosition="2" size="140,40" pixmap="skin_default/buttons/key_exit.png" transparent="1" alphatest="on" />
  305. <widget name="key_exit" position="10,535" size="140,40" valign="center" halign="center" zPosition="4" backgroundColor="blue" foregroundColor="white" font="Regular;20" transparent="1" shadowColor="background" shadowOffset="-2,-2" />
  306. <ePixmap name="red" position="150,535" zPosition="2" size="140,40" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
  307. <widget name="key_red" position="150,535" size="140,40" valign="center" halign="center" zPosition="4" foregroundColor="white" font="Regular;20" transparent="1" shadowColor="background" shadowOffset="-2,-2" />
  308. <ePixmap name="green" position="290,535" zPosition="2" size="140,40" pixmap="skin_default/buttons/green.png" transparent="1" alphatest="on" />
  309. <widget name="key_green" position="290,535" size="140,40" valign="center" halign="center" zPosition="4" foregroundColor="white" font="Regular;20" transparent="1" shadowColor="background" shadowOffset="-2,-2" />
  310. <ePixmap name="yellow" position="430,535" zPosition="2" size="140,40" pixmap="skin_default/buttons/yellow.png" transparent="1" alphatest="on" />
  311. <widget name="key_yellow" position="430,535" size="140,40" valign="center" halign="center" zPosition="4" foregroundColor="white" font="Regular;20" transparent="1" shadowColor="background" shadowOffset="-2,-2" />
  312. <ePixmap name="menu" position="610,540" zPosition="2" size="140,40" pixmap="skin_default/buttons/key_menu.png" transparent="1" alphatest="on" />
  313. <widget name="key_menu" position="610,535" size="140,40" valign="center" halign="center" zPosition="4" backgroundColor="blue" foregroundColor="white" font="Regular;20" transparent="1" shadowColor="background" shadowOffset="-2,-2" />
  314. </screen>"""
  315. def __init__(self, session):
  316. Screen.__init__(self, session)
  317. #self.setTitle2("Home")
  318. self.session = session
  319. self.e2 = None
  320. self["key_red"] = Button(_("Exit"))
  321. self["key_green"] = Button(_("Select"))
  322. self["key_yellow"] = Button(_("Options"))
  323. self["key_menu"] = Button("Menu")
  324. self["key_exit"] = Button("Back")
  325. self["actions"] = ActionMap(["OkCancelActions", "ColorActions","MenuActions", "NumberActions"],
  326. {
  327. #"cancel": self.Cancel,
  328. "ok": self.Ok,
  329. "green": self.Ok,
  330. "red": self.Cancel,
  331. "yellow": self.options_screen,
  332. "blue": self.download_list,
  333. "menu": self.item_menu,
  334. "cancel": self.Back,
  335. })
  336. self["list"] = List([])
  337. self["list"].onSelectionChanged.append(self.SelectionChanged)
  338. self["pic"] = Pixmap()
  339. self["cur"] = Label()
  340. self["title"] = Label()
  341. self.downloading = 0
  342. self.activeDownloads = 0
  343. if not os.path.exists(TMPDIR):
  344. os.mkdir(TMPDIR)
  345. self.onLayoutFinish.append(self.LayoutFinish)
  346. def LayoutFinish(self):
  347. self.cur_directory = os.path.dirname(os.path.realpath(__file__))
  348. self.defimage = LoadPixmap(os.path.join(self.cur_directory,"PlayStream.png"))
  349. #self.defimage = None
  350. #sc = AVSwitch().getFramebufferScale()
  351. #self.defimage0 = ePicLoad()
  352. #self.defimage0.PictureData.get().append(boundFunction(self.FinishDecodeDef, os.path.join(self.cur_directory,"PlayStream.png")))
  353. #self.defimage0.setPara((self["pic"].instance.size().width(),self["pic"].instance.size().height(),sc[0], sc[1], False, 0, "#00000000"))
  354. #self.defimage0.startDecode("default")
  355. self.activeDownloads = 0
  356. self.images = {}
  357. self.images_url = {}
  358. self.picloads = {}
  359. self.history = []
  360. reload(ContentSources)
  361. self.sources = ContentSources.ContentSources(os.path.join(self.cur_directory,"sources"))
  362. self.config = self.sources.plugins["config"]
  363. self.cur_menu = ("Home","config::home","","Sākums") #
  364. self.content = self.sources.get_content(self.cur_menu[1])
  365. #print self.content
  366. self["list"].setList(self.content)
  367. self["cur"].setText(self.content[0][3])
  368. self.setTitle2(self.cur_menu[0])
  369. self.ShowPic(self.content[0][2])
  370. def SelectionChanged(self):
  371. current = self["list"].getCurrent()
  372. print "[PlayStream] SelectionChanged: current=",current
  373. if not current: return
  374. self["cur"].setText(current[3]) if current[3] else self["cur"].setText("")
  375. if current[2]:
  376. self.ShowPic(current[2])
  377. else:
  378. self.ShowDefPic()
  379. def setTitle2(self,title):
  380. #print self.keys()
  381. self["title"].setText(title)
  382. def ShowDefPic(self):
  383. if self.defimage:
  384. self["pic"].instance.setPixmap(self.defimage)
  385. def ShowPic(self,image_url):
  386. if image_url == "default":
  387. self.ShowDefPic()
  388. return
  389. elif self.images.has_key(image_url):
  390. if self.images[image_url] in (-1,-2):
  391. return
  392. elif self.images[image_url] == -3:
  393. self.ShowDefPic()
  394. return
  395. else:
  396. self["pic"].instance.setPixmap(self.images[image_url])
  397. else:
  398. if image_url.startswith("http"):
  399. fname = image_url.replace(":","-").replace("/","_")
  400. image_path = os.path.join(TMPDIR, fname)
  401. self.download_image(image_path, image_url)
  402. else: # local file
  403. image_path = os.path.join(self.cur_directory,image_url)
  404. self.start_decode(image_path,image_url)
  405. def start_decode(self,image_path,image_url):
  406. self.images[image_url] = -2
  407. self.images_url[image_path] = image_url
  408. sc = AVSwitch().getFramebufferScale()
  409. if not self.picloads.has_key(image_path):
  410. self.picloads[image_path] = ePicLoad()
  411. self.picloads[image_path].PictureData.get().append(boundFunction(self.FinishDecode, image_path))
  412. self.picloads[image_path].setPara((self["pic"].instance.size().width(),
  413. self["pic"].instance.size().height(),
  414. sc[0], sc[1], True, 0, "#00000000"))
  415. #print image_path,image_url
  416. self.picloads[image_path].startDecode(image_path)
  417. def FinishDecode(self, image_path,picInfo = None):
  418. image_url = self.images_url[image_path]
  419. del self.images_url[image_path] #III
  420. self.images[image_url] = self.picloads[image_path].getData()
  421. self["pic"].instance.setPixmap(self.images[image_url])
  422. del self.picloads[image_path]
  423. if len(self.images)>30:
  424. del self.images[self.images.keys()[0]]
  425. # self.images.pop()
  426. #def FinishDecodeDef(self, image_path,picInfo = None):
  427. # self.defimage = self.defimage0.getData()
  428. # del self.defimage0
  429. # self["pic"].instance.setPixmap(self.defimage)
  430. def download_image(self,image_path,image_url):
  431. #print "Image download started",self.downloading,image_path,image_url
  432. self.downloading += 1
  433. self.images[image_url] = -1
  434. downloadPage(image_url, image_path).addCallback(boundFunction(self.downloadFinished, image_path,image_url)).addErrback(boundFunction(self.downloadFailed, image_path,image_url))
  435. def downloadFinished(self, image_path, image_url, result):
  436. self.downloading -= 1
  437. #print "[ Play] Image downloaded finished ",self.downloading,image_path, image_url,result
  438. self.start_decode(image_path,image_url)
  439. def downloadFailed(self, image_path, image_url,result):
  440. self.downloading -= 1
  441. print "[TV Play] Image downloaded failed ",self.downloading,image_path, image_url,result
  442. self.images[image_url] = -3
  443. def Ok(self):
  444. current = self["list"].getCurrent()
  445. self.current = current
  446. index = self["list"].getIndex()
  447. self.index = index
  448. print "[PlayStream] - menu selected ", current
  449. data = current[1].split("::")[1] if "::" in current[1] else current[1]
  450. if not data:
  451. return
  452. elif self.sources.is_video(current[1]):
  453. if self.sources.stream_type(current[1]):
  454. stream = stream0.copy()
  455. stream["url"] = current[1]
  456. stream["name"] = current[0]
  457. streams = [stream]
  458. else:
  459. try:
  460. streams = self.sources.get_streams(current[1])
  461. except Exception,e:
  462. print str(e)
  463. self.session. open(MessageBox, "Error - %s"%str(e) , MessageBox.TYPE_INFO)
  464. return
  465. if streams:
  466. #print streams
  467. for s in streams:
  468. if not s["name"]: s["name"] = current[0]
  469. if not s["img"]: s["img"] = current[2]
  470. if not s["desc"]: s["desc"] = current[3]
  471. try:
  472. self.session.open(PSPlayer, streams)
  473. except Exception as e:
  474. self.msg2("Error launching player - " + str(e))
  475. return
  476. else:
  477. self.msg("No stream found - %s"%(self.current[1]))
  478. return
  479. elif current[1] == "back":
  480. cur_menu_old = self.cur_menu
  481. self.cur_menu = self.history.pop()
  482. new_content = self.sources.get_content(self.cur_menu[1])
  483. try:
  484. index = zip(*new_content)[1].index(cur_menu_old[1])
  485. except:
  486. index = 0
  487. self.setTitle2(self.cur_menu[0])
  488. self.show_content(new_content,index)
  489. else:
  490. print "selected=",current
  491. if "{0}" in current[1]:
  492. self.session.openWithCallback(self.cb_input,VirtualKeyBoard, title="Enter value", text="")
  493. #a = raw_input("Enter value:")
  494. #a = "big bang"
  495. #current = (current[0],current[1].format(a),current[2],current[3])
  496. #self.get_content(current)
  497. else:
  498. self.get_content(current)
  499. def cb_input(self,value):
  500. if not value:
  501. return
  502. current = self.current
  503. current = (current[0],current[1].format(value),current[2],current[3])
  504. self.get_content(current)
  505. def get_content(self,current):
  506. self.history.append(self.cur_menu)
  507. self.cur_menu = current
  508. try:
  509. new_content = self.sources.get_content(self.cur_menu[1])
  510. except Exception,e:
  511. self.cur_menu = self.history.pop()
  512. self.session. open(MessageBox, "Error - %s"%str(e) , MessageBox.TYPE_INFO)
  513. return
  514. self.setTitle2(self.cur_menu[0])
  515. self.show_content(new_content)
  516. def Back(self):
  517. self["list"].setIndex(0)
  518. self.Ok()
  519. def show_content(self,content,index=0):
  520. self["list"].setList(content)
  521. self["list"].setIndex(index)
  522. self.SelectionChanged()
  523. def Cancel(self):
  524. #if os.path.exists(TMPDIR):
  525. #for name in os.listdir(TMPDIR):
  526. #os.remove(os.path.join(TMPDIR, name))
  527. #os.rmdir(TMPDIR)
  528. self.close()
  529. def item_menu(self):
  530. print "\n[PlayStream] options\n"
  531. self.current = self["list"].getCurrent()
  532. self.index = self["list"].getIndex()
  533. #self.session. open(MessageBox, "Item options - %s"%current[0] , MessageBox.TYPE_INFO)
  534. #args=[current,self.cur_menu]
  535. #self.session.open(ItemMenuScreen,current,index,self)
  536. lst = [
  537. ("Aditional information","info","Display additional information about item"),
  538. ("Add to bouquet","bouquet","Add current item to Enigma2 bouquet"),
  539. ("Add to favorites","favorites","Add current item to PlayStrem favorites"),
  540. ("Show active downloads","download_list","Show active downloads list"),
  541. ("Set download folder","download_folder","Set download folder")
  542. ]
  543. if self.sources.is_video(self.current[1]):
  544. lst.extend([
  545. ("Download video","download","Download video in background"),
  546. ])
  547. else:
  548. lst.extend([
  549. ("Download videos in folder","download","Download videos in folder (if any)"),
  550. ])
  551. if "config::" in self.cur_menu[1]:
  552. lst.extend([
  553. ("Rename item","rename","Rename list item"),
  554. ("Move item","move","Move list item"),
  555. ("Delete item","delete","Delete list item"),
  556. ("Add submenu","add_list","Add submenu before selected item"),
  557. ])
  558. title = self.current[0]
  559. self.session.openWithCallback(self.cb_item_menu, ChoiceBox, title = title, list = lst) #TODO
  560. def cb_item_menu(self,answer):
  561. #print "item_menu_selected",answer
  562. if not answer:
  563. return
  564. if answer[1] == "info":
  565. self.session.open(MessageBox, "Not yet implemented!", MessageBox.TYPE_INFO)
  566. pass # TODO parada papildus info
  567. elif answer[1] == "bouquet":
  568. #if not e2:
  569. #e2 = enigma2_api.DBServices()
  570. #print "load_buuquets - ",e2._load_bouquets()
  571. self.session.open(MessageBox, "Not yet implemented!", MessageBox.TYPE_INFO)
  572. elif answer[1] == "favorites":
  573. lists = self.config.get_lists()
  574. lists2 = [(l,l) for l in lists]
  575. self.session.openWithCallback(self.cb_favorites, ChoiceBox, title="Selected menu item will be added",list = lists2)
  576. elif answer[1] == 'download':
  577. current = self.current
  578. if not self.sources.is_video(current[1]):
  579. #self.msg("Can not download listst (yet) - %s"%(current[1]))
  580. n = 0
  581. for current2 in self.sources.get_content(current[1]):
  582. if self.sources.is_video(current2[1]):
  583. n += 1
  584. self.download_video(current2)
  585. if n>0:
  586. self.msg("%s videos download started"%n)
  587. else:
  588. self.msg("No videos to download")
  589. else:
  590. if self.download_video(current):
  591. self.msg("Video download started")
  592. elif answer[1] == 'download_list':
  593. self.download_list()
  594. elif answer[1] == 'download_folder':
  595. #downloadDir = "/media/hdd/movie" #config.plugins.playstream.downloadDir.value TODO
  596. self.session.openWithCallback(self.select_download_dir, LocationBox,"Select download folder","",config.playstream.download_dir.value,config.playstream.locations,False,"Select folder",None,True,True)
  597. elif answer[1] == "delete":
  598. lst = self.cur_menu[1].replace("config::","")
  599. #print lst
  600. self.config.del_item(lst,self.index)
  601. self.config.write_streams()
  602. txt = "'%s' deleted from favourite stream list '%s'"%(self.current[0],lst)
  603. self.session.open(MessageBox, txt, MessageBox.TYPE_INFO,timeout=5)
  604. elif answer[1] == "rename":
  605. #name2 = "Renamed"
  606. self.session.openWithCallback(self.cb_rename,VirtualKeyBoard, title="Enter new item name", text=self.current[0])
  607. elif answer[1] == "add_list":
  608. self.session.open(MessageBox, "Not yet implemented!", MessageBox.TYPE_INFO,timeout=5)
  609. pass #TODO
  610. return
  611. def select_download_dir(self, downloadDir, select=None):
  612. if not downloadDir:
  613. return
  614. print "Folder selected - %s"%downloadDir
  615. config.playstream.download_dir.setValue(downloadDir)
  616. config.playstream.download_dir.save()
  617. config.playstream.locations.save()
  618. config.save()
  619. def download_list(self):
  620. self.session.open(VideoDownloadList)
  621. def download_video(self,current):
  622. if self.sources.stream_type(current[1]):
  623. stream = stream0.copy()
  624. stream["url"] = current[1]
  625. stream["name"] = current[0]
  626. streams = [stream]
  627. else:
  628. try:
  629. streams = self.sources.get_streams(current[1])
  630. except Exception,e:
  631. print "Error - %s"%str(e)
  632. self.session. open(MessageBox, "Error - %s"%str(e) , MessageBox.TYPE_INFO)
  633. return
  634. if not streams:
  635. self.msg("No stream found to download - %s"%(self.current[1]))
  636. return
  637. for s in streams:
  638. if not s["name"]: s["name"] = current[0]
  639. if not s["img"]: s["img"] = current[2]
  640. if not s["desc"]: s["desc"] = current[3]
  641. if len(streams)>1:
  642. stream = streams[0] # TODO iespeja izvelēties strīmu, ja to ir vairāki
  643. else:
  644. stream = streams[0]
  645. return self.download_stream(stream)
  646. def download_stream(self,stream):
  647. print "download stream",stream
  648. #self.msg("Start downloading..")
  649. self.stream = stream
  650. stream_type = self.stream["type"] #self.sources.stream_type(stream["url"])
  651. if not stream_type: #
  652. print "Not supported stream type found to download - %s"%(self.current[1])
  653. self.msg("Not supported stream type found to download - %s"%(self.current[1]))
  654. return
  655. title = self.stream["name"].strip()
  656. url = self.stream["url"]
  657. stream_type = self.stream["type"] #self.sources.stream_type(stream["url"])
  658. downloadDir = config.playstream.download_dir.value
  659. if not os.path.exists(downloadDir):
  660. print 'Sorry, download directory "%s" not exist!\nPlease specify in the settings existing directory'%downloadDir
  661. self.msg0(_('Sorry, download directory "%s" not exist!\nPlease specify in the settings existing directory'%downloadDir))
  662. return
  663. fname0 = re.sub("[/\n\r\t,:]"," ",title)
  664. fname0 = re.sub("['""]","",fname0)
  665. fname = fname0 +".mp4"
  666. outputfile = os.path.join(downloadDir, fname)
  667. #print "Trying to download - ", current
  668. if self.stream["subs"]:
  669. suburl = self.stream["subs"][0]["url"]
  670. print "\n**Download subtitles %s - %s"%(title,suburl)
  671. subs = urllib2.urlopen(suburl).read()
  672. if subs:
  673. #fname0 = re.sub("[/\n\r\t,:]"," ",title)
  674. subext = ".srt"
  675. subfile = os.path.join(downloadDir,fname0+subext)
  676. if ".xml" in suburl:
  677. subs = util.ttaf2srt(subs)
  678. with open(subfile,"w") as f:
  679. f.write(subs)
  680. else:
  681. print "\n Error downloading subtitle %s"%suburl
  682. if os.path.exists(outputfile):
  683. self.msg( _('Sorry, this file already exists:\n%s') % outputfile)
  684. return False
  685. #os.remove(outputfile)
  686. if stream_type in ("http","https"):
  687. print "\n**Download %s - %s"%(title,url)
  688. #reload(downloadJob)
  689. job_manager.AddJob(downloadJob(url, outputfile, title[:20], self.video_download_stop))
  690. self.activeDownloads += 1
  691. #self.msg(_('Video download started!'))
  692. return True
  693. elif stream_type == "hls":
  694. #self.msg("HLS stream download not yet implemented!")
  695. print "\n**Download %s - %s"%(title,url)
  696. #reload(HLSDownloadJob)
  697. print "HLSDownload", url,outputfile
  698. job_manager.AddJob(HLSDownloadJob(url, outputfile, title[:20], self.video_download_stop))
  699. self.activeDownloads += 1
  700. #self.msg(_('Video download started!'))
  701. return True
  702. elif stream_type == "rstp":
  703. self.msg("RSTP stream download not yet implemented!")
  704. return False
  705. else:
  706. self.msg("Unkown stream type!")
  707. return False
  708. def cb_rename(self,value):
  709. if not value:
  710. return
  711. lst = self.cur_menu[1].replace("config::","")
  712. pos = self.index
  713. print value
  714. item2 = list(self.current)
  715. item2[0]=value
  716. item2 = tuple(item2)
  717. self.config.replace_item(lst,item2,pos)
  718. self.config.write_streams()
  719. txt = "'%s' renamed to '%s'"%(self.current[0],value)
  720. self.session.open(MessageBox, txt, MessageBox.TYPE_INFO,timeout=5)
  721. def cb_favorites(self,answer):
  722. print "cb_favorites",answer,self.current
  723. if not answer:
  724. return
  725. value = answer[1]
  726. self.config.add_item(value,self.current)
  727. self.config.write_streams()
  728. txt = "'%s' added to favourite stream list '%s'"%(self.current[0],value)
  729. self.session.open(MessageBox, txt, MessageBox.TYPE_INFO,timeout=3)
  730. #self.session.openWithCallback(self.callMyMsg, MessageBox, _("Do you want to exit the plugin?"), MessageBox.TYPE_INFO)
  731. def options_screen(self):
  732. source = self.cur_menu[1].split("::")[0]
  733. options = self.sources.options_read(source)
  734. print source
  735. if not options:
  736. self.session. open(MessageBox, "No options available for source %s (%s)"%(self.cur_menu[0],source) , MessageBox.TYPE_INFO)
  737. else:
  738. self.session.open(OptionsScreen,self)
  739. def video_download_stop(self,title):
  740. #self.activeDownloads -= 1
  741. #self.msg("Download '%s'finished!"%title)
  742. print "video_download_stop ", title
  743. def msg2(self,msg,timeout=10,mtype = None):
  744. mtype=mtype if mtype else MessageBox.TYPE_INFO
  745. Notifications.AddPopup(text = msg, type=mtype, timeout=timeout)
  746. def msg(self,msg,timeout=10):
  747. self.session.open(MessageBox, msg, MessageBox.TYPE_INFO, timeout)
  748. ##########################################################################
  749. from Components.config import config, ConfigSubsection, ConfigYesNo,\
  750. getConfigListEntry, ConfigSelection, ConfigNumber, ConfigDirectory,ConfigText, ConfigSubDict
  751. from Components.ConfigList import ConfigListScreen
  752. #from Screens.LocationBox import LocationBox
  753. config.plugins.playstream = ConfigSubDict()
  754. class OptionsScreen(ConfigListScreen,Screen):
  755. skin = """
  756. <screen position="center,center" size="560,400" >
  757. <ePixmap name="red" position="0,0" zPosition="2" size="140,40" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
  758. <widget name="key_red" position="0,0" size="140,40" valign="center" halign="center" zPosition="4" foregroundColor="white" font="Regular;20" transparent="1" shadowColor="background" shadowOffset="-2,-2" />
  759. <ePixmap name="green" position="140,0" zPosition="2" size="140,40" pixmap="skin_default/buttons/green.png" transparent="1" alphatest="on" />
  760. <widget name="key_green" position="140,0" size="140,40" valign="center" halign="center" zPosition="4" foregroundColor="white" font="Regular;20" transparent="1" shadowColor="background" shadowOffset="-2,-2" />
  761. <ePixmap name="yellow" position="280,0" zPosition="2" size="140,40" pixmap="skin_default/buttons/yellow.png" transparent="1" alphatest="on" />
  762. <widget name="key_yellow" position="280,0" size="140,40" valign="center" halign="center" zPosition="4" foregroundColor="white" font="Regular;20" transparent="1" shadowColor="background" shadowOffset="-2,-2" />
  763. <ePixmap name="blue" position="420,0" zPosition="2" size="140,40" pixmap="skin_default/buttons/blue.png" transparent="1" alphatest="on" />
  764. <widget name="key_blue" position="420,0" size="140,40" valign="center" halign="center" zPosition="4" foregroundColor="white" font="Regular;20" transparent="1" shadowColor="background" shadowOffset="-2,-2" />
  765. <widget name="config" position="10,40" size="540,340" scrollbarMode="showOnDemand" />
  766. </screen>"""
  767. def __init__(self, session,*args):
  768. self.session = session
  769. Screen.__init__(self, session)
  770. self.main = args[0]
  771. self.setTitle(self.main.cur_menu[0]+" options")
  772. self.source = self.main.cur_menu[1].split("::")[0]
  773. self.cfg = config.plugins.playstream
  774. self.list = []
  775. self.options = self.main.sources.options_read(self.source)
  776. if not self.options:
  777. #self.session. open(MessageBox, "No options available for source %s (%s)"%(self.main.cur_menu[0],self.source) , MessageBox.TYPE_INFO)
  778. self.close(False,self.session)
  779. for k in self.options:
  780. self.cfg[k]=ConfigText(default=self.options[k],fixed_size=False)
  781. self.list.append(getConfigListEntry(k, self.cfg[k]))
  782. ConfigListScreen.__init__(self, self.list, session = self.session)
  783. self["key_red"] = Button(_("Cancel"))
  784. self["key_green"] = Button("Save")
  785. self["key_yellow"] = Button("")
  786. self["key_blue"] = Button("")
  787. self["setupActions"] = ActionMap(["SetupActions", "ColorActions"],
  788. {
  789. "red": self.cancel,
  790. "green": self.save,
  791. "save": self.save,
  792. "cancel": self.cancel,
  793. "ok": self.ok,
  794. }, -2)
  795. def getCurrentEntry(self):
  796. return self["config"].getCurrent()[0]
  797. def getCurrentValue(self):
  798. return str(self["config"].getCurrent()[1].getText())
  799. def ok(self):
  800. self.save()
  801. #if self["config"].getCurrent()[1] == config.plugins.getpicons.folder:
  802. #folder = config.plugins.getpicons.folder.value
  803. #self.session.openWithCallback(self.change_dir, LocationBox,"Select Folder")
  804. #else:
  805. #def change_dir(self, folder, select=None):
  806. #if folder:
  807. ##print "change_dir to %s"%folder
  808. #config.plugins.getpicons.folder.value = folder
  809. def save(self):
  810. print "saving"
  811. #self.saveAll()
  812. for k in self.options.keys():
  813. self.options[k]=self.cfg[k].value
  814. print "%s=%s"%(k,self.cfg[k].value)
  815. self.main.sources.options_write(self.source,self.options)
  816. self.close(True,self.session)
  817. def cancel(self):
  818. print "cancel"
  819. self.close(False,self.session)