Python module (submodule repositary), which provides content (video streams) from various online stream sources to corresponding Enigma2, Kodi, Plex plugins

util.py 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  1. # -*- coding: UTF-8 -*-
  2. # /*
  3. # * Copyright (C) 2011 Libor Zoubek,ivars777
  4. # *
  5. # *
  6. # * This Program is free software; you can redistribute it and/or modify
  7. # * it under the terms of the GNU General Public License as published by
  8. # * the Free Software Foundation; either version 2, or (at your option)
  9. # * any later version.
  10. # *
  11. # * This Program is distributed in the hope that it will be useful,
  12. # * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # * GNU General Public License for more details.
  15. # *
  16. # * You should have received a copy of the GNU General Public License
  17. # * along with this program; see the file COPYING. If not, write to
  18. # * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  19. # * http://www.gnu.org/copyleft/gpl.html
  20. # *
  21. # */
  22. import os, sys, re
  23. import urllib, urllib2
  24. import datetime, time
  25. import traceback
  26. import cookielib
  27. import requests
  28. try:
  29. from requests.packages.urllib3.exceptions import InsecureRequestWarning
  30. requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
  31. except:
  32. pass
  33. from htmlentitydefs import name2codepoint as n2cp
  34. import HTMLParser
  35. import StringIO
  36. #import threading
  37. #import Queue
  38. import pickle
  39. import string
  40. import simplejson as json
  41. #from demjson import demjson
  42. #import demjson
  43. import json
  44. #from bs4 import BeautifulSoup
  45. UA = 'Mozilla/6.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.5) Gecko/2008092417 Firefox/3.0.3'
  46. LOG = 2
  47. _cookie_jar = None
  48. CACHE_COOKIES = 'cookies'
  49. def system():
  50. if "kodi" in sys.executable.lower():
  51. return "kodi"
  52. elif sys.platform == "win32":
  53. return "windows"
  54. elif sys.platform == "linux2":
  55. return "enigma2"
  56. else:
  57. return "unknown"
  58. def nfo2xml(nfo_dict):
  59. nfo_type,nfo = next(nfo_dict.iteritems())
  60. s= "<%s>\n"%nfo_type.encode("utf8")
  61. for k,v in nfo.iteritems():
  62. if isinstance(v,list):
  63. for v2 in v:
  64. if isinstance(v2,unicode): v2 = v2.encode("utf8")
  65. s += " <%s>%s</%s>\n"%(k.encode("utf8"), v2, k.encode("utf8"))
  66. else:
  67. if isinstance(v,unicode): v = v.encode("utf8")
  68. s += " <%s>%s</%s>\n"%(k.encode("utf8"), v, k.encode("utf8"))
  69. s += "</%s>\n"%nfo_type.encode("utf8")
  70. return s
  71. def nfo2desc(nfo):
  72. if not "title" in nfo:
  73. nfo_type, nfo = next(nfo.iteritems())
  74. desc = nfo2title(nfo)
  75. dd = lambda t: "\n" + nfo[t] if t in nfo and nfo[t] else ""
  76. dd2 = lambda t: "\n" + ",".join(nfo[t]) if t in nfo and nfo[t] else ""
  77. def ddd(t,title=""):
  78. if title:
  79. title = title + ": "
  80. if t in nfo and nfo[t]:
  81. if isinstance(nfo[t],list):
  82. d = "\n" + title + ",".join(nfo[t])
  83. else:
  84. d = "\n" + title + nfo[t]
  85. else:
  86. d = ""
  87. return d.encode("utf8") if isinstance(d, unicode) else d
  88. desc += ddd("tagline")
  89. if "plot" in nfo and "tagline" in nfo and nfo["tagline"] <> nfo["plot"]:
  90. desc += ddd("plot")
  91. elif "plot" in nfo and not "tagline" in nfo:
  92. desc += ddd("plot")
  93. desc += ddd("genre","Genre")
  94. desc += ddd("runtime","Length")
  95. desc += ddd("director","Director")
  96. desc += ddd("actor","Actors")
  97. desc += ddd("language","Languages")
  98. desc += ddd("quality","Quality")
  99. return desc.encode("utf8") if isinstance(desc,unicode) else desc
  100. def nfo2title(nfo):
  101. if not "title" in nfo:
  102. nfo_type, nfo = next(nfo.iteritems())
  103. title = nfo["title"]
  104. if "originaltitle" in nfo and nfo["originaltitle"] and nfo["originaltitle"]<>nfo["title"]:
  105. title +=" ~ "+nfo["originaltitle"]
  106. if "year" in nfo and nfo["year"]:
  107. title += " (%s)"%nfo["year"]
  108. return title.encode("utf8") if isinstance(title,unicode) else title
  109. def stream_type(data):
  110. data = data.lower()
  111. m = re.search(r"^(\w+)://", data)
  112. prefix = m.group(1) if m else ""
  113. if prefix in ("http","https"):
  114. if ".m3u8" in data:
  115. return "hls"
  116. elif ".mpd" in data:
  117. return "dash"
  118. else:
  119. return "http"
  120. else:
  121. return prefix
  122. def check_version(package,url="http://feed.blue.lv/Packages"):
  123. "Return current package version from OPKG feed"
  124. url = "http://feed.blue.lv/Packages"
  125. r = requests.get(url)
  126. if not r.ok:
  127. return ""
  128. m = re.search("Package: %s\nVersion: (.+?)\n"%package, r.content)
  129. if not m:
  130. return ""
  131. return m.group(1)
  132. SPLIT_CHAR = "~"
  133. SPLIT_CODE = urllib.quote(SPLIT_CHAR)
  134. EQ_CODE = urllib.quote("=")
  135. COL_CODE = urllib.quote(":")
  136. SPACE_CODE = urllib.quote(" ")
  137. def make_fname(title):
  138. "Make file name from title"
  139. title = title.strip()
  140. fname0 = re.sub("[/\n\r\t,:]"," ",title)
  141. fname0 = re.sub("['""]","",fname0)
  142. return fname0
  143. def hls_base(url):
  144. url2 = url.split("?")[0]
  145. url2 = "/".join(url2.split("/")[0:-1])+ "/"
  146. return url2
  147. def stream_change(stream):
  148. #return stream # TODO
  149. if "resolver" in stream and stream["resolver"] in ("viaplay","hqq","filmas") or \
  150. "surl" in stream and re.search("https*://(hqq|goo\.gl)",stream["surl"]):
  151. stream["url"] = streamproxy_encode(stream["url"],stream["headers"])
  152. stream["headers"] = {}
  153. return stream
  154. else:
  155. return stream
  156. def streamproxy_encode(url,headers=[],proxy_url=None):
  157. PROXY_URL = "http://localhost:8880/"
  158. if not "?" in url:
  159. url = url+"?"
  160. url2 = url.replace(SPLIT_CHAR,SPLIT_CODE).replace(":",COL_CODE).replace(" ",SPACE_CODE)
  161. if not proxy_url:
  162. proxy_url = PROXY_URL
  163. url2 = proxy_url + url2
  164. if headers:
  165. headers2 = []
  166. for h in headers:
  167. headers2.append("%s=%s"%(h,headers[h].replace("=",EQ_CODE).replace(SPLIT_CHAR,SPLIT_CODE).replace(" ",SPACE_CODE)))
  168. headers2 = SPLIT_CHAR.join(headers2)
  169. url2 = url2+SPLIT_CHAR+headers2
  170. #return url2.encode("utf8") if isinstance(url2,unicode) else url2
  171. return url2
  172. def streamproxy_decode(urlp):
  173. import urlparse
  174. path = urlp.replace(re.search("http://[^/]+",urlp).group(0),"")
  175. p = path.split(SPLIT_CHAR)
  176. url = urllib.unquote(p[0][1:])
  177. #headers = {"User-Agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/47.0.2526.70 Mobile/13C71 Safari/601.1.46"}
  178. headers={}
  179. if len(p)>1:
  180. for h in p[1:]:
  181. #h = urllib.unquote()
  182. headers[h.split("=")[0]]=urllib.unquote(h.split("=")[1])
  183. return url,headers
  184. def streamproxy_encode2(url,headers=[],proxy_url=None):
  185. PROXY_URL = "http://localhost:8880/"
  186. #url2 = url.replace(SPLIT_CHAR,SPLIT_CODE).replace(":",COL_CODE).replace(" ",SPACE_CODE)
  187. url2 = urllib.quote_plus(url)
  188. if not proxy_url:
  189. proxy_url = PROXY_URL
  190. url2 = proxy_url + url2+"/?"
  191. if headers:
  192. headers2 = []
  193. for h in headers:
  194. headers2.append("%s=%s"%(h,headers[h].replace("=",EQ_CODE).replace(SPLIT_CHAR,SPLIT_CODE).replace(" ",SPACE_CODE)))
  195. headers2 = SPLIT_CHAR.join(headers2)
  196. url2 = url2+SPLIT_CHAR+headers2
  197. return url2
  198. def streamproxy_decode2(urlp):
  199. path = urlp.replace(re.search("http://[^/]+",urlp).group(0),"")
  200. p = path.split(SPLIT_CHAR)
  201. url = urllib.unquote_plus(p[0][1:-2])
  202. #headers = {"User-Agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/47.0.2526.70 Mobile/13C71 Safari/601.1.46"}
  203. headers={}
  204. if len(p)>1:
  205. for h in p[1:]:
  206. #h = urllib.unquote()
  207. headers[h.split("=")[0]]=urllib.unquote(h.split("=")[1])
  208. return url,headers
  209. class Captions(object):
  210. def __init__(self,uri):
  211. self.uri = uri
  212. self.subs = []
  213. self.styles = {}
  214. if uri.startswith("http"):
  215. r = requests.get(uri)
  216. if r.status_code == 200:
  217. self.loads(r.content)
  218. def loads(self,s):
  219. if "WEBVTT" in s[:s.find("\n")]: # vtt captions
  220. self.load_vtt(s)
  221. elif "<?xml" in s[:s.find("\n")]:
  222. self.load_ttaf(s)
  223. else:
  224. self.load_vtt(s) # TODO
  225. def load_ttaf(self,s):
  226. for r2 in re.findall("<style .+?/>", s):
  227. st = {}
  228. for a in re.findall(r'(\w+)="([^ "]+)"', r2):
  229. st[a[0]] = a[1]
  230. if a[0] == "id":
  231. sid = a[1]
  232. self.styles[sid] = st
  233. for r2 in re.findall("<p .+?</p>", s):
  234. sub = {}
  235. sub["begin"] = str2sec(re.search('begin="([^"]+)"', r2).group(1)) if re.search('begin="([^"]+)"', r2) else -1
  236. sub["end"] = str2sec(re.search('end="([^"]+)"', r2).group(1)) if re.search('end="([^"]+)"', r2) else -1
  237. sub["style"] = re.search('style="([^"]+)"', r2).group(1) if re.search('style="([^"]+)"', r2) else None
  238. sub["text"] = re.search("<p[^>]+>(.+)</p>", r2).group(1).replace("\n","")
  239. sub["text"] = re.sub("<br\s*?/>","\n",sub["text"])
  240. sub["text"] = re.sub("<.+?>"," ",sub["text"])
  241. self.subs.append(sub)
  242. pass
  243. def load_vtt(self,s):
  244. f = StringIO.StringIO(s)
  245. while True:
  246. line = f.readline()
  247. if not line:
  248. break
  249. m = re.search(r"([\d\.\,:]+)\s*-->\s*([\d\.\,\:]+)",line)
  250. if m:
  251. sub = {}
  252. sub["begin"] = str2sec(m.group(1))
  253. sub["end"] = str2sec(m.group(2))
  254. sub["style"] = None
  255. sub["text"] = []
  256. line = f.readline()
  257. while line.strip():
  258. txt = line.strip()
  259. if isinstance(txt,unicode):
  260. txt = txt.encode("utf8")
  261. sub["text"].append(txt)
  262. line = f.readline()
  263. sub["text"] = "\n".join(sub["text"])
  264. self.subs.append(sub)
  265. else:
  266. continue
  267. pass
  268. def get_srt(self):
  269. out = ""
  270. i = 0
  271. for sub in self.subs:
  272. i +=1
  273. begin = sub["begin"]
  274. begin = "%s,%03i"%(str(datetime.timedelta(seconds=begin/1000)),begin%1000)
  275. end = sub["end"]
  276. end = "%s,%03i"%(str(datetime.timedelta(seconds=end/1000)),end%1000)
  277. txt2 = sub["text"]
  278. out += "%s\n%s --> %s\n%s\n\n\n"%(i,begin,end,txt2)
  279. return out
  280. def str2sec(r):
  281. # Convert str time to miliseconds
  282. r= r.replace(",",".")
  283. m = re.search(r"(\d+\:)*(\d+)\:(\d+\.\d+)", r)
  284. if m:
  285. sec = int(m.group(1)[:-1])*60*60*1000 if m.group(1) else 0
  286. sec += int(m.group(2))*60*1000 + int(float(m.group(3))*1000)
  287. return sec
  288. else:
  289. return -1
  290. #c = Captions("http://195.13.216.2/mobile-vod/mp4:lb_barbecue_fr_lq.mp4/lb_barbecue_lv.vtt")
  291. #c = Captions("http://www.bbc.co.uk/iplayer/subtitles/ng/modav/bUnknown-0edd6227-0f38-411c-8d46-fa033c4c61c1_b05ql1s3_1479853893356.xml")
  292. #url = "http://195.13.216.2/mobile-vod/mp4:ac_now_you_see_me_2_en_lq.mp4/ac_now_you_see_me_2_lv.vtt"
  293. #c = Captions(url)
  294. #pass
  295. def ttaf2srt(s):
  296. out = u""
  297. i = 0
  298. for p,txt in re.findall("<p ([^>]+)>(.+?)</p>", s, re.DOTALL):
  299. i +=1
  300. begin = re.search('begin="(.+?)"',p).group(1)
  301. begin = begin.replace(".",",")
  302. end = re.search('end="(.+?)"',p).group(1)
  303. end = end.replace(".",",")
  304. txt2 = re.sub("<br */>","\n",txt)
  305. out += "%s\n%s --> %s\n%s\n\n"%(i,begin,end,txt2)
  306. return out
  307. def vtt2srt(s):
  308. out = ""
  309. i = 0
  310. # result = re.findall(r"([\d:\. ]+-->[\d:\. ]+)\n(.+?\n)+", r.content)
  311. for t1, t2, txt in re.findall(r"([\d:\.]+)\s*-->\s*([\d:\.]+)\n(.+?\n)+", s):
  312. i +=1
  313. if len(t1.split(":")) == 2:
  314. t1 = "00:" + t1
  315. t1 = t1.replace(".", ",")
  316. if len(t2.split(":")) == 2:
  317. t2 = "00:" + t2
  318. t2 = t2.replace(".", ",")
  319. out += "%s\n%s --> %s\n%s\n\n"%(i,t1,t2,txt)
  320. return out
  321. def item():
  322. """Default item content"""
  323. stream0 = {
  324. 'name': '', #
  325. 'url': '',
  326. 'quality': '?',
  327. 'surl': '',
  328. 'subs': [],
  329. 'headers': {},
  330. "desc":"",
  331. "img":"",
  332. "lang":"",
  333. "type":"",
  334. "resolver":"",
  335. "order":0,
  336. "live":False
  337. }
  338. return stream0
  339. class _StringCookieJar(cookielib.LWPCookieJar):
  340. def __init__(self, string=None, filename=None, delayload=False, policy=None):
  341. cookielib.LWPCookieJar.__init__(self, filename, delayload, policy)
  342. if string and len(string) > 0:
  343. self._cookies = pickle.loads(str(string))
  344. def dump(self):
  345. return pickle.dumps(self._cookies)
  346. def init_urllib(cache=None):
  347. """
  348. Initializes urllib cookie handler
  349. """
  350. global _cookie_jar
  351. data = None
  352. if cache is not None:
  353. data = cache.get(CACHE_COOKIES)
  354. _cookie_jar = _StringCookieJar(data)
  355. opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(_cookie_jar))
  356. urllib2.install_opener(opener)
  357. def cache_cookies(cache):
  358. """
  359. Saves cookies to cache
  360. """
  361. global _cookie_jar
  362. if _cookie_jar:
  363. cache.set(CACHE_COOKIES, _cookie_jar.dump())
  364. def request0(url, headers={}):
  365. debug('request: %s' % url)
  366. req = urllib2.Request(url, headers=headers)
  367. req.add_header('User-Agent', UA)
  368. try:
  369. response = urllib2.urlopen(req)
  370. data = response.read()
  371. response.close()
  372. except urllib2.HTTPError, error:
  373. data = error.read()
  374. debug('len(data) %s' % len(data))
  375. return data
  376. def request(url, headers={}):
  377. debug('request: %s' % url)
  378. #req = urllib2.Request(url, headers=headers)
  379. #req.add_header('User-Agent', UA)
  380. if 'User-Agent' not in headers:
  381. headers['User-Agent']= UA
  382. try:
  383. r = requests.get(url, headers=headers)
  384. data = r.content
  385. except:
  386. data = r.content
  387. debug('len(data) %s' % len(data))
  388. return data
  389. def post(url, data, headers={}):
  390. postdata = urllib.urlencode(data)
  391. #req = urllib2.Request(url, postdata, headers)
  392. #req.add_header('User-Agent', UA)
  393. import requests
  394. if 'User-Agent' not in headers:
  395. headers['User-Agent']= UA
  396. try:
  397. r = requests.post(url, data=postdata,headers=headers)
  398. data = r.content
  399. except urllib2.HTTPError, error:
  400. data = r.content
  401. return data
  402. def post0(url, data, headers={}):
  403. postdata = urllib.urlencode(data)
  404. req = urllib2.Request(url, postdata, headers)
  405. req.add_header('User-Agent', UA)
  406. try:
  407. response = urllib2.urlopen(req)
  408. data = response.read()
  409. response.close()
  410. except urllib2.HTTPError, error:
  411. data = error.read()
  412. return data
  413. def post_json(url, data, headers={}):
  414. postdata = json.dumps(data)
  415. headers['Content-Type'] = 'application/json'
  416. req = urllib2.Request(url, postdata, headers)
  417. req.add_header('User-Agent', UA)
  418. response = urllib2.urlopen(req)
  419. data = response.read()
  420. response.close()
  421. return data
  422. #def run_parallel_in_threads(target, args_list):
  423. #result = Queue.Queue()
  424. ## wrapper to collect return value in a Queue
  425. #def task_wrapper(*args):
  426. #result.put(target(*args))
  427. #threads = [threading.Thread(target=task_wrapper, args=args) for args in args_list]
  428. #for t in threads:
  429. #t.start()
  430. #for t in threads:
  431. #t.join()
  432. #return result
  433. def substr(data, start, end):
  434. i1 = data.find(start)
  435. i2 = data.find(end, i1)
  436. return data[i1:i2]
  437. def save_to_file(url, file):
  438. try:
  439. return save_data_to_file(request(url), file)
  440. except:
  441. traceback.print_exc()
  442. def save_data_to_file(data, file):
  443. try:
  444. f = open(file, 'wb')
  445. f.write(data)
  446. f.close()
  447. info('File %s saved' % file)
  448. return True
  449. except:
  450. traceback.print_exc()
  451. def read_file(file):
  452. if not os.path.exists(file):
  453. return ''
  454. f = open(file, 'r')
  455. data = f.read()
  456. f.close()
  457. return data
  458. def _substitute_entity(match):
  459. ent = match.group(3)
  460. if match.group(1) == '#':
  461. # decoding by number
  462. if match.group(2) == '':
  463. # number is in decimal
  464. return unichr(int(ent))
  465. elif match.group(2) == 'x':
  466. # number is in hex
  467. return unichr(int('0x' + ent, 16))
  468. else:
  469. # they were using a name
  470. cp = n2cp.get(ent)
  471. if cp:
  472. return unichr(cp)
  473. else:
  474. return match.group()
  475. def decode_html(data):
  476. if not type(data) == str:
  477. return data
  478. try:
  479. if not type(data) == unicode:
  480. data = unicode(data, 'utf-8', errors='ignore')
  481. entity_re = re.compile(r'&(#?)(x?)(\w+);')
  482. return entity_re.subn(_substitute_entity, data)[0]
  483. except:
  484. traceback.print_exc()
  485. print[data]
  486. return data
  487. def unescape(s0):
  488. #s2 = re.sub("&#\w+;",HTMLParser.HTMLParser().unescape("\1"),s)
  489. s0 = s0.replace("&amp;","&").replace("&quot;", '"')
  490. for s in re.findall("&#\w+;",s0):
  491. s2 = HTMLParser.HTMLParser().unescape(s)
  492. if isinstance(s0,str):
  493. s2 = s2.encode("utf8")
  494. s0 = s0.replace(s,s2)
  495. pass
  496. return s0
  497. def debug(text):
  498. if LOG > 1:
  499. print('[DEBUG] ' + str([text]))
  500. def info(text):
  501. if LOG > 0:
  502. print('[INFO] ' + str([text]))
  503. def error(text):
  504. print('[ERROR] ' + str([text]))
  505. _diacritic_replace = {u'\u00f3': 'o',
  506. u'\u0213': '-',
  507. u'\u00e1': 'a',
  508. u'\u010d': 'c',
  509. u'\u010c': 'C',
  510. u'\u010f': 'd',
  511. u'\u010e': 'D',
  512. u'\u00e9': 'e',
  513. u'\u011b': 'e',
  514. u'\u00ed': 'i',
  515. u'\u0148': 'n',
  516. u'\u0159': 'r',
  517. u'\u0161': 's',
  518. u'\u0165': 't',
  519. u'\u016f': 'u',
  520. u'\u00fd': 'y',
  521. u'\u017e': 'z',
  522. u'\xed': 'i',
  523. u'\xe9': 'e',
  524. u'\xe1': 'a',
  525. }
  526. def replace_diacritic(string):
  527. ret = []
  528. for char in string:
  529. if char in _diacritic_replace:
  530. ret.append(_diacritic_replace[char])
  531. else:
  532. ret.append(char)
  533. return ''.join(ret)
  534. def params(url=None):
  535. if not url:
  536. url = sys.argv[2]
  537. param = {}
  538. paramstring = url
  539. if len(paramstring) >= 2:
  540. params = url
  541. cleanedparams = params.replace('?', '')
  542. if (params[len(params) - 1] == '/'):
  543. params = params[0:len(params) - 2]
  544. pairsofparams = cleanedparams.split('&')
  545. param = {}
  546. for i in range(len(pairsofparams)):
  547. splitparams = {}
  548. splitparams = pairsofparams[i].split('=')
  549. if (len(splitparams)) == 2:
  550. param[splitparams[0]] = splitparams[1]
  551. for p in param.keys():
  552. param[p] = param[p].decode('hex')
  553. return param
  554. def int_to_base(number, base):
  555. digs = string.digits + string.letters
  556. if number < 0:
  557. sign = -1
  558. elif number == 0:
  559. return digs[0]
  560. else:
  561. sign = 1
  562. number *= sign
  563. digits = []
  564. while number:
  565. digits.append(digs[number % base])
  566. number /= base
  567. if sign < 0:
  568. digits.append('-')
  569. digits.reverse()
  570. return ''.join(digits)
  571. def extract_jwplayer_setup(data):
  572. """
  573. Extracts jwplayer setup configuration and returns it as a dictionary.
  574. :param data: A string to extract the setup from
  575. :return: A dictionary containing the setup configuration
  576. """
  577. data = re.search(r'<script.+?}\(\'(.+)\',\d+,\d+,\'([\w\|]+)\'.*</script>', data, re.I | re.S)
  578. if data:
  579. replacements = data.group(2).split('|')
  580. data = data.group(1)
  581. for i in reversed(range(len(replacements))):
  582. if len(replacements[i]) > 0:
  583. data = re.sub(r'\b%s\b' % int_to_base(i, 36), replacements[i], data)
  584. data = re.search(r'\.setup\(([^\)]+?)\);', data)
  585. if data:
  586. return json.loads(data.group(1).decode('string_escape'))
  587. #return demjson.decode(data.group(1).decode('string_escape')) ### III
  588. return None
  589. def datetime_from_utc_to_local(utc_datetime):
  590. now_timestamp = time.time()
  591. offset = datetime.datetime.fromtimestamp(now_timestamp) - datetime.datetime.utcfromtimestamp(now_timestamp)
  592. return utc_datetime + offset
  593. #def parse_html(url):
  594. # return BeautifulSoup(request(url), 'html5lib', from_encoding='utf-8')
  595. if __name__ == "__main__":
  596. s = open("The LEGO Ninjago Movie (2017).lv.vtt").read()
  597. s2 = vtt2srt(s)
  598. open("The LEGO Ninjago Movie (2017).lv.srt", "w").write(s2)
  599. s = 'B\xc4\x93thovena D\xc4\x81rgumu Taka (2014)/Beethoven&#x27;s Treasure [LV]'
  600. #s = s.decode("utf8")
  601. #s=unescape(s)
  602. #url = "http://localhost:88/https://walterebert.com/playground/video/hls/ts/480x270.m3u8?token=xxxx~User-Agent=Enigma2~Cookie=xxxxx"
  603. url = "http://hyt4d6.vkcache.com/secip/0/UMQ3q2gNjTlOPnEVm3iTiA/ODAuMjMyLjI0MC42/1479610800/hls-vod-s3/flv/api/files/videos/2015/09/11/144197748923a22.mp4.m3u8http://hyt4d6.vkcache.com/secip/0/Y-ZA1qRm8toplc0dN_L6_w/ODAuMjMyLjI0MC42/1479654000/hls-vod-s3/flv/api/files/videos/2015/09/11/144197748923a22.mp4.m3u8"
  604. headers = {"User-Agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/47.0.2526.70 Mobile/13C71 Safari/601.1.46"}
  605. url = "http://str1e.lattelecom.tv/mobile-vod/mp4:sf_fantastic_beasts_and_where_to_find_them_en_hd.mp4/playlist.m3u8?resource_id=fantastic_beasts_and_where_to_find_them&auth_token=6NAvMFDG+rYTAc4hb5JeL2bmsaRR7bAE23M6KDmhKYOGyXoo0gDpJUE9scYy+nQmfbgk03cWMe9MuXWSH1GqwolEk2jOQ/8Mrg7tOdbwrA8zM7nmkfCZPqQkwajZN4mfSJQVKHqXqJ8="
  606. headers={}
  607. print url
  608. url = "replay::tiesraide/ltv1/"
  609. url = "ltc::content/live-streams/103?include=quality"
  610. urlp = streamproxy_encode2(url,headers)
  611. print urlp
  612. url2,headers2 = streamproxy_decode2(urlp)
  613. print url2
  614. player(urlp)
  615. pass