diff --git a/addon.xml b/addon.xml index 090aa67..0c14e50 100644 --- a/addon.xml +++ b/addon.xml @@ -1,9 +1,9 @@ - + - + - + diff --git a/lib/aadecode.py b/lib/aadecode.py index e18dbba..92135a2 100644 --- a/lib/aadecode.py +++ b/lib/aadecode.py @@ -1,209 +1,209 @@ -#-*- coding: utf-8 -*- -# -# author : Djeman -# Updated by Shani-08 (https://github.com/Shani-08/ShaniXBMCWork2) - -import re - -class AADecoder(object): - def __init__(self, aa_encoded_data): - self.encoded_str = aa_encoded_data.replace('/*´∇`*/','') - - self.b = ["(c^_^o)", "(゚Θ゚)", "((o^_^o) - (゚Θ゚))", "(o^_^o)", - "(゚ー゚)", "((゚ー゚) + (゚Θ゚))", "((o^_^o) +(o^_^o))", "((゚ー゚) + (o^_^o))", - "((゚ー゚) + (゚ー゚))", "((゚ー゚) + (゚ー゚) + (゚Θ゚))", "(゚Д゚) .゚ω゚ノ", "(゚Д゚) .゚Θ゚ノ", - "(゚Д゚) ['c']", "(゚Д゚) .゚ー゚ノ", "(゚Д゚) .゚Д゚ノ", "(゚Д゚) [゚Θ゚]"] - - def is_aaencoded(self): - idx = self.encoded_str.find("゚ω゚ノ= /`m´)ノ ~┻━┻ //*´∇`*/ ['_']; o=(゚ー゚) =_=3; c=(゚Θ゚) =(゚ー゚)-(゚ー゚); ") - if idx == -1: - return False - - if self.encoded_str.find("(゚Д゚)[゚o゚]) (゚Θ゚)) ('_');", idx) == -1: - return False - - return True - - def base_repr(self, number, base=2, padding=0): - digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' - if base > len(digits): - base = len(digits) - - num = abs(number) - res = [] - while num: - res.append(digits[num % base]) - num //= base - if padding: - res.append('0' * padding) - if number < 0: - res.append('-') - return ''.join(reversed(res or '0')) - - def decode_char(self, enc_char, radix): - end_char = "+ " - str_char = "" - while enc_char != '': - found = False - - if not found: - for i in range(len(self.b)): - enc_char=enc_char.replace(self.b[i], str(i)) - - startpos=0 - findClose=True - balance=1 - result=[] - if enc_char.startswith('('): - l=0 - - for t in enc_char[1:]: - l+=1 - if findClose and t==')': - balance-=1; - if balance==0: - result+=[enc_char[startpos:l+1]] - findClose=False - continue - elif not findClose and t=='(': - startpos=l - findClose=True - balance=1 - continue - elif t=='(': - balance+=1 - - - if result is None or len(result)==0: - return "" - else: - - for r in result: - value = self.decode_digit(r, radix) - if value == "": - return "" - else: - str_char += value - - return str_char - - enc_char = enc_char[len(end_char):] - - return str_char - - - - def decode_digit(self, enc_int, radix): - - rr = '(\(.+?\)\))\+' - rerr=enc_int.split('))+') - v = '' - - #new mode - - for c in rerr: - - if len(c)>0: - if c.strip().endswith('+'): - c=c.strip()[:-1] - - startbrackets=len(c)-len(c.replace('(','')) - endbrackets=len(c)-len(c.replace(')','')) - - if startbrackets>endbrackets: - c+=')'*startbrackets-endbrackets - - c = c.replace('!+[]','1') - c = c.replace('-~','1+') - c = c.replace('[]','0') - - v+=str(eval(c)) - - return v - - mode = 0 - value = 0 - - while enc_int != '': - found = False - for i in range(len(self.b)): - if enc_int.find(self.b[i]) == 0: - if mode == 0: - value += i - else: - value -= i - enc_int = enc_int[len(self.b[i]):] - found = True - break - - if not found: - return "" - - enc_int = re.sub('^\s+|\s+$', '', enc_int) - if enc_int.find("+") == 0: - mode = 0 - else: - mode = 1 - - enc_int = enc_int[1:] - enc_int = re.sub('^\s+|\s+$', '', enc_int) - - return self.base_repr(value, radix) - - def decode(self): - - self.encoded_str = re.sub('^\s+|\s+$', '', self.encoded_str) - - # get data - pattern = (r"\(゚Д゚\)\[゚o゚\]\+ (.+?)\(゚Д゚\)\[゚o゚\]\)") - result = re.search(pattern, self.encoded_str, re.DOTALL) - if result is None: - print "AADecoder: data not found" - return False - - data = result.group(1) - - # hex decode string - begin_char = "(゚Д゚)[゚ε゚]+" - alt_char = "(o゚ー゚o)+ " - - out = '' - - while data != '': - # Check new char - if data.find(begin_char) != 0: - print "AADecoder: data not found" - return False - - data = data[len(begin_char):] - - # Find encoded char - enc_char = "" - if data.find(begin_char) == -1: - enc_char = data - data = "" - else: - enc_char = data[:data.find(begin_char)] - data = data[len(enc_char):] - - - radix = 8 - # Detect radix 16 for utf8 char - if enc_char.find(alt_char) == 0: - enc_char = enc_char[len(alt_char):] - radix = 16 - - str_char = self.decode_char(enc_char, radix) - - if str_char == "": - print "no match : " - print data + "\nout = " + out + "\n" - return False - - out += chr(int(str_char, radix)) - - if out == "": - print "no match : " + data - return False - - return out +#-*- coding: utf-8 -*- +# +# author : Djeman +# Updated by Shani-08 (https://github.com/Shani-08/ShaniXBMCWork2) + +import re + +class AADecoder(object): + def __init__(self, aa_encoded_data): + self.encoded_str = aa_encoded_data.replace('/*´∇`*/','') + + self.b = ["(c^_^o)", "(゚Θ゚)", "((o^_^o) - (゚Θ゚))", "(o^_^o)", + "(゚ー゚)", "((゚ー゚) + (゚Θ゚))", "((o^_^o) +(o^_^o))", "((゚ー゚) + (o^_^o))", + "((゚ー゚) + (゚ー゚))", "((゚ー゚) + (゚ー゚) + (゚Θ゚))", "(゚Д゚) .゚ω゚ノ", "(゚Д゚) .゚Θ゚ノ", + "(゚Д゚) ['c']", "(゚Д゚) .゚ー゚ノ", "(゚Д゚) .゚Д゚ノ", "(゚Д゚) [゚Θ゚]"] + + def is_aaencoded(self): + idx = self.encoded_str.find("゚ω゚ノ= /`m´)ノ ~┻━┻ //*´∇`*/ ['_']; o=(゚ー゚) =_=3; c=(゚Θ゚) =(゚ー゚)-(゚ー゚); ") + if idx == -1: + return False + + if self.encoded_str.find("(゚Д゚)[゚o゚]) (゚Θ゚)) ('_');", idx) == -1: + return False + + return True + + def base_repr(self, number, base=2, padding=0): + digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' + if base > len(digits): + base = len(digits) + + num = abs(number) + res = [] + while num: + res.append(digits[num % base]) + num //= base + if padding: + res.append('0' * padding) + if number < 0: + res.append('-') + return ''.join(reversed(res or '0')) + + def decode_char(self, enc_char, radix): + end_char = "+ " + str_char = "" + while enc_char != '': + found = False + + if not found: + for i in range(len(self.b)): + enc_char=enc_char.replace(self.b[i], str(i)) + + startpos=0 + findClose=True + balance=1 + result=[] + if enc_char.startswith('('): + l=0 + + for t in enc_char[1:]: + l+=1 + if findClose and t==')': + balance-=1; + if balance==0: + result+=[enc_char[startpos:l+1]] + findClose=False + continue + elif not findClose and t=='(': + startpos=l + findClose=True + balance=1 + continue + elif t=='(': + balance+=1 + + + if result is None or len(result)==0: + return "" + else: + + for r in result: + value = self.decode_digit(r, radix) + if value == "": + return "" + else: + str_char += value + + return str_char + + enc_char = enc_char[len(end_char):] + + return str_char + + + + def decode_digit(self, enc_int, radix): + + rr = '(\(.+?\)\))\+' + rerr=enc_int.split('))+') + v = '' + + #new mode + + for c in rerr: + + if len(c)>0: + if c.strip().endswith('+'): + c=c.strip()[:-1] + + startbrackets=len(c)-len(c.replace('(','')) + endbrackets=len(c)-len(c.replace(')','')) + + if startbrackets>endbrackets: + c+=')'*startbrackets-endbrackets + + c = c.replace('!+[]','1') + c = c.replace('-~','1+') + c = c.replace('[]','0') + + v+=str(eval(c)) + + return v + + mode = 0 + value = 0 + + while enc_int != '': + found = False + for i in range(len(self.b)): + if enc_int.find(self.b[i]) == 0: + if mode == 0: + value += i + else: + value -= i + enc_int = enc_int[len(self.b[i]):] + found = True + break + + if not found: + return "" + + enc_int = re.sub('^\s+|\s+$', '', enc_int) + if enc_int.find("+") == 0: + mode = 0 + else: + mode = 1 + + enc_int = enc_int[1:] + enc_int = re.sub('^\s+|\s+$', '', enc_int) + + return self.base_repr(value, radix) + + def decode(self): + + self.encoded_str = re.sub('^\s+|\s+$', '', self.encoded_str) + + # get data + pattern = (r"\(゚Д゚\)\[゚o゚\]\+ (.+?)\(゚Д゚\)\[゚o゚\]\)") + result = re.search(pattern, self.encoded_str, re.DOTALL) + if result is None: + print("AADecoder: data not found") + return False + + data = result.group(1) + + # hex decode string + begin_char = "(゚Д゚)[゚ε゚]+" + alt_char = "(o゚ー゚o)+ " + + out = '' + + while data != '': + # Check new char + if data.find(begin_char) != 0: + print("AADecoder: data not found") + return False + + data = data[len(begin_char):] + + # Find encoded char + enc_char = "" + if data.find(begin_char) == -1: + enc_char = data + data = "" + else: + enc_char = data[:data.find(begin_char)] + data = data[len(enc_char):] + + + radix = 8 + # Detect radix 16 for utf8 char + if enc_char.find(alt_char) == 0: + enc_char = enc_char[len(alt_char):] + radix = 16 + + str_char = self.decode_char(enc_char, radix) + + if str_char == "": + print("no match : ") + print(data + "\nout = " + out + "\n") + return False + + out += chr(int(str_char, radix)) + + if out == "": + print("no match : " + data) + return False + + return out diff --git a/lib/cloudflare.py b/lib/cloudflare.py index ea116dd..855d90d 100644 --- a/lib/cloudflare.py +++ b/lib/cloudflare.py @@ -22,9 +22,8 @@ # the Free Software Foundation; version 3 import re -import urllib -import urllib2 -import urlparse +import urllib.request, urllib.parse, urllib.error +import urllib.parse import util import xbmc @@ -32,7 +31,7 @@ COMPONENT = __name__ -class NoRedirection(urllib2.HTTPErrorProcessor): +class NoRedirection(urllib.request.HTTPErrorProcessor): def http_response(self, request, response): util.info('[CF] Stopping Redirect') @@ -61,18 +60,18 @@ def solve(url, cj, user_agent=None, wait=True): cj.load(ignore_discard=True) except: pass - opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) - urllib2.install_opener(opener) + opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + urllib.request.install_opener(opener) - scheme = urlparse.urlparse(url).scheme - domain = urlparse.urlparse(url).hostname - request = urllib2.Request(url) + scheme = urllib.parse.urlparse(url).scheme + domain = urllib.parse.urlparse(url).hostname + request = urllib.request.Request(url) for key in headers: request.add_header(key, headers[key]) try: - response = urllib2.urlopen(request) + response = urllib.request.urlopen(request) html = response.read() - except urllib2.HTTPError as e: + except urllib.error.HTTPError as e: html = e.read() tries = 0 @@ -140,17 +139,17 @@ def solve(url, cj, user_agent=None, wait=True): url = \ '%s://%s/cdn-cgi/l/chk_jschl?s=%s&jschl_vc=%s&pass=%s&jschl_answer=%s' \ - % (scheme, domain, urllib.quote(s), urllib.quote(vc), urllib.quote(password), urllib.quote(result)) + % (scheme, domain, urllib.parse.quote(s), urllib.parse.quote(vc), urllib.parse.quote(password), urllib.parse.quote(result)) # util.info('[CF] url: %s' % url) # util.debug('[CF] headers: {0}'.format(headers)) - request = urllib2.Request(url) + request = urllib.request.Request(url) for key in headers: request.add_header(key, headers[key]) try: - opener = urllib2.build_opener(NoRedirection) - urllib2.install_opener(opener) - response = urllib2.urlopen(request) + opener = urllib.request.build_opener(NoRedirection) + urllib.request.install_opener(opener) + response = urllib.request.urlopen(request) # util.info('[CF] code: {}'.format(response.getcode())) while response.getcode() in [301, 302, 303, 307]: if cj is not None: @@ -159,15 +158,15 @@ def solve(url, cj, user_agent=None, wait=True): redir_url = response.info().getheader('location') if not redir_url.startswith('http'): base_url = '%s://%s' % (scheme, domain) - redir_url = urlparse.urljoin(base_url, redir_url) + redir_url = urllib.parse.urljoin(base_url, redir_url) - request = urllib2.Request(redir_url) + request = urllib.request.Request(redir_url) for key in headers: request.add_header(key, headers[key]) if cj is not None: cj.add_cookie_header(request) - response = urllib2.urlopen(request) + response = urllib.request.urlopen(request) final = response.read() if 'cf-browser-verification' in final: util.info('[CF] Failure: html: %s url: %s' % (html, url)) @@ -175,11 +174,11 @@ def solve(url, cj, user_agent=None, wait=True): html = final else: break - except urllib2.HTTPError as e: + except urllib.error.HTTPError as e: util.info('[CF] HTTP Error: %s on url: %s' % (e.code, url)) return False - except urllib2.URLError as e: + except urllib.error.URLError as e: util.info('[CF] URLError Error: %s on url: %s' % (e, url)) return False diff --git a/lib/contentprovider/provider.py b/lib/contentprovider/provider.py index da1edcb..8536a39 100644 --- a/lib/contentprovider/provider.py +++ b/lib/contentprovider/provider.py @@ -26,7 +26,7 @@ try: import StorageServer except ImportError: - print 'Using dummy storage server' + print('Using dummy storage server') import storageserverdummy as StorageServer diff --git a/lib/contentprovider/xbmcprovider.py b/lib/contentprovider/xbmcprovider.py index aa18717..2fc47ac 100644 --- a/lib/contentprovider/xbmcprovider.py +++ b/lib/contentprovider/xbmcprovider.py @@ -29,8 +29,8 @@ import xbmcplugin import xbmc import xbmcgui -import urlparse -import urllib +import urllib.parse +import urllib.request, urllib.parse, urllib.error from collections import defaultdict from provider import ResolveException @@ -69,7 +69,7 @@ def __init__(self, provider, settings, addon): def check_setting_keys(self, keys): for key in keys: - if not key in self.settings.keys(): + if not key in list(self.settings.keys()): raise Exception('Invalid settings passed - [' + key + '] setting is required') def params(self): @@ -78,20 +78,20 @@ def params(self): def run(self, params): if params == {} or params == self.params(): return self.root() - if 'list' in params.keys(): + if 'list' in list(params.keys()): self.list(self.provider.list(params['list'])) return xbmcplugin.endOfDirectory(int(sys.argv[1])) - if 'down' in params.keys(): + if 'down' in list(params.keys()): return self.download({'url': params['down'], 'title': params['title']}) - if 'play' in params.keys(): + if 'play' in list(params.keys()): return self.play({'url': params['play'], 'info': params}) - if 'search-list' in params.keys(): + if 'search-list' in list(params.keys()): return self.search_list() - if 'search' in params.keys(): + if 'search' in list(params.keys()): return self.do_search(params['search']) - if 'search-remove' in params.keys(): + if 'search-remove' in list(params.keys()): return self.search_remove(params['search-remove']) - if 'search-edit' in params.keys(): + if 'search-edit' in list(params.keys()): return self.search_edit(params['search-edit']) if self.run_custom: return self.run_custom(params) @@ -167,7 +167,7 @@ def download(self, item): return stream = self.resolve(item['url']) if stream: - if not 'headers' in stream.keys(): + if not 'headers' in list(stream.keys()): stream['headers'] = {} xbmcutil.reportUsage(self.addon_id, self.addon_id + '/download') # clean up \ and / @@ -186,11 +186,11 @@ def play(self, item): stream = self.resolve(item['url']) if stream: xbmcutil.reportUsage(self.addon_id, self.addon_id + '/play') - if 'headers' in stream.keys(): - headerStr = '|' + urllib.urlencode(stream['headers']) + if 'headers' in list(stream.keys()): + headerStr = '|' + urllib.parse.urlencode(stream['headers']) if len(headerStr) > 1: stream['url'] += headerStr - print 'Sending %s to player' % stream['url'] + print('Sending %s to player' % stream['url']) li = xbmcgui.ListItem(path=stream['url'], iconImage='DefaulVideo.png') il = self._extract_infolabels(item['info']) if len(il) > 0: # only set when something was extracted @@ -220,7 +220,7 @@ def resolve(self, url): item.update({'url': url}) try: return self.provider.resolve(item) - except ResolveException, e: + except ResolveException as e: self._handle_exc(e) def search(self, keyword): @@ -257,7 +257,7 @@ def render_dir(self, item): params.update({'list': item['url']}) title = item['title'] img = None - if 'img' in item.keys(): + if 'img' in list(item.keys()): img = item['img'] if title.find('$') == 0: try: @@ -265,8 +265,8 @@ def render_dir(self, item): except: pass menuItems = {} - if 'menu' in item.keys(): - for ctxtitle, value in item['menu'].iteritems(): + if 'menu' in list(item.keys()): + for ctxtitle, value in item['menu'].items(): if ctxtitle.find('$') == 0: try: ctxtitle = self.addon.getLocalizedString(int(ctxtitle[1:])) @@ -281,7 +281,7 @@ def _extract_infolabels(self, item): for label in ['title', 'plot', 'year', 'genre', 'rating', 'director', 'votes', 'cast', 'trailer', 'tvshowtitle', 'season', 'episode', 'duration']: - if label in item.keys(): + if label in list(item.keys()): infoLabels[label] = util.decode_html(item[label]) return infoLabels @@ -299,8 +299,8 @@ def render_video(self, item): menuItems = {} if "!download" not in self.provider.capabilities(): menuItems[xbmc.getLocalizedString(33003)] = downparams - if 'menu' in item.keys(): - for ctxtitle, value in item['menu'].iteritems(): + if 'menu' in list(item.keys()): + for ctxtitle, value in item['menu'].items(): if ctxtitle.find('$') == 0: try: ctxtitle = self.addon.getLocalizedString(int(ctxtitle[1:])) @@ -351,7 +351,7 @@ def select_cb(resolved): return resolved[ret] try: return self.provider.resolve(item, select_cb=select_cb) - except ResolveException, e: + except ResolveException as e: self._handle_exc(e) @@ -371,7 +371,7 @@ def __init__(self, provider, settings, addon): self.check_setting_keys(['vip']) def ask_for_captcha(self, params): - img = os.path.join(unicode(xbmc.translatePath( + img = os.path.join(str(xbmc.translatePath( self.addon.getAddonInfo('profile'))), 'captcha.png') util.save_to_file(params['img'], img) cd = CaptchaDialog('captcha-dialog.xml', @@ -383,7 +383,7 @@ def ask_for_captcha(self, params): kb = xbmc.Keyboard('', self.addon.getLocalizedString(200), False) kb.doModal() if kb.isConfirmed(): - print 'got code ' + kb.getText() + print('got code ' + kb.getText()) return kb.getText() def ask_for_account_type(self): @@ -409,7 +409,7 @@ def resolve(self, url): return try: return self.provider.resolve(item, captcha_cb=self.ask_for_captcha) - except ResolveException, e: + except ResolveException as e: self._handle_exc(e) @@ -437,7 +437,7 @@ def resolve(self, url): return try: return self.provider.resolve(item, captcha_cb=self.ask_for_captcha, wait_cb=self.wait_cb) - except ResolveException, e: + except ResolveException as e: self._handle_exc(e) diff --git a/lib/crypto/md5crypt.py b/lib/crypto/md5crypt.py index 24f2e90..e0902fb 100644 --- a/lib/crypto/md5crypt.py +++ b/lib/crypto/md5crypt.py @@ -156,4 +156,4 @@ def unix_md5_crypt(pw, salt, magic=None): md5crypt = unix_md5_crypt if __name__ == "__main__": - print unix_md5_crypt("cat", "hat") + print(unix_md5_crypt("cat", "hat")) diff --git a/lib/resolver.py b/lib/resolver.py index 963a6c8..063f107 100644 --- a/lib/resolver.py +++ b/lib/resolver.py @@ -34,7 +34,7 @@ if module == '__init__.py' or module[-3:] != '.py': continue module = module[:-3] - exec 'import %s' % module + exec('import %s' % module) resolver = eval(module) util.debug('found %s %s' % (resolver, dir(resolver))) @@ -75,12 +75,12 @@ def resolve(url): def fix_stream(i, url, resolver, default): """ fix missing but required values """ - if 'name' not in i.keys(): + if 'name' not in list(i.keys()): i['name'] = resolver.__name__ - if 'surl' not in i.keys(): + if 'surl' not in list(i.keys()): i['surl'] = url - for key in default.keys(): - if key not in i.keys(): + for key in list(default.keys()): + if key not in list(i.keys()): i[key] = default[key] [fix_stream(i, url, resolver, default) for i in value] @@ -132,7 +132,7 @@ def get_url(obj): resolvables = [] resolved = [] not_found = False - if isinstance(data, basestring) and regexes: + if isinstance(data, str) and regexes: for regex in regexes: for match in re.finditer(regex, data, re.IGNORECASE | re.DOTALL): urls.append(match.group('url')) @@ -161,12 +161,12 @@ def get_url(obj): elif len(streams) > 0: for stream in streams: if isinstance(url, dict): - for key in url.keys(): + for key in list(url.keys()): if key not in stream: stream[key] = url[key] elif key not in item(): - if isinstance(stream[key], basestring) and \ - isinstance(url[key], basestring): + if isinstance(stream[key], str) and \ + isinstance(url[key], str): stream[key] = url[key] + ' +' + stream[key] elif isinstance(stream[key], list) and \ isinstance(url[key], list): @@ -196,23 +196,23 @@ def filter_by_quality(resolved, q): ret = [] # first group streams by source url for item in resolved: - if item['surl'] in sources.keys(): + if item['surl'] in list(sources.keys()): sources[item['surl']].append(item) else: sources[item['surl']] = [item] if q == '1': # always return best quality from each source - for key in sources.keys(): + for key in list(sources.keys()): ret.append(sources[key][0]) elif q == '2': # always return worse quality from each source - for key in sources.keys(): + for key in list(sources.keys()): ret.append(sources[key][-1]) else: # we try to select sources of desired qualities quality = q_map[q] # 3,4,5 are 720,480,360 - for key in sources.keys(): + for key in list(sources.keys()): added = False for item in sources[key]: if quality == item['quality']: @@ -260,7 +260,7 @@ def findstreams_multi(data, regexes): error = False for regex in regexes: for match in re.finditer(regex, data, re.IGNORECASE | re.DOTALL): - print 'Found resolvable %s ' % match.group('url') + print('Found resolvable %s ' % match.group('url')) streams = resolve(match.group('url')) if isinstance(streams, list) and streams: util.debug('There was an error resolving ' + match.group('url')) @@ -279,11 +279,11 @@ def findstreams_multi(data, regexes): resolved2.reverse() qualities = {} for item in resolved2: - if item['quality'] in qualities.keys(): + if item['quality'] in list(qualities.keys()): qualities[item['quality']].append(item) else: qualities[item['quality']] = [item] # now .. we must sort items to be in same order as they were found on page - for q in qualities.keys(): + for q in list(qualities.keys()): qualities[q] = sorted(qualities[q], key=lambda i: resolved.index(i)) return qualities diff --git a/lib/search.py b/lib/search.py index 01a9b7c..69b727f 100644 --- a/lib/search.py +++ b/lib/search.py @@ -65,12 +65,12 @@ def item(items={},label=xbmcutil.__lang__(30003)): def main(addon,history,p,callback,key=None,value=None): if (key==None) or (key in p and p[key] == value): - if 'search-list' in p.keys(): + if 'search-list' in list(p.keys()): _list(addon,history,key,value) - if 'search' in p.keys(): + if 'search' in list(p.keys()): update_history=True - if 'search-no-history' in p.keys(): + if 'search-no-history' in list(p.keys()): update_history=False _search(addon,history,p['search'],update_history,callback) - if 'search-remove' in p.keys(): + if 'search-remove' in list(p.keys()): _remove(addon,history,p['search-remove']) diff --git a/lib/server/anyfilesresolver.py b/lib/server/anyfilesresolver.py index fe7a416..c6fec63 100644 --- a/lib/server/anyfilesresolver.py +++ b/lib/server/anyfilesresolver.py @@ -12,8 +12,8 @@ # */ import re -import urllib -import urllib2 +import urllib.request, urllib.parse, urllib.error +import urllib.request, urllib.error, urllib.parse import random import decimal @@ -67,7 +67,7 @@ def _decode(param): if loc_3[j + 1] == 64: break try: - loc_2 += unichr(loc_4[j]) + loc_2 += chr(loc_4[j]) except: pass j = j + 1 @@ -79,7 +79,7 @@ def _decode(param): def resolve(url): m = _regex(url) if m: - resp = urllib2.urlopen(url) + resp = urllib.request.urlopen(url) sessc = resp.headers.get('Set-Cookie').split(';')[0] resp.close() furl = "%s/w.jsp?id=%s&width=620&height=349&pos=&skin=0" % (BASE_URL,m.group('id')) diff --git a/lib/server/dailymotionresolver.py b/lib/server/dailymotionresolver.py index 4b356e6..538db52 100644 --- a/lib/server/dailymotionresolver.py +++ b/lib/server/dailymotionresolver.py @@ -31,16 +31,16 @@ def supports(url): def resolve(url): - print 'The url is ::', url + print('The url is ::', url) id = re.search(r'dailymotion.com/embed/video/(.+)', url).group(1) - print 'The id is ::', id + print('The id is ::', id) headers = {'User-Agent': 'Android'} cookie = {'Cookie': "lang=en; ff=off"} r = util.request("http://www.dailymotion.com/player/metadata/video/" + id, headers) content = json.loads(r) cc = content['qualities'] - cc = cc.items() + cc = list(cc.items()) cc = sorted(cc, reverse=True) m_url = '' diff --git a/lib/server/hqqresolver.py b/lib/server/hqqresolver.py index 911f92f..d503fb6 100644 --- a/lib/server/hqqresolver.py +++ b/lib/server/hqqresolver.py @@ -11,12 +11,12 @@ # * original based on https://gitorious.org/iptv-pl-dla-openpli/ urlresolver # * update based on https://github.com/LordVenom/ # */ -from StringIO import StringIO +from io import StringIO import json import util import re import base64 -import urllib +import urllib.request, urllib.parse, urllib.error __name__ = 'hqq' @@ -51,12 +51,12 @@ def l0I(string): o2 = bits >> 8 & 0xff o3 = bits & 0xff if h3 == 64: - enc += unichr(o1) + enc += chr(o1) else: if h4 == 64: - enc += unichr(o1) + unichr(o2) + enc += chr(o1) + chr(o2) else: - enc += unichr(o1) + unichr(o2) + unichr(o3) + enc += chr(o1) + chr(o2) + chr(o3) if i >= len(string): break return enc @@ -175,8 +175,8 @@ def resolve(url): get_data = {'iss': jsonIp, 'vid': vid, 'at': at.group(1), 'autoplayed': 'yes', 'referer': 'on', 'http_referer': '', 'pass': '', 'embed_from' : '', 'need_captcha' : '0' } - data = urllib.unquote(util.request("http://hqq.tv/sec/player/embed_player.php?" + - urllib.urlencode(get_data), headers)) + data = urllib.parse.unquote(util.request("http://hqq.tv/sec/player/embed_player.php?" + + urllib.parse.urlencode(get_data), headers)) l = re.search(r'link_1: ([a-zA-Z]+), server_1: ([a-zA-Z]+)', data) vid_server = re.search(r'var ' + l.group(2) + ' = "([^"]+)"', data).group(1) @@ -186,7 +186,7 @@ def resolve(url): get_data = {'server_1': vid_server, 'link_1': vid_link, 'at': at.group(1), 'adb': '0/', 'b': '1', 'vid': vid } headers['x-requested-with'] = 'XMLHttpRequest' - data = util.request("http://hqq.tv/player/get_md5.php?" + urllib.urlencode(get_data), headers) + data = util.request("http://hqq.tv/player/get_md5.php?" + urllib.parse.urlencode(get_data), headers) jsonData = json.loads(data) encodedm3u = jsonData['file'] decodedm3u = _decode2(encodedm3u.replace('\\', '')) @@ -205,7 +205,7 @@ def _regex(url): return match match = re.search(r'(hqq|netu)\.tv/player/hash\.php\?hash=\d+', url) if match: - match = re.search(r'var\s+vid\s*=\s*\'(?P[^\']+)\'', urllib.unquote(util.request(url))) + match = re.search(r'var\s+vid\s*=\s*\'(?P[^\']+)\'', urllib.parse.unquote(util.request(url))) if match: return match b64enc = re.search(r'data:text/javascript\;charset\=utf\-8\;base64([^\"]+)', url) diff --git a/lib/server/koukejseresolver.py b/lib/server/koukejseresolver.py index ee8185a..fc62b0e 100644 --- a/lib/server/koukejseresolver.py +++ b/lib/server/koukejseresolver.py @@ -19,7 +19,7 @@ # * http://www.gnu.org/copyleft/gpl.html # * # */ -import re,util,urllib2,traceback +import re,util,urllib.request,urllib.error,urllib.parse,traceback __name__ = 'koukejse.cz' def supports(url): return not _regex(url) == None diff --git a/lib/server/koukniresolver.py b/lib/server/koukniresolver.py index 01f667b..e9a0a38 100644 --- a/lib/server/koukniresolver.py +++ b/lib/server/koukniresolver.py @@ -19,7 +19,7 @@ # * http://www.gnu.org/copyleft/gpl.html # * # */ -import re, util, urllib2, traceback +import re, util, urllib.request, urllib.error, urllib.parse, traceback __name__ = 'koukni.cz' def supports(url): return not _regex(url) == None diff --git a/lib/server/ksetresolver.py b/lib/server/ksetresolver.py index 94d71cf..4d4db7c 100644 --- a/lib/server/ksetresolver.py +++ b/lib/server/ksetresolver.py @@ -1,54 +1,54 @@ -# -*- coding: UTF-8 -*- -#/* -# * Copyright (C) 2013 mx3L -# * -# * -# * This Program is free software; you can redistribute it and/or modify -# * it under the terms of the GNU General Public License as published by -# * the Free Software Foundation; either version 2, or (at your option) -# * any later version. -# * -# * This Program is distributed in the hope that it will be useful, -# * but WITHOUT ANY WARRANTY; without even the implied warranty of -# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# * GNU General Public License for more details. -# * -# * You should have received a copy of the GNU General Public License -# * along with this program; see the file COPYING. If not, write to -# * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. -# * http://www.gnu.org/copyleft/gpl.html -# * -# */ -import re, util, decimal, random, base64, urllib - -__name__ = 'kset' -def supports(url): - return not _regex(url) == None - -def gen_random_decimal(i, d): - return decimal.Decimal('%d.%d' % (random.randint(0, i), random.randint(0, d))) - -# returns the steam url -def resolve(url): - m = _regex(url) - if m: - id = int(m.group('id')) - headers = { - "Referer":"http://st.kset.kz/pl/pl.swf" - } - - params = { - 'id':id, - 'ref':'http://kset.kz/video_frame.php?id=%d' % id, - 'r':gen_random_decimal(0, 99999999999999) - } - quality = "480p" - data = util.request("http://kset.kz/v.php?" + urllib.urlencode(params), headers=headers) - item = util.json.loads(base64.decodestring(data)) - return [{'quality':quality, 'url':item[u'file']}] - - -def _regex(url): - m = re.search('http://kset\.kz/video_frame\.php\?id=(?P[0-9]+)', url, re.IGNORECASE | re.DOTALL) - return m - +# -*- coding: UTF-8 -*- +#/* +# * Copyright (C) 2013 mx3L +# * +# * +# * This Program is free software; you can redistribute it and/or modify +# * it under the terms of the GNU General Public License as published by +# * the Free Software Foundation; either version 2, or (at your option) +# * any later version. +# * +# * This Program is distributed in the hope that it will be useful, +# * but WITHOUT ANY WARRANTY; without even the implied warranty of +# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# * GNU General Public License for more details. +# * +# * You should have received a copy of the GNU General Public License +# * along with this program; see the file COPYING. If not, write to +# * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. +# * http://www.gnu.org/copyleft/gpl.html +# * +# */ +import re, util, decimal, random, base64, urllib.request, urllib.parse, urllib.error + +__name__ = 'kset' +def supports(url): + return not _regex(url) == None + +def gen_random_decimal(i, d): + return decimal.Decimal('%d.%d' % (random.randint(0, i), random.randint(0, d))) + +# returns the steam url +def resolve(url): + m = _regex(url) + if m: + id = int(m.group('id')) + headers = { + "Referer":"http://st.kset.kz/pl/pl.swf" + } + + params = { + 'id':id, + 'ref':'http://kset.kz/video_frame.php?id=%d' % id, + 'r':gen_random_decimal(0, 99999999999999) + } + quality = "480p" + data = util.request("http://kset.kz/v.php?" + urllib.parse.urlencode(params), headers=headers) + item = util.json.loads(base64.decodestring(data)) + return [{'quality':quality, 'url':item['file']}] + + +def _regex(url): + m = re.search('http://kset\.kz/video_frame\.php\?id=(?P[0-9]+)', url, re.IGNORECASE | re.DOTALL) + return m + diff --git a/lib/server/mixturevideoresolver.py b/lib/server/mixturevideoresolver.py index 27c004f..027696e 100644 --- a/lib/server/mixturevideoresolver.py +++ b/lib/server/mixturevideoresolver.py @@ -19,32 +19,32 @@ # * http://www.gnu.org/copyleft/gpl.html # * # */ -import re,util,urllib2,traceback,resolver +import re,util,urllib.request,urllib.error,urllib.parse,traceback,resolver __name__ = 'mixturecloud' def supports(url): return not _regex(url) == None -class MyHTTPRedirectHandler(urllib2.HTTPRedirectHandler): +class MyHTTPRedirectHandler(urllib.request.HTTPRedirectHandler): def http_error_302(self, req, fp, code, msg, headers): self.location = headers.getheader('Location') - return urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers) + return urllib.request.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers) # returns the steam url def resolve(url): m = _regex(url) if m: - defrhandler = urllib2.HTTPRedirectHandler - cookieprocessor = urllib2.HTTPCookieProcessor() + defrhandler = urllib.request.HTTPRedirectHandler + cookieprocessor = urllib.request.HTTPCookieProcessor() redirecthandler = MyHTTPRedirectHandler() - opener = urllib2.build_opener(redirecthandler, cookieprocessor) - urllib2.install_opener(opener) - req = urllib2.Request(url) - response = urllib2.urlopen(req) + opener = urllib.request.build_opener(redirecthandler, cookieprocessor) + urllib.request.install_opener(opener) + req = urllib.request.Request(url) + response = urllib.request.urlopen(req) response.close() - urllib2.install_opener(urllib2.build_opener(defrhandler,cookieprocessor)) + urllib.request.install_opener(urllib.request.build_opener(defrhandler,cookieprocessor)) # mixturevideo uses REDIRECT to 'secret url' ;-) url = redirecthandler.location item = resolver.item() diff --git a/lib/server/moevideoresolver.py b/lib/server/moevideoresolver.py index 8a5d0f2..27f213a 100644 --- a/lib/server/moevideoresolver.py +++ b/lib/server/moevideoresolver.py @@ -19,7 +19,7 @@ # * http://www.gnu.org/copyleft/gpl.html # * # */ -import re,util,urllib2,urlparse +import re,util,urllib.request,urllib.error,urllib.parse,urllib.parse __name__ = 'moevideo' def supports(url): return not _regex(url) == None @@ -32,7 +32,7 @@ def url(url): post = {'r':'["tVL0gjqo5",["preview/flv_image",{"uid":"'+id+'"}],["preview/flv_link",{"uid":"'+id+'"}]]'} data = util.post('http://api.letitbit.net',post) data = data.replace('\\','') - print data + print(data) link = re.search('link\"\:\"(?P[^\"]+)',data) if link: return [{'url':link.group('link')}] diff --git a/lib/server/mojevideosk.py b/lib/server/mojevideosk.py index 41b34ad..dca6a6d 100644 --- a/lib/server/mojevideosk.py +++ b/lib/server/mojevideosk.py @@ -36,8 +36,8 @@ def resolve(url): cookies = {} util.init_urllib(cookies) data = util.request(url) - view = pickle.loads(util._cookie_jar.dump())[ - '.mojevideo.sk']['/'].keys()[0] + view = list(pickle.loads(util._cookie_jar.dump())[ + '.mojevideo.sk']['/'].keys())[0] st = re.search(r'vHash=\[\'([^\']+)', data) if not st: return None diff --git a/lib/server/myviruresolver.py b/lib/server/myviruresolver.py index 4f706f8..3706a3d 100644 --- a/lib/server/myviruresolver.py +++ b/lib/server/myviruresolver.py @@ -24,14 +24,14 @@ import re import util -import urllib +import urllib.request, urllib.parse, urllib.error import pickle from demjson import demjson __author__ = 'Jose Riha' __name__ = 'myviru' -UA = urllib.quote(util.UA) +UA = urllib.parse.quote(util.UA) def supports(url): @@ -50,7 +50,7 @@ def resolve(url): '.myvi.ru']['/']['UniversalUserID'] for f in playlist['video']: streamurl = f['url'] - streamurl += '|Cookie=UniversalUserID%3D' + urllib.quote(uuid.value) + streamurl += '|Cookie=UniversalUserID%3D' + urllib.parse.quote(uuid.value) streamurl += '&User-Agent=' + UA result.append({'url': streamurl}) if result: diff --git a/lib/server/openload.py b/lib/server/openload.py index 9023924..4556342 100644 --- a/lib/server/openload.py +++ b/lib/server/openload.py @@ -22,8 +22,8 @@ # uses code fragments from https://github.com/LordVenom/venom-xbmc-addons import re import util -import urllib -import urllib2 +import urllib.request, urllib.parse, urllib.error +import urllib.request, urllib.error, urllib.parse from aadecode import AADecoder class cRequestHandler: @@ -68,7 +68,7 @@ def request(self): return self.__callRequest() def getRequestUri(self): - return self.__sUrl + '?' + urllib.urlencode(self.__aParamaters) + return self.__sUrl + '?' + urllib.parse.urlencode(self.__aParamaters) def __setDefaultHeader(self): UA = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de-DE; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3' @@ -77,7 +77,7 @@ def __setDefaultHeader(self): self.addHeaderEntry('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7') def __callRequest(self): - sParameters = urllib.urlencode(self.__aParamaters) + sParameters = urllib.parse.urlencode(self.__aParamaters) if (self.__cType == cRequestHandler.REQUEST_TYPE_GET): if (len(sParameters) > 0): @@ -89,18 +89,18 @@ def __callRequest(self): sParameters = '' if (len(sParameters) > 0): - oRequest = urllib2.Request(self.__sUrl, sParameters) + oRequest = urllib.request.Request(self.__sUrl, sParameters) else: - oRequest = urllib2.Request(self.__sUrl) + oRequest = urllib.request.Request(self.__sUrl) for aHeader in self.__aHeaderEntries: - for sHeaderKey, sHeaderValue in aHeader.items(): + for sHeaderKey, sHeaderValue in list(aHeader.items()): oRequest.add_header(sHeaderKey, sHeaderValue) sContent = '' try: - oResponse = urllib2.urlopen(oRequest, timeout=30) + oResponse = urllib.request.urlopen(oRequest, timeout=30) sContent = oResponse.read() self.__sResponseHeader = oResponse.info() @@ -108,7 +108,7 @@ def __callRequest(self): oResponse.close() - except urllib2.HTTPError, e: + except urllib.error.HTTPError as e: if e.code == 503: if cloudflare.CheckIfActive(e.headers): cookies = e.headers['Set-Cookie'] @@ -133,7 +133,7 @@ def __callRequest(self): return sContent def getHeaderLocationUrl(self): - opened = urllib.urlopen(self.__sUrl) + opened = urllib.request.urlopen(self.__sUrl) return opened.geturl() class cParser: @@ -267,8 +267,8 @@ def resolve(url): UA = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0' headers = {'User-Agent': UA } - req = urllib2.Request(api_call,None,headers) - res = urllib2.urlopen(req) + req = urllib.request.Request(api_call,None,headers) + res = urllib.request.urlopen(req) finalurl = res.geturl() api_call = finalurl diff --git a/lib/server/publicvideohostresolver.py b/lib/server/publicvideohostresolver.py index 8d9dc63..6bbd178 100644 --- a/lib/server/publicvideohostresolver.py +++ b/lib/server/publicvideohostresolver.py @@ -1,48 +1,48 @@ -# -*- coding: UTF-8 -*- -#/* -# * Copyright (C) 2013 mx3L -# * -# * -# * This Program is free software; you can redistribute it and/or modify -# * it under the terms of the GNU General Public License as published by -# * the Free Software Foundation; either version 2, or (at your option) -# * any later version. -# * -# * This Program is distributed in the hope that it will be useful, -# * but WITHOUT ANY WARRANTY; without even the implied warranty of -# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# * GNU General Public License for more details. -# * -# * You should have received a copy of the GNU General Public License -# * along with this program; see the file COPYING. If not, write to -# * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. -# * http://www.gnu.org/copyleft/gpl.html -# * -# */ -import re, util, decimal, random, base64, urllib - -__name__ = 'publicvideohost' -def supports(url): - return not _regex(url) == None - -def gen_random_decimal(i, d): - return decimal.Decimal('%d.%d' % (random.randint(0, i), random.randint(0, d))) - -# returns the steam url -def resolve(url): - m = _regex(url) - if m: - id = int(m.group('v')) - params = { - 'v':id, - } - quality = "480p" - data = util.request("http://embed.publicvideohost.org/v.php?" + urllib.urlencode(params)) - vurl = re.search('file\:(.*?)\"(?P[^"]+)',data, re.IGNORECASE | re.DOTALL).group('url') - return [{'quality':quality, 'url':vurl}] - - -def _regex(url): - m = re.search('http://embed\.publicvideohost\.org/v\.php\?(.+?)v=(?P[0-9]+)', url, re.IGNORECASE | re.DOTALL) - return m - +# -*- coding: UTF-8 -*- +#/* +# * Copyright (C) 2013 mx3L +# * +# * +# * This Program is free software; you can redistribute it and/or modify +# * it under the terms of the GNU General Public License as published by +# * the Free Software Foundation; either version 2, or (at your option) +# * any later version. +# * +# * This Program is distributed in the hope that it will be useful, +# * but WITHOUT ANY WARRANTY; without even the implied warranty of +# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# * GNU General Public License for more details. +# * +# * You should have received a copy of the GNU General Public License +# * along with this program; see the file COPYING. If not, write to +# * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. +# * http://www.gnu.org/copyleft/gpl.html +# * +# */ +import re, util, decimal, random, base64, urllib.request, urllib.parse, urllib.error + +__name__ = 'publicvideohost' +def supports(url): + return not _regex(url) == None + +def gen_random_decimal(i, d): + return decimal.Decimal('%d.%d' % (random.randint(0, i), random.randint(0, d))) + +# returns the steam url +def resolve(url): + m = _regex(url) + if m: + id = int(m.group('v')) + params = { + 'v':id, + } + quality = "480p" + data = util.request("http://embed.publicvideohost.org/v.php?" + urllib.parse.urlencode(params)) + vurl = re.search('file\:(.*?)\"(?P[^"]+)',data, re.IGNORECASE | re.DOTALL).group('url') + return [{'quality':quality, 'url':vurl}] + + +def _regex(url): + m = re.search('http://embed\.publicvideohost\.org/v\.php\?(.+?)v=(?P[0-9]+)', url, re.IGNORECASE | re.DOTALL) + return m + diff --git a/lib/server/putlockerresolver.py b/lib/server/putlockerresolver.py index 40246df..560ae51 100644 --- a/lib/server/putlockerresolver.py +++ b/lib/server/putlockerresolver.py @@ -78,15 +78,15 @@ def url(url): #find session_hash try: html = util.request(web_url) - except urllib2.URLError, e: - print ('putlocker: got http error %d fetching %s' % (e.code, web_url)) + except urllib.error.URLError as e: + print(('putlocker: got http error %d fetching %s' % (e.code, web_url))) return False #Shortcut for logged in users pattern = 'Download File' link = re.search(pattern, html) if link: - print 'Direct link found: %s' %link.group(1) + print('Direct link found: %s' %link.group(1)) return 'http://www.putlocker.com%s' %link.group(1) r = re.search('value="([0-9a-f]+?)" name="hash"', html) @@ -99,8 +99,8 @@ def url(url): #post session_hash try: html = util.post(web_url, {'hash': session_hash,'confirm': 'Continue as Free User'}) - except urllib2.URLError, e: - print ('putlocker: got http error %d posting %s' %(e.code, web_url)) + except urllib.error.URLError as e: + print(('putlocker: got http error %d posting %s' %(e.code, web_url))) return False #find playlist code @@ -135,7 +135,7 @@ def url(url): xml_url += playlist_code try: html = util.request(xml_url) - except urllib2.URLError, e: + except urllib.error.URLError as e: pritn ('putlocker: got http error %d fetching %s'(e.code, xml_url)) return False diff --git a/lib/server/servertipczresolver.py b/lib/server/servertipczresolver.py index 7669129..462e7cc 100644 --- a/lib/server/servertipczresolver.py +++ b/lib/server/servertipczresolver.py @@ -19,7 +19,7 @@ # * http://www.gnu.org/copyleft/gpl.html # * # */ -import re,util,urllib +import re,util,urllib.request,urllib.parse,urllib.error __name__ = 'servertip' def supports(url): return not _regex(url) == None diff --git a/lib/server/sledujuserialyresolver.py b/lib/server/sledujuserialyresolver.py index d4f9f7e..f781e44 100644 --- a/lib/server/sledujuserialyresolver.py +++ b/lib/server/sledujuserialyresolver.py @@ -19,7 +19,7 @@ # * http://www.gnu.org/copyleft/gpl.html # * # */ -import re,util,urllib2,traceback +import re,util,urllib.request,urllib.error,urllib.parse,traceback __name__ = 'zkouknito.cz' def supports(url): return not _regex(url) == None @@ -37,7 +37,7 @@ def resolve(url): subs = re.search('\'file\'\: \'(?P.+?srt)',data) if subs: item['subs'] = _furl(subs.group('url')) - print item + print(item) return [item] def _furl(url): diff --git a/lib/server/videobbresolver.py b/lib/server/videobbresolver.py index 7019080..b1659c1 100644 --- a/lib/server/videobbresolver.py +++ b/lib/server/videobbresolver.py @@ -45,7 +45,7 @@ def resolve(url): if r: for match in r: - print match.groups() + print(match.groups()) res, url = match.groups() res = int(res.strip('p')) if res > chosen_res and res <= max_res: @@ -145,7 +145,7 @@ def bin( x): pass try: return '0b' + ''.join(reversed(out)) - except NameError, ne2: + except NameError as ne2: out.reverse() return '0b' + ''.join(out) diff --git a/lib/server/videomailresolver.py b/lib/server/videomailresolver.py index 3a032ef..a3be844 100644 --- a/lib/server/videomailresolver.py +++ b/lib/server/videomailresolver.py @@ -19,7 +19,7 @@ # * http://www.gnu.org/copyleft/gpl.html # * # */ -import re, util,urllib2 +import re, util,urllib.request,urllib.error,urllib.parse __name__ = 'videomail' def supports(url): return not _regex(url) == None @@ -35,16 +35,16 @@ def resolve(url): vurl = 'http://videoapi.my.mail.ru/' + vurl + '.json' util.init_urllib() - req = urllib2.Request(vurl) + req = urllib.request.Request(vurl) req.add_header('User-Agent', util.UA) - resp = urllib2.urlopen(req) + resp = urllib.request.urlopen(req) data = resp.read() vkey = [] for cookie in re.finditer('(video_key=[^\;]+)',resp.headers.get('Set-Cookie'),re.IGNORECASE | re.DOTALL): vkey.append(cookie.group(1)) headers = {'Cookie':vkey[-1]} item = util.json.loads(data) - for v in item[u'videos']: + for v in item['videos']: quality = v['key'] link = v['url'] items.append({'quality':quality, 'url':link, 'headers':headers}) diff --git a/lib/server/videonetresolver.py b/lib/server/videonetresolver.py index 1650749..cad97e3 100644 --- a/lib/server/videonetresolver.py +++ b/lib/server/videonetresolver.py @@ -42,7 +42,7 @@ def latin2text(word): 'ý' : 'ý', 'ž': 'ž', } - for key in dict_hex.keys(): + for key in list(dict_hex.keys()): word = word.replace(key,dict_hex[key]) return word diff --git a/lib/server/videozerresolver.py b/lib/server/videozerresolver.py index b96adfd..6f59739 100644 --- a/lib/server/videozerresolver.py +++ b/lib/server/videozerresolver.py @@ -145,7 +145,7 @@ def bin( x): pass try: return '0b' + ''.join(reversed(out)) - except NameError, ne2: + except NameError as ne2: out.reverse() return '0b' + ''.join(out) diff --git a/lib/server/vimeoresolver.py b/lib/server/vimeoresolver.py index eaa32dd..492f6cd 100644 --- a/lib/server/vimeoresolver.py +++ b/lib/server/vimeoresolver.py @@ -21,8 +21,8 @@ # */ import re -import urllib -import urllib2 +import urllib.request, urllib.parse, urllib.error +import urllib.request, urllib.error, urllib.parse import random import decimal @@ -40,7 +40,7 @@ def resolve(url): data = util.request("http://player.vimeo.com/v2/video/%s/config?type=moogaloop&referrer=&player_url=player.vimeo.com&v=1.0.0&cdn_url=http://a.vimeocdn.com"%m.group('id')) data = util.json.loads(data) h264 = data["request"]["files"]["h264"] - for quality in h264.iterkeys(): + for quality in h264.keys(): item = {} item['title'] = data['video']['title'] item['length'] = data['video']['duration'] diff --git a/lib/server/youtuberesolver.py b/lib/server/youtuberesolver.py index 2030b54..7e5a22a 100644 --- a/lib/server/youtuberesolver.py +++ b/lib/server/youtuberesolver.py @@ -284,7 +284,7 @@ def call_function(self, funcname, *args): def build_function(self, argnames, code): def resf(args): - local_vars = dict(zip(argnames, args)) + local_vars = dict(list(zip(argnames, args))) for stmt in code.split(';'): res, abort = self.interpret_statement(stmt, local_vars) if abort: @@ -294,7 +294,7 @@ def resf(args): # inspired by https://github.com/rg3/youtube-dl/blob/master/youtube_dl/extractor/youtube.py -import urllib2 +import urllib.request, urllib.error, urllib.parse class SignatureExtractor: def __init__(self): @@ -314,9 +314,9 @@ def decryptSignature(self, s, playerUrl): # use algoCache if playerUrl not in self.algoCache: # get player HTML 5 sript - request = urllib2.Request(playerUrl) + request = urllib.request.Request(playerUrl) try: - self.playerData = urllib2.urlopen(request).read() + self.playerData = urllib.request.urlopen(request).read() self.playerData = self.playerData.decode('utf-8', 'ignore') except: util.debug('Unable to download playerUrl webpage') @@ -464,49 +464,49 @@ def scrapeWebPageForVideoLinks(self, result, video, video_id): if re.search(r'player-age-gate-content">', result) is not None: # We simulate the access to the video from www.youtube.com/v/{video_id} # this can be viewed without login into Youtube - embed_webpage = util.request(self.urls[u"embed_stream"] % video_id) + embed_webpage = util.request(self.urls["embed_stream"] % video_id) sts = re.search('"sts"\s*:\s*(\d+)', embed_webpage).group().replace('"sts":', '') - result = util.request(self.urls[u"video_info"] % (video_id, video_id, sts)) + result = util.request(self.urls["video_info"] % (video_id, video_id, sts)) flashvars = cgi.parse_qs(result) - flashvars[u"url_encoded_fmt_stream_map"] = flashvars[u"url_encoded_fmt_stream_map"][0] - flashvars[u"title"] = flashvars[u"title"][0] + flashvars["url_encoded_fmt_stream_map"] = flashvars["url_encoded_fmt_stream_map"][0] + flashvars["title"] = flashvars["title"][0] else: flashvars = self.extractFlashVars(result, 0) - if not flashvars.has_key(u"url_encoded_fmt_stream_map"): + if "url_encoded_fmt_stream_map" not in flashvars: return links - if flashvars.has_key(u"ttsurl"): - video[u"ttsurl"] = flashvars[u"ttsurl"] - if flashvars.has_key("title"): + if "ttsurl" in flashvars: + video["ttsurl"] = flashvars["ttsurl"] + if "title" in flashvars: video["title"] = flashvars["title"] - for url_desc in flashvars[u"url_encoded_fmt_stream_map"].split(u","): + for url_desc in flashvars["url_encoded_fmt_stream_map"].split(","): url_desc_map = cgi.parse_qs(url_desc) - if not (url_desc_map.has_key(u"url") or url_desc_map.has_key(u"stream")): + if not ("url" in url_desc_map or "stream" in url_desc_map): continue - key = int(url_desc_map[u"itag"][0]) - url = u"" - if url_desc_map.has_key(u"url"): - url = urllib.unquote(url_desc_map[u"url"][0]) - elif url_desc_map.has_key(u"conn") and url_desc_map.has_key(u"stream"): - url = urllib.unquote(url_desc_map[u"conn"][0]) + key = int(url_desc_map["itag"][0]) + url = "" + if "url" in url_desc_map: + url = urllib.parse.unquote(url_desc_map["url"][0]) + elif "conn" in url_desc_map and "stream" in url_desc_map: + url = urllib.parse.unquote(url_desc_map["conn"][0]) if url.rfind("/") < len(url) - 1: url = url + "/" - url = url + urllib.unquote(url_desc_map[u"stream"][0]) - elif url_desc_map.has_key(u"stream") and not url_desc_map.has_key(u"conn"): - url = urllib.unquote(url_desc_map[u"stream"][0]) - - if url_desc_map.has_key(u"sig"): - url = url + u"&sig=" + url_desc_map[u"sig"][0] - elif url_desc_map.has_key(u"s"): - sig = url_desc_map[u"s"][0] + url = url + urllib.parse.unquote(url_desc_map["stream"][0]) + elif "stream" in url_desc_map and "conn" not in url_desc_map: + url = urllib.parse.unquote(url_desc_map["stream"][0]) + + if "sig" in url_desc_map: + url = url + "&sig=" + url_desc_map["sig"][0] + elif "s" in url_desc_map: + sig = url_desc_map["s"][0] flashvars = self.extractFlashVars(result, 1) - js = flashvars[u"js"] - url = url + u"&sig=" + self.decrypt_signature(sig, js) + js = flashvars["js"] + url = url + "&sig=" + self.decrypt_signature(sig, js) links[key] = url @@ -517,10 +517,10 @@ def decrypt_signature(self, s, js): def extractVideoLinksFromYoutube(self, url, videoid, video): - result = util.request(self.urls[u"video_stream"] % videoid) + result = util.request(self.urls["video_stream"] % videoid) links = self.scrapeWebPageForVideoLinks(result, video, videoid) if len(links) == 0: - util.error(u"Couldn't find video url- or stream-map.") + util.error("Couldn't find video url- or stream-map.") return links # /* # * Copyright (C) 2011 Libor Zoubek @@ -542,7 +542,7 @@ def extractVideoLinksFromYoutube(self, url, videoid, video): # * http://www.gnu.org/copyleft/gpl.html # * # */ -import re, util, urllib +import re, util, urllib.request, urllib.parse, urllib.error __name__ = 'youtube' @@ -560,7 +560,7 @@ def resolve(url): links = player.extractVideoLinksFromYoutube(url, m.group('id'), video) resolved = [] for q in links: - if q in player.fmt_value.keys(): + if q in list(player.fmt_value.keys()): quality = player.fmt_value[q] item = {} item['name'] = __name__ diff --git a/lib/usage/googletracker.py b/lib/usage/googletracker.py index b809a90..622ce11 100644 --- a/lib/usage/googletracker.py +++ b/lib/usage/googletracker.py @@ -19,7 +19,7 @@ # * http://www.gnu.org/copyleft/gpl.html # * # */ -import os,re,sys,urllib,urllib2,traceback,cookielib,random,time +import os,re,sys,urllib.request,urllib.parse,urllib.error,urllib.request,urllib.error,urllib.parse,traceback,http.cookiejar,random,time UA='Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3' TRACKER_URL='http://www.google-analytics.com/__utm.gif' @@ -27,19 +27,19 @@ ## # initializes urllib cookie handler def init_urllib(): - cj = cookielib.LWPCookieJar() - opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) - urllib2.install_opener(opener) + cj = http.cookiejar.LWPCookieJar() + opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + urllib.request.install_opener(opener) def _request(url,info): # setup useragent!! - print '[google] Submiting usage' - req = urllib2.Request(url) + print('[google] Submiting usage') + req = urllib.request.Request(url) req.add_header('User-Agent',info['useragent']) - response = urllib2.urlopen(req) + response = urllib.request.urlopen(req) data = response.read() if 200 == response.code: - print '[google] Usage has been submitted' + print('[google] Usage has been submitted') response.close() def _get_cookie(info): @@ -68,7 +68,7 @@ def track_usage(url,action,trackingCode,dry,info): 'utmcc':_get_cookie(info), 'utmu':'q~' # what is this about? } - req = TRACKER_URL+'?'+urllib.urlencode(params) + req = TRACKER_URL+'?'+urllib.parse.urlencode(params) if not dry: _request(req,info) diff --git a/lib/usage/tracker.py b/lib/usage/tracker.py index d38663e..9b88f27 100644 --- a/lib/usage/tracker.py +++ b/lib/usage/tracker.py @@ -45,7 +45,7 @@ def __init__(self, addon): file_content = f.read() f.close() try: - self.data = json.loads(unicode(file_content.decode('utf-8', 'ignore'))) + self.data = json.loads(str(file_content.decode('utf-8', 'ignore'))) except: self.data = {} self.data['id'] = {} @@ -55,7 +55,7 @@ def __init__(self, addon): self.save() for serv in self.services: - if not serv.__name__ in self.data['id'].keys(): + if not serv.__name__ in list(self.data['id'].keys()): self.data['id'][serv.__name__] = serv.createInstanceID() self.save() else: @@ -113,7 +113,7 @@ def _getUserAgent(self, version, language): if platform.startswith('darwin'): return 'KODI/%s (Mac; U; Intel Mac OS X; %s)' % (version, language) else: - print '[script.usage.tracker] Unknown platform %s, please report a bug, plugin needs to be fixed' % sys.platform + print('[script.usage.tracker] Unknown platform %s, please report a bug, plugin needs to be fixed' % sys.platform) return 'KODI/%s (X11; U; Unknown i686; %s)' % (version, language) def getSystemInfo(self): @@ -227,5 +227,5 @@ def getLanguageCode(id): id = id.lower() if id in languages: return languages[id] - print '[script.usage.tracker] Cannot detect language code from language: %s, please report a bug, plugin needs to be fixed' % id + print('[script.usage.tracker] Cannot detect language code from language: %s, please report a bug, plugin needs to be fixed' % id) return id diff --git a/lib/usage/utmain.py b/lib/usage/utmain.py index ae135b8..f5264a5 100644 --- a/lib/usage/utmain.py +++ b/lib/usage/utmain.py @@ -22,10 +22,10 @@ import os import re import sys -import urllib -import urllib2 +import urllib.request, urllib.parse, urllib.error +import urllib.request, urllib.error, urllib.parse import traceback -import cookielib +import http.cookiejar import xbmc import xbmcaddon import xbmcgui @@ -65,11 +65,11 @@ def trackUsage(params): if not xbmcaddon.Addon(params['id']).getAddonInfo('id') == params['id']: raise Exception('') except: - print 'Unable to create addon instance for %s, invalid addon ID?!' % (params['id']) + print('Unable to create addon instance for %s, invalid addon ID?!' % (params['id'])) return if register(params): - print 'Tracking usage ...' + print('Tracking usage ...') sett = tracker.TrackerSettings(__addon__) info = tracker.TrackerInfo().getSystemInfo() # retrieve per-installation-unique ID @@ -77,7 +77,7 @@ def trackUsage(params): if 'google' == params['service']: return googletracker.track_usage(params['host'], params['action'], params['tc'], params['dry'], info) else: - print 'Reporting for %s disabled by user' % (params['id']) + print('Reporting for %s disabled by user' % (params['id'])) def register(params): diff --git a/lib/util.py b/lib/util.py index c0c9bec..fec1440 100644 --- a/lib/util.py +++ b/lib/util.py @@ -22,13 +22,13 @@ import os import re import sys -import urllib -import urllib2 +import urllib.request, urllib.parse, urllib.error +import urllib.request, urllib.error, urllib.parse import traceback -import cookielib -from htmlentitydefs import name2codepoint as n2cp +import http.cookiejar +from html.entities import name2codepoint as n2cp import threading -import Queue +import queue import pickle import string import json @@ -45,11 +45,11 @@ CACHE_COOKIES = 'cookies' -class _StringCookieJar(cookielib.LWPCookieJar): +class _StringCookieJar(http.cookiejar.LWPCookieJar): def __init__(self, string=None, filename=None, delayload=False, policy=None, cache=None): self.cache = cache - cookielib.LWPCookieJar.__init__(self, filename, delayload, policy) + http.cookiejar.LWPCookieJar.__init__(self, filename, delayload, policy) if string and len(string) > 0: self._cookies = pickle.loads(str(string)) @@ -68,8 +68,8 @@ def init_urllib(cache=None): _cookie_jar = _StringCookieJar(data, cache=cache) else: _cookie_jar = _StringCookieJar(data) - opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(_cookie_jar)) - urllib2.install_opener(opener) + opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(_cookie_jar)) + urllib.request.install_opener(opener) def cache_cookies(cache=None): @@ -97,31 +97,31 @@ def _solve_http_errors(url, error): def request(url, headers={}): debug('request: %s' % url) - req = urllib2.Request(url, headers=headers) + req = urllib.request.Request(url, headers=headers) req.add_header('User-Agent', UA) if _cookie_jar is not None: _cookie_jar.add_cookie_header(req) try: - response = urllib2.urlopen(req) + response = urllib.request.urlopen(req) data = response.read() response.close() - except urllib2.HTTPError, error: + except urllib.error.HTTPError as error: data = _solve_http_errors(url, error) debug('len(data) %s' % len(data)) return data def post(url, data, headers={}): - postdata = urllib.urlencode(data) - req = urllib2.Request(url, postdata, headers) + postdata = urllib.parse.urlencode(data) + req = urllib.request.Request(url, postdata, headers) req.add_header('User-Agent', UA) if _cookie_jar is not None: _cookie_jar.add_cookie_header(req) try: - response = urllib2.urlopen(req) + response = urllib.request.urlopen(req) data = response.read() response.close() - except urllib2.HTTPError, error: + except urllib.error.HTTPError as error: data = _solve_http_errors(url, error) return data @@ -129,21 +129,21 @@ def post(url, data, headers={}): def post_json(url, data, headers={}): postdata = json.dumps(data) headers['Content-Type'] = 'application/json' - req = urllib2.Request(url, postdata, headers) + req = urllib.request.Request(url, postdata, headers) req.add_header('User-Agent', UA) if _cookie_jar is not None: _cookie_jar.add_cookie_header(req) try: - response = urllib2.urlopen(req) + response = urllib.request.urlopen(req) data = response.read() response.close() - except urllib2.HTTPError, error: + except urllib.error.HTTPError as error: data = _solve_http_errors(url, error) return data def run_parallel_in_threads(target, args_list): - result = Queue.Queue() + result = queue.Queue() # wrapper to collect return value in a Queue def task_wrapper(*args): @@ -169,7 +169,7 @@ def substr(data, start, end): def _create_plugin_url(params, plugin=sys.argv[0]): url = [] - for key in params.keys(): + for key in list(params.keys()): value = decode_html(params[key]) value = value.encode('ascii', 'ignore') url.append(key + '=' + value.encode('hex', ) + '&') @@ -209,15 +209,15 @@ def _substitute_entity(match): # decoding by number if match.group(2) == '': # number is in decimal - return unichr(int(ent)) + return chr(int(ent)) elif match.group(2) == 'x': # number is in hex - return unichr(int('0x' + ent, 16)) + return chr(int('0x' + ent, 16)) else: # they were using a name cp = n2cp.get(ent) if cp: - return unichr(cp) + return chr(cp) else: return match.group() @@ -226,13 +226,13 @@ def decode_html(data): if not type(data) == str: return data try: - if not type(data) == unicode: - data = unicode(data, 'utf-8', errors='ignore') + if not type(data) == str: + data = str(data, 'utf-8', errors='ignore') entity_re = re.compile(r'&(#?)(x?)(\w+);') return entity_re.subn(_substitute_entity, data)[0] except: traceback.print_exc() - print[data] + print([data]) return data @@ -250,35 +250,35 @@ def error(text): except: def debug(text): if LOG > 1: - print('[DEBUG] ' + str([text])) + print(('[DEBUG] ' + str([text]))) def info(text): if LOG > 0: - print('[INFO] ' + str([text])) + print(('[INFO] ' + str([text]))) def error(text): - print('[ERROR] ' + str([text])) - -_diacritic_replace = {u'\u00f3': 'o', - u'\u0213': '-', - u'\u00e1': 'a', - u'\u010d': 'c', - u'\u010c': 'C', - u'\u010f': 'd', - u'\u010e': 'D', - u'\u00e9': 'e', - u'\u011b': 'e', - u'\u00ed': 'i', - u'\u0148': 'n', - u'\u0159': 'r', - u'\u0161': 's', - u'\u0165': 't', - u'\u016f': 'u', - u'\u00fd': 'y', - u'\u017e': 'z', - u'\xed': 'i', - u'\xe9': 'e', - u'\xe1': 'a', + print(('[ERROR] ' + str([text]))) + +_diacritic_replace = {'\u00f3': 'o', + '\u0213': '-', + '\u00e1': 'a', + '\u010d': 'c', + '\u010c': 'C', + '\u010f': 'd', + '\u010e': 'D', + '\u00e9': 'e', + '\u011b': 'e', + '\u00ed': 'i', + '\u0148': 'n', + '\u0159': 'r', + '\u0161': 's', + '\u0165': 't', + '\u016f': 'u', + '\u00fd': 'y', + '\u017e': 'z', + '\xed': 'i', + '\xe9': 'e', + '\xe1': 'a', } @@ -309,7 +309,7 @@ def params(url=None): splitparams = pairsofparams[i].split('=') if (len(splitparams)) == 2: param[splitparams[0]] = splitparams[1] - for p in param.keys(): + for p in list(param.keys()): param[p] = param[p].decode('hex') return param @@ -344,7 +344,7 @@ def extract_jwplayer_setup(data): if data: replacements = data.group(2).split('|') data = data.group(1) - for i in reversed(range(len(replacements))): + for i in reversed(list(range(len(replacements)))): if len(replacements[i]) > 0: data = re.sub(r'\b%s\b' % int_to_base(i, 36), replacements[i], data) data = re.search(r'\.setup\(([^\)]+?)\);', data) diff --git a/lib/xbmcutil.py b/lib/xbmcutil.py index 2e9b5b2..59434a6 100644 --- a/lib/xbmcutil.py +++ b/lib/xbmcutil.py @@ -22,10 +22,10 @@ import os import re import sys -import urllib -import urllib2 +import urllib.request, urllib.parse, urllib.error +import urllib.request, urllib.error, urllib.parse import traceback -import cookielib +import http.cookiejar import time import socket import unicodedata @@ -33,7 +33,7 @@ import xbmcplugin import xbmc import xbmcaddon -from htmlentitydefs import name2codepoint as n2cp +from html.entities import name2codepoint as n2cp import json import util UA = 'Mozilla/6.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.5) Gecko/2008092417 Firefox/3.0.3' @@ -47,17 +47,17 @@ def init_urllib(): - cj = cookielib.LWPCookieJar() - opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) - urllib2.install_opener(opener) + cj = http.cookiejar.LWPCookieJar() + opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + urllib.request.install_opener(opener) def request(url, headers=None): if headers is None: headers = {} debug('request: %s' % url) - req = urllib2.Request(url, headers=headers) - response = urllib2.urlopen(req) + req = urllib.request.Request(url, headers=headers) + response = urllib.request.urlopen(req) data = response.read() response.close() debug('len(data) %s' % len(data)) @@ -65,10 +65,10 @@ def request(url, headers=None): def post(url, data): - postdata = urllib.urlencode(data) - req = urllib2.Request(url, postdata) + postdata = urllib.parse.urlencode(data) + req = urllib.request.Request(url, postdata) req.add_header('User-Agent', UA) - response = urllib2.urlopen(req) + response = urllib.request.urlopen(req) data = response.read() response.close() return data @@ -96,7 +96,7 @@ def add_dir(name, params, logo='', infoLabels={}, menuItems={}): except: traceback.print_exc() items = [] - for mi in menuItems.keys(): + for mi in list(menuItems.keys()): action = menuItems[mi] if not type(action) == type({}): items.append((mi, action)) @@ -124,7 +124,7 @@ def add_local_dir(name, url, logo='', infoLabels={}, menuItems={}): liz = xbmcgui.ListItem(name, iconImage='DefaultFolder.png', thumbnailImage=logo) liz.setInfo(type='Video', infoLabels=infoLabels) items = [] - for mi in menuItems.keys(): + for mi in list(menuItems.keys()): items.append((mi, 'RunPlugin(%s)' % _create_plugin_url(menuItems[mi]))) if len(items) > 0: liz.addContextMenuItems(items) @@ -144,7 +144,7 @@ def add_video(name, params={}, logo='', infoLabels={}, menuItems={}): li.addStreamInfo('video', {}) li.setProperty('IsPlayable', 'true') items = [(xbmc.getLocalizedString(13347), 'Action(Queue)')] - for mi in menuItems.keys(): + for mi in list(menuItems.keys()): action = menuItems[mi] if not type(action) == type({}): items.append((mi, action)) @@ -169,7 +169,7 @@ def add_video(name, params={}, logo='', infoLabels={}, menuItems={}): def _create_plugin_url(params, plugin=sys.argv[0]): url = [] - for key in params.keys(): + for key in list(params.keys()): value = decode_html(params[key]) #--value = value.encode('ascii','ignore') value = value.encode('utf-8') @@ -249,28 +249,28 @@ def _substitute_entity(match): # decoding by number if match.group(2) == '': # number is in decimal - return unichr(int(ent)) + return chr(int(ent)) elif match.group(2) == 'x': # number is in hex - return unichr(int('0x' + ent, 16)) + return chr(int('0x' + ent, 16)) else: # they were using a name cp = n2cp.get(ent) if cp: - return unichr(cp) + return chr(cp) else: return match.group() def decode_html(data): try: - if not type(data) == unicode: - data = unicode(data, 'utf-8', errors='ignore') + if not type(data) == str: + data = str(data, 'utf-8', errors='ignore') entity_re = re.compile(r'&(#?)(x?)(\w+);') return entity_re.subn(_substitute_entity, data)[0] except: traceback.print_exc() - print[data] + print([data]) return data @@ -345,7 +345,7 @@ def get_searches(addon, server): return [] f = open(c_local, 'r') data = f.read() - searches = json.loads(unicode(data.decode('utf-8', 'ignore'))) + searches = json.loads(str(data.decode('utf-8', 'ignore'))) f.close() return searches @@ -360,7 +360,7 @@ def add_search(addon, server, search, maximum): if os.path.exists(c_local): f = open(c_local, 'r') data = f.read() - searches = json.loads(unicode(data.decode('utf-8', 'ignore'))) + searches = json.loads(str(data.decode('utf-8', 'ignore'))) f.close() if search in searches: searches.remove(search) @@ -393,7 +393,7 @@ def remove_search(addon, server, search): if os.path.exists(c_local): f = open(c_local, 'r') data = f.read() - searches = json.loads(unicode(data.decode('utf-8', 'ignore'))) + searches = json.loads(str(data.decode('utf-8', 'ignore'))) f.close() searches.remove(search) f = open(c_local, 'w') @@ -422,7 +422,7 @@ def download(addon, filename, url, local, notifyFinishDialog=True, headers={}): notifyPercent = 5 def encode(string): - return u' '.join(string).encode('utf-8') + return ' '.join(string).encode('utf-8') def notify(title, message, time=3000): try: @@ -472,7 +472,7 @@ def __init__(self, callback=None): self.percent = -1 def download(self, remote, local, filename=None, headers={}): - class MyURLopener(urllib.FancyURLopener): + class MyURLopener(urllib.request.FancyURLopener): def http_error_default(self, url, fp, errcode, errmsg, headers): self.error_msg = 'Downlad failed, error : ' + str(errcode) @@ -514,23 +514,23 @@ def dlProgress(self, count, blockSize, totalSize): self.callback(percent, speed, est, self.filename) self.percent = percent -_diacritic_replace = {u'\u00f3': 'o', - u'\u0213': '-', - u'\u00e1': 'a', - u'\u010d': 'c', - u'\u010c': 'C', - u'\u010f': 'd', - u'\u010e': 'D', - u'\u00e9': 'e', - u'\u011b': 'e', - u'\u00ed': 'i', - u'\u0148': 'n', - u'\u0159': 'r', - u'\u0161': 's', - u'\u0165': 't', - u'\u016f': 'u', - u'\u00fd': 'y', - u'\u017e': 'z' +_diacritic_replace = {'\u00f3': 'o', + '\u0213': '-', + '\u00e1': 'a', + '\u010d': 'c', + '\u010c': 'C', + '\u010f': 'd', + '\u010e': 'D', + '\u00e9': 'e', + '\u011b': 'e', + '\u00ed': 'i', + '\u0148': 'n', + '\u0159': 'r', + '\u0161': 's', + '\u0165': 't', + '\u016f': 'u', + '\u00fd': 'y', + '\u017e': 'z' } @@ -549,6 +549,6 @@ def compat_path(path): if isinstance(path, str): path = path.decode('utf-8') else: - if isinstance(path, unicode): + if isinstance(path, str): path = path.encode('utf-8') return path