# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/cloudflare.py
import sys, traceback, urllib2, re, urllib, os

def createCookie(url, cj = None, agent = 'Mozilla/5.0 (Windows NT 6.1; rv:32.0) Gecko/20100101 Firefox/32.0'):
    urlData = ''
    try:
        import urlparse, cookielib, urllib2

        class NoRedirection(urllib2.HTTPErrorProcessor):

            def http_response(self, request, response):
                return response

        def parseJSString(s):
            try:
                offset = 1 if s[0] == '+' else 0
                val = int(eval(s.replace('!+[]', '1').replace('!![]', '1').replace('[]', '0').replace('(', 'str(')[offset:]))
                return val
            except:
                pass

        if cj == None:
            cj = cookielib.CookieJar()
        opener = urllib2.build_opener(NoRedirection, urllib2.HTTPCookieProcessor(cj))
        opener.addheaders = [('User-Agent', agent)]
        response = opener.open(url)
        result = urlData = response.read()
        response.close()
        jschl = re.compile('name="jschl_vc" value="(.+?)"/>').findall(result)[0]
        init = re.compile('setTimeout\\(function\\(\\){\\s*.*?.*:(.*?)};').findall(result)[0]
        builder = re.compile("challenge-form\\'\\);\\s*(.*)a.v").findall(result)[0]
        decryptVal = parseJSString(init)
        lines = builder.split(';')
        for line in lines:
            if len(line) > 0 and '=' in line:
                sections = line.split('=')
                line_val = parseJSString(sections[1])
                decryptVal = int(eval(str(decryptVal) + sections[0][-1] + str(line_val)))

        answer = decryptVal + len(urlparse.urlparse(url).netloc)
        u = '/'.join(url.split('/')[:-1])
        query = '%s/cdn-cgi/l/chk_jschl?jschl_vc=%s&jschl_answer=%s' % (u, jschl, answer)
        if 'type="hidden" name="pass"' in result:
            passval = re.compile('name="pass" value="(.*?)"').findall(result)[0]
            query = '%s/cdn-cgi/l/chk_jschl?jschl_vc=%s&pass=%s&jschl_answer=%s' % (u,
             jschl,
             urllib.quote_plus(passval),
             answer)
            print query
            query = query.replace('channels/', '')
            print query
            os.system('sleep 8')
        response = opener.open(query)
        response.close()
        return urlData
    except:
        traceback.print_exc(file=sys.stdout)
        return urlData

    return