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

util.py 21KB

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