Kodi plugin to to play various online streams (mostly Latvian)

util.py 21KB

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