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

PlayStream.py 40KB

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