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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  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.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,310" size="400,250" halign="center" font="Regular;20"/>
  304. <ePixmap name="red" position="100,530" zPosition="2" size="140,40" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
  305. <widget name="key_red" position="100,530" size="140,40" valign="center" halign="center" zPosition="4" foregroundColor="white" font="Regular;20" transparent="1" shadowColor="background" shadowOffset="-2,-2" />
  306. <ePixmap name="green" position="240,530" zPosition="2" size="140,40" pixmap="skin_default/buttons/green.png" transparent="1" alphatest="on" />
  307. <widget name="key_green" position="240,530" size="140,40" valign="center" halign="center" zPosition="4" foregroundColor="white" font="Regular;20" transparent="1" shadowColor="background" shadowOffset="-2,-2" />
  308. <ePixmap name="yellow" position="380,530" zPosition="2" size="140,40" pixmap="skin_default/buttons/yellow.png" transparent="1" alphatest="on" />
  309. <widget name="key_yellow" position="380,530" size="140,40" valign="center" halign="center" zPosition="4" foregroundColor="white" font="Regular;20" transparent="1" shadowColor="background" shadowOffset="-2,-2" />
  310. <ePixmap name="menu" position="560,535" zPosition="2" size="140,40" pixmap="skin_default/buttons/key_menu.png" transparent="1" alphatest="on" />
  311. <widget name="key_menu" position="560,530" size="140,40" valign="center" halign="center" zPosition="4" backgroundColor="blue" foregroundColor="white" font="Regular;20" transparent="1" shadowColor="background" shadowOffset="-2,-2" />
  312. </screen>"""
  313. def __init__(self, session):
  314. Screen.__init__(self, session)
  315. #self.setTitle2("Home")
  316. self.session = session
  317. self.e2 = None
  318. self["key_red"] = Button(_("Back"))
  319. self["key_green"] = Button(_("Select"))
  320. self["key_yellow"] = Button(_("Options"))
  321. self["key_menu"] = Button("Menu" )
  322. self["actions"] = ActionMap(["OkCancelActions", "ColorActions","MenuActions", "NumberActions"],
  323. {
  324. "cancel": self.Cancel,
  325. "ok": self.Ok,
  326. "green": self.Ok,
  327. "red": self.Back,
  328. "yellow": self.options_screen,
  329. "blue": self.download_list,
  330. "menu": self.item_menu,
  331. })
  332. self["list"] = List([])
  333. self["list"].onSelectionChanged.append(self.SelectionChanged)
  334. self["pic"] = Pixmap()
  335. self["cur"] = Label()
  336. self["title"] = Label()
  337. self.downloading = 0
  338. self.activeDownloads = 0
  339. if not os.path.exists(TMPDIR):
  340. os.mkdir(TMPDIR)
  341. self.onLayoutFinish.append(self.LayoutFinish)
  342. def LayoutFinish(self):
  343. self.cur_directory = os.path.dirname(os.path.realpath(__file__))
  344. self.defimage = LoadPixmap(os.path.join(self.cur_directory,"PlayStream.png"))
  345. #self.defimage = None
  346. #sc = AVSwitch().getFramebufferScale()
  347. #self.defimage0 = ePicLoad()
  348. #self.defimage0.PictureData.get().append(boundFunction(self.FinishDecodeDef, os.path.join(self.cur_directory,"PlayStream.png")))
  349. #self.defimage0.setPara((self["pic"].instance.size().width(),self["pic"].instance.size().height(),sc[0], sc[1], False, 0, "#00000000"))
  350. #self.defimage0.startDecode("default")
  351. self.activeDownloads = 0
  352. self.images = {}
  353. self.images_url = {}
  354. self.picloads = {}
  355. self.history = []
  356. reload(ContentSources)
  357. self.sources = ContentSources.ContentSources(os.path.join(self.cur_directory,"sources"))
  358. self.config = self.sources.plugins["config"]
  359. self.cur_menu = ("Home","config::home","","Sākums") #
  360. self.content = self.sources.get_content(self.cur_menu[1])
  361. #print self.content
  362. self["list"].setList(self.content)
  363. self["cur"].setText(self.content[0][3])
  364. self.setTitle2(self.cur_menu[0])
  365. self.ShowPic(self.content[0][2])
  366. def SelectionChanged(self):
  367. current = self["list"].getCurrent()
  368. print "[PlayStream] SelectionChanged: current=",current
  369. if not current: return
  370. self["cur"].setText(current[3]) if current[3] else self["cur"].setText("")
  371. if current[2]:
  372. self.ShowPic(current[2])
  373. else:
  374. self.ShowDefPic()
  375. def setTitle2(self,title):
  376. #print self.keys()
  377. self["title"].setText(title)
  378. def ShowDefPic(self):
  379. if self.defimage:
  380. self["pic"].instance.setPixmap(self.defimage)
  381. def ShowPic(self,image_url):
  382. if image_url == "default":
  383. self.ShowDefPic()
  384. return
  385. elif self.images.has_key(image_url):
  386. if self.images[image_url] in (-1,-2):
  387. return
  388. elif self.images[image_url] == -3:
  389. self.ShowDefPic()
  390. return
  391. else:
  392. self["pic"].instance.setPixmap(self.images[image_url])
  393. else:
  394. if image_url.startswith("http"):
  395. fname = image_url.replace(":","-").replace("/","_")
  396. image_path = os.path.join(TMPDIR, fname)
  397. self.download_image(image_path, image_url)
  398. else: # local file
  399. image_path = os.path.join(self.cur_directory,image_url)
  400. self.start_decode(image_path,image_url)
  401. def start_decode(self,image_path,image_url):
  402. self.images[image_url] = -2
  403. self.images_url[image_path] = image_url
  404. sc = AVSwitch().getFramebufferScale()
  405. if not self.picloads.has_key(image_path):
  406. self.picloads[image_path] = ePicLoad()
  407. self.picloads[image_path].PictureData.get().append(boundFunction(self.FinishDecode, image_path))
  408. self.picloads[image_path].setPara((self["pic"].instance.size().width(),
  409. self["pic"].instance.size().height(),
  410. sc[0], sc[1], True, 0, "#00000000"))
  411. #print image_path,image_url
  412. self.picloads[image_path].startDecode(image_path)
  413. def FinishDecode(self, image_path,picInfo = None):
  414. image_url = self.images_url[image_path]
  415. del self.images_url[image_path] #III
  416. self.images[image_url] = self.picloads[image_path].getData()
  417. self["pic"].instance.setPixmap(self.images[image_url])
  418. del self.picloads[image_path]
  419. if len(self.images)>30:
  420. del self.images[self.images.keys()[0]]
  421. # self.images.pop()
  422. #def FinishDecodeDef(self, image_path,picInfo = None):
  423. # self.defimage = self.defimage0.getData()
  424. # del self.defimage0
  425. # self["pic"].instance.setPixmap(self.defimage)
  426. def download_image(self,image_path,image_url):
  427. #print "Image download started",self.downloading,image_path,image_url
  428. self.downloading += 1
  429. self.images[image_url] = -1
  430. downloadPage(image_url, image_path).addCallback(boundFunction(self.downloadFinished, image_path,image_url)).addErrback(boundFunction(self.downloadFailed, image_path,image_url))
  431. def downloadFinished(self, image_path, image_url, result):
  432. self.downloading -= 1
  433. #print "[ Play] Image downloaded finished ",self.downloading,image_path, image_url,result
  434. self.start_decode(image_path,image_url)
  435. def downloadFailed(self, image_path, image_url,result):
  436. self.downloading -= 1
  437. print "[TV Play] Image downloaded failed ",self.downloading,image_path, image_url,result
  438. self.images[image_url] = -3
  439. def Ok(self):
  440. current = self["list"].getCurrent()
  441. self.current = current
  442. index = self["list"].getIndex()
  443. self.index = index
  444. print "[PlayStream] - menu selected ", current
  445. data = current[1].split("::")[1] if "::" in current[1] else current[1]
  446. if not data:
  447. return
  448. elif self.sources.is_video(current[1]):
  449. if self.sources.stream_type(current[1]):
  450. stream = stream0.copy()
  451. stream["url"] = current[1]
  452. stream["name"] = current[0]
  453. streams = [stream]
  454. else:
  455. try:
  456. streams = self.sources.get_streams(current[1])
  457. except Exception,e:
  458. print str(e)
  459. self.session. open(MessageBox, "Error - %s"%str(e) , MessageBox.TYPE_INFO)
  460. return
  461. if streams:
  462. #print streams
  463. for s in streams:
  464. if not s["name"]: s["name"] = current[0]
  465. if not s["img"]: s["img"] = current[2]
  466. if not s["desc"]: s["desc"] = current[3]
  467. try:
  468. self.session.open(PSPlayer, streams)
  469. except Exception as e:
  470. self.msg2("Error launching player - " + str(e))
  471. return
  472. else:
  473. self.msg("No stream found - %s"%(self.current[1]))
  474. return
  475. elif current[1] == "back":
  476. cur_menu_old = self.cur_menu
  477. self.cur_menu = self.history.pop()
  478. new_content = self.sources.get_content(self.cur_menu[1])
  479. try:
  480. index = zip(*new_content)[1].index(cur_menu_old[1])
  481. except:
  482. index = 0
  483. self.setTitle2(self.cur_menu[0])
  484. self.show_content(new_content,index)
  485. else:
  486. print "selected=",current
  487. if "{0}" in current[1]:
  488. self.session.openWithCallback(self.cb_input,VirtualKeyBoard, title="Enter value", text="")
  489. #a = raw_input("Enter value:")
  490. #a = "big bang"
  491. #current = (current[0],current[1].format(a),current[2],current[3])
  492. #self.get_content(current)
  493. else:
  494. self.get_content(current)
  495. def cb_input(self,value):
  496. if not value:
  497. return
  498. current = self.current
  499. current = (current[0],current[1].format(value),current[2],current[3])
  500. self.get_content(current)
  501. def get_content(self,current):
  502. self.history.append(self.cur_menu)
  503. self.cur_menu = current
  504. try:
  505. new_content = self.sources.get_content(self.cur_menu[1])
  506. except Exception,e:
  507. self.cur_menu = self.history.pop()
  508. self.session. open(MessageBox, "Error - %s"%str(e) , MessageBox.TYPE_INFO)
  509. return
  510. self.setTitle2(self.cur_menu[0])
  511. self.show_content(new_content)
  512. def Back(self):
  513. self["list"].setIndex(0)
  514. self.Ok()
  515. def show_content(self,content,index=0):
  516. self["list"].setList(content)
  517. self["list"].setIndex(index)
  518. self.SelectionChanged()
  519. def Cancel(self):
  520. #if os.path.exists(TMPDIR):
  521. #for name in os.listdir(TMPDIR):
  522. #os.remove(os.path.join(TMPDIR, name))
  523. #os.rmdir(TMPDIR)
  524. self.close()
  525. def item_menu(self):
  526. print "\n[PlayStream] options\n"
  527. self.current = self["list"].getCurrent()
  528. self.index = self["list"].getIndex()
  529. #self.session. open(MessageBox, "Item options - %s"%current[0] , MessageBox.TYPE_INFO)
  530. #args=[current,self.cur_menu]
  531. #self.session.open(ItemMenuScreen,current,index,self)
  532. lst = [
  533. ("Aditional information","info","Display additional information about item"),
  534. ("Add to bouquet","bouquet","Add current item to Enigma2 bouquet"),
  535. ("Add to favorites","favorites","Add current item to PlayStrem favorites"),
  536. ("Show active downloads","download_list","Show active downloads list"),
  537. ("Set download folder","download_folder","Set download folder")
  538. ]
  539. if self.sources.is_video(self.current[1]):
  540. lst.extend([
  541. ("Download video","download","Download video in background"),
  542. ])
  543. else:
  544. lst.extend([
  545. ("Download videos in folder","download","Download videos in folder (if any)"),
  546. ])
  547. if "config::" in self.cur_menu[1]:
  548. lst.extend([
  549. ("Rename item","rename","Rename list item"),
  550. ("Move item","move","Move list item"),
  551. ("Delete item","delete","Delete list item"),
  552. ("Add submenu","add_list","Add submenu before selected item"),
  553. ])
  554. title = self.current[0]
  555. self.session.openWithCallback(self.cb_item_menu, ChoiceBox, title = title, list = lst) #TODO
  556. def cb_item_menu(self,answer):
  557. #print "item_menu_selected",answer
  558. if not answer:
  559. return
  560. if answer[1] == "info":
  561. self.session.open(MessageBox, "Not yet implemented!", MessageBox.TYPE_INFO)
  562. pass # TODO parada papildus info
  563. elif answer[1] == "bouquet":
  564. #if not e2:
  565. #e2 = enigma2_api.DBServices()
  566. #print "load_buuquets - ",e2._load_bouquets()
  567. self.session.open(MessageBox, "Not yet implemented!", MessageBox.TYPE_INFO)
  568. elif answer[1] == "favorites":
  569. lists = self.config.get_lists()
  570. lists2 = [(l,l) for l in lists]
  571. self.session.openWithCallback(self.cb_favorites, ChoiceBox, title="Selected menu item will be added",list = lists2)
  572. elif answer[1] == 'download':
  573. current = self.current
  574. if not self.sources.is_video(current[1]):
  575. #self.msg("Can not download listst (yet) - %s"%(current[1]))
  576. n = 0
  577. for current2 in self.sources.get_content(current[1]):
  578. if self.sources.is_video(current2[1]):
  579. n += 1
  580. self.download_video(current2)
  581. if n>0:
  582. self.msg("%s videos download started"%n)
  583. else:
  584. self.msg("No videos to download")
  585. else:
  586. if self.download_video(current):
  587. self.msg("Video download started")
  588. elif answer[1] == 'download_list':
  589. self.download_list()
  590. elif answer[1] == 'download_folder':
  591. #downloadDir = "/media/hdd/movie" #config.plugins.playstream.downloadDir.value TODO
  592. 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)
  593. elif answer[1] == "delete":
  594. lst = self.cur_menu[1].replace("config::","")
  595. #print lst
  596. self.config.del_item(lst,self.index)
  597. self.config.write_streams()
  598. txt = "'%s' deleted from favourite stream list '%s'"%(self.current[0],lst)
  599. self.session.open(MessageBox, txt, MessageBox.TYPE_INFO,timeout=5)
  600. elif answer[1] == "rename":
  601. #name2 = "Renamed"
  602. self.session.openWithCallback(self.cb_rename,VirtualKeyBoard, title="Enter new item name", text=self.current[0])
  603. elif answer[1] == "add_list":
  604. self.session.open(MessageBox, "Not yet implemented!", MessageBox.TYPE_INFO,timeout=5)
  605. pass #TODO
  606. return
  607. def select_download_dir(self, downloadDir, select=None):
  608. if not downloadDir:
  609. return
  610. print "Folder selected - %s"%downloadDir
  611. config.playstream.download_dir.setValue(downloadDir)
  612. config.playstream.download_dir.save()
  613. config.playstream.locations.save()
  614. config.save()
  615. def download_list(self):
  616. self.session.open(VideoDownloadList)
  617. def download_video(self,current):
  618. if self.sources.stream_type(current[1]):
  619. stream = stream0.copy()
  620. stream["url"] = current[1]
  621. stream["name"] = current[0]
  622. streams = [stream]
  623. else:
  624. try:
  625. streams = self.sources.get_streams(current[1])
  626. except Exception,e:
  627. print "Error - %s"%str(e)
  628. self.session. open(MessageBox, "Error - %s"%str(e) , MessageBox.TYPE_INFO)
  629. return
  630. if not streams:
  631. self.msg("No stream found to download - %s"%(self.current[1]))
  632. return
  633. for s in streams:
  634. if not s["name"]: s["name"] = current[0]
  635. if not s["img"]: s["img"] = current[2]
  636. if not s["desc"]: s["desc"] = current[3]
  637. if len(streams)>1:
  638. stream = streams[0] # TODO iespeja izvelēties strīmu, ja to ir vairāki
  639. else:
  640. stream = streams[0]
  641. return self.download_stream(stream)
  642. def download_stream(self,stream):
  643. print "download stream",stream
  644. #self.msg("Start downloading..")
  645. self.stream = stream
  646. stream_type = self.stream["type"] #self.sources.stream_type(stream["url"])
  647. if not stream_type: #
  648. print "Not supported stream type found to download - %s"%(self.current[1])
  649. self.msg("Not supported stream type found to download - %s"%(self.current[1]))
  650. return
  651. title = self.stream["name"].strip()
  652. url = self.stream["url"]
  653. stream_type = self.stream["type"] #self.sources.stream_type(stream["url"])
  654. downloadDir = config.playstream.download_dir.value
  655. if not os.path.exists(downloadDir):
  656. print 'Sorry, download directory "%s" not exist!\nPlease specify in the settings existing directory'%downloadDir
  657. self.msg0(_('Sorry, download directory "%s" not exist!\nPlease specify in the settings existing directory'%downloadDir))
  658. return
  659. fname0 = re.sub("[/\n\r\t,:]"," ",title)
  660. fname0 = re.sub("['""]","",fname0)
  661. fname = fname0 +".mp4"
  662. outputfile = os.path.join(downloadDir, fname)
  663. #print "Trying to download - ", current
  664. if self.stream["subs"]:
  665. suburl = self.stream["subs"][0]["url"]
  666. print "\n**Download subtitles %s - %s"%(title,suburl)
  667. subs = urllib2.urlopen(suburl).read()
  668. if subs:
  669. #fname0 = re.sub("[/\n\r\t,:]"," ",title)
  670. subext = ".srt"
  671. subfile = os.path.join(downloadDir,fname0+subext)
  672. if ".xml" in suburl:
  673. subs = util.ttaf2srt(subs)
  674. with open(subfile,"w") as f:
  675. f.write(subs)
  676. else:
  677. print "\n Error downloading subtitle %s"%suburl
  678. if os.path.exists(outputfile):
  679. self.msg( _('Sorry, this file already exists:\n%s') % outputfile)
  680. return False
  681. #os.remove(outputfile)
  682. if stream_type in ("http","https"):
  683. print "\n**Download %s - %s"%(title,url)
  684. #reload(downloadJob)
  685. job_manager.AddJob(downloadJob(url, outputfile, title[:20], self.video_download_stop))
  686. self.activeDownloads += 1
  687. #self.msg(_('Video download started!'))
  688. return True
  689. elif stream_type == "hls":
  690. #self.msg("HLS stream download not yet implemented!")
  691. print "\n**Download %s - %s"%(title,url)
  692. #reload(HLSDownloadJob)
  693. print "HLSDownload", url,outputfile
  694. job_manager.AddJob(HLSDownloadJob(url, outputfile, title[:20], self.video_download_stop))
  695. self.activeDownloads += 1
  696. #self.msg(_('Video download started!'))
  697. return True
  698. elif stream_type == "rstp":
  699. self.msg("RSTP stream download not yet implemented!")
  700. return False
  701. else:
  702. self.msg("Unkown stream type!")
  703. return False
  704. def cb_rename(self,value):
  705. if not value:
  706. return
  707. lst = self.cur_menu[1].replace("config::","")
  708. pos = self.index
  709. print value
  710. item2 = list(self.current)
  711. item2[0]=value
  712. item2 = tuple(item2)
  713. self.config.replace_item(lst,item2,pos)
  714. self.config.write_streams()
  715. txt = "'%s' renamed to '%s'"%(self.current[0],value)
  716. self.session.open(MessageBox, txt, MessageBox.TYPE_INFO,timeout=5)
  717. def cb_favorites(self,answer):
  718. print "cb_favorites",answer,self.current
  719. if not answer:
  720. return
  721. value = answer[1]
  722. self.config.add_item(value,self.current)
  723. self.config.write_streams()
  724. txt = "'%s' added to favourite stream list '%s'"%(self.current[0],value)
  725. self.session.open(MessageBox, txt, MessageBox.TYPE_INFO,timeout=3)
  726. #self.session.openWithCallback(self.callMyMsg, MessageBox, _("Do you want to exit the plugin?"), MessageBox.TYPE_INFO)
  727. def options_screen(self):
  728. source = self.cur_menu[1].split("::")[0]
  729. options = self.sources.options_read(source)
  730. print source
  731. if not options:
  732. self.session. open(MessageBox, "No options available for source %s (%s)"%(self.cur_menu[0],source) , MessageBox.TYPE_INFO)
  733. else:
  734. self.session.open(OptionsScreen,self)
  735. def video_download_stop(self,title):
  736. #self.activeDownloads -= 1
  737. #self.msg("Download '%s'finished!"%title)
  738. print "video_download_stop ", title
  739. def msg2(self,msg,timeout=10,mtype = None):
  740. mtype=mtype if mtype else MessageBox.TYPE_INFO
  741. Notifications.AddPopup(text = msg, type=mtype, timeout=timeout)
  742. def msg(self,msg,timeout=10):
  743. self.session.open(MessageBox, msg, MessageBox.TYPE_INFO, timeout)
  744. ##########################################################################
  745. from Components.config import config, ConfigSubsection, ConfigYesNo,\
  746. getConfigListEntry, ConfigSelection, ConfigNumber, ConfigDirectory,ConfigText, ConfigSubDict
  747. from Components.ConfigList import ConfigListScreen
  748. #from Screens.LocationBox import LocationBox
  749. config.plugins.playstream = ConfigSubDict()
  750. class OptionsScreen(ConfigListScreen,Screen):
  751. skin = """
  752. <screen position="center,center" size="560,400" >
  753. <ePixmap name="red" position="0,0" zPosition="2" size="140,40" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
  754. <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" />
  755. <ePixmap name="green" position="140,0" zPosition="2" size="140,40" pixmap="skin_default/buttons/green.png" transparent="1" alphatest="on" />
  756. <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" />
  757. <ePixmap name="yellow" position="280,0" zPosition="2" size="140,40" pixmap="skin_default/buttons/yellow.png" transparent="1" alphatest="on" />
  758. <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" />
  759. <ePixmap name="blue" position="420,0" zPosition="2" size="140,40" pixmap="skin_default/buttons/blue.png" transparent="1" alphatest="on" />
  760. <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" />
  761. <widget name="config" position="10,40" size="540,340" scrollbarMode="showOnDemand" />
  762. </screen>"""
  763. def __init__(self, session,*args):
  764. self.session = session
  765. Screen.__init__(self, session)
  766. self.main = args[0]
  767. self.setTitle(self.main.cur_menu[0]+" options")
  768. self.source = self.main.cur_menu[1].split("::")[0]
  769. self.cfg = config.plugins.playstream
  770. self.list = []
  771. self.options = self.main.sources.options_read(self.source)
  772. if not self.options:
  773. #self.session. open(MessageBox, "No options available for source %s (%s)"%(self.main.cur_menu[0],self.source) , MessageBox.TYPE_INFO)
  774. self.close(False,self.session)
  775. for k in self.options:
  776. self.cfg[k]=ConfigText(default=self.options[k],fixed_size=False)
  777. self.list.append(getConfigListEntry(k, self.cfg[k]))
  778. ConfigListScreen.__init__(self, self.list, session = self.session)
  779. self["key_red"] = Button(_("Cancel"))
  780. self["key_green"] = Button("Save")
  781. self["key_yellow"] = Button("")
  782. self["key_blue"] = Button("")
  783. self["setupActions"] = ActionMap(["SetupActions", "ColorActions"],
  784. {
  785. "red": self.cancel,
  786. "green": self.save,
  787. "save": self.save,
  788. "cancel": self.cancel,
  789. "ok": self.ok,
  790. }, -2)
  791. def getCurrentEntry(self):
  792. return self["config"].getCurrent()[0]
  793. def getCurrentValue(self):
  794. return str(self["config"].getCurrent()[1].getText())
  795. def ok(self):
  796. self.save()
  797. #if self["config"].getCurrent()[1] == config.plugins.getpicons.folder:
  798. #folder = config.plugins.getpicons.folder.value
  799. #self.session.openWithCallback(self.change_dir, LocationBox,"Select Folder")
  800. #else:
  801. #def change_dir(self, folder, select=None):
  802. #if folder:
  803. ##print "change_dir to %s"%folder
  804. #config.plugins.getpicons.folder.value = folder
  805. def save(self):
  806. print "saving"
  807. #self.saveAll()
  808. for k in self.options.keys():
  809. self.options[k]=self.cfg[k].value
  810. print "%s=%s"%(k,self.cfg[k].value)
  811. self.main.sources.options_write(self.source,self.options)
  812. self.close(True,self.session)
  813. def cancel(self):
  814. print "cancel"
  815. self.close(False,self.session)