示例#1
0
def login(plugin):
    method = Dialog().yesno("Login", "Select Login Method",
                            yeslabel="Keyboard", nolabel="WEB")
    if method == 1:
        login_type = Dialog().yesno("Login", "Select Login Type",
                                    yeslabel="OTP", nolabel="Password")
        if login_type == 1:
            mobile = keyboard("Enter your Jio mobile number")
            error = sendOTP(mobile)
            if error:
                Script.notify("Login Error", error)
                return
            otp = keyboard("Enter OTP", hidden=True)
            ULogin(mobile, otp, mode="otp")
        elif login_type == 0:
            username = keyboard("Enter your Jio mobile number or email")
            password = keyboard("Enter your password", hidden=True)
            ULogin(username, password)
    elif method == 0:
        pDialog = DialogProgress()
        pDialog.create(
            'JioTV', 'Visit [B]http://%s:48996/[/B] to login' % socket.gethostbyname(socket.gethostname()))
        for i in range(120):
            sleep(1)
            with PersistentDict("headers") as db:
                headers = db.get("headers")
            if headers or pDialog.iscanceled():
                break
            pDialog.update(i)
        pDialog.close()
示例#2
0
def check_token():
    with PersistentDict("userdata.pickle") as db:
        encoded_token = db.get("token")

    if encoded_token is None:
        return generate_token()

    #else check the token validity if not valid generate again
    try:
        decoded = jwt.decode(encoded_token,
                             options={
                                 "verify_signature": False,
                                 "verify": False
                             })
        exp_time_stamp = decoded["exp"]
        #print(exp_time_stamp)

        current_timestamp = time.time()
        current_timestamp = round(current_timestamp)
        #print(current_timestamp)

        if current_timestamp < exp_time_stamp:
            return True
        else:
            return generate_token()
    except:
        return False

    return False
示例#3
0
 def login_wrapper(*args, **kwargs):
     with PersistentDict("headers") as db:
         username = db.get("username")
         password = db.get("password")
         headers = db.get("headers")
         exp = db.get("exp", 0)
     if headers and exp > time.time():
         return func(*args, **kwargs)
     elif username and password:
         login(username, password)
         return func(*args, **kwargs)
     elif headers and exp < time.time():
         Script.notify("Login Error", "Session expired. Please login again")
         executebuiltin(
             "RunPlugin(plugin://plugin.video.jiotv/resources/lib/main/login/)"
         )
         return False
     else:
         Script.notify(
             "Login Error",
             "You need to login with Jio Username and password to use this add-on"
         )
         executebuiltin(
             "RunPlugin(plugin://plugin.video.jiotv/resources/lib/main/login/)"
         )
         return False
 def _refreshToken(self):
     try:
         with PersistentDict("userdata.pickle") as db:
             oldToken = db.get("token")
             if oldToken:
                 resp = self.session.get(url_constructor(
                     "/in/aadhar/v2/firetv/in/users/refresh-token"),
                                         headers={
                                             "userIdentity":
                                             oldToken,
                                             "deviceId":
                                             db.get("deviceId",
                                                    str(uuid4()))
                                         },
                                         raise_for_status=False,
                                         max_age=-1).json()
                 if resp.get("errorCode"):
                     return resp.get("message")
                 new_token = deep_get(resp, "description.userIdentity")
                 db['token'] = new_token
                 db.flush()
                 return new_token
         return False
     except Exception as e:
         return e
    def __init__(self):
        super(SavedSearches, self).__init__()

        # Persistent list of currently saved searches
        self.search_db = PersistentDict(SEARCH_DB)
        self.register_delayed(self.close)
        self.session_data = None  # type: list
示例#6
0
    def __init__(self, plugin, extra_params):
        # The saved search persistent storage
        self.db = search_db = PersistentDict(SEARCH_DB)
        plugin.register_delayed(search_db.close)

        # Fetch saved data specific to this session
        session_hash = self.hash_params(extra_params)
        self.data = search_db.setdefault(session_hash, [])
    def getTray(self, url, search_query=None):
        if search_query:
            url = url_constructor("/s/v1/scout?q=%s&size=30" %
                                  quote_plus(search_query))
        if "persona" in url:
            with PersistentDict("userdata.pickle") as db:
                pid = db.get("udata", {}).get("pId")
            results = self.get(url.format(pid=pid),
                               headers={
                                   "hotstarauth":
                                   self._getAuth(includeST=True, persona=True)
                               })
            # ids = ",".join(map(lambda x: x.get("item_id"),
            #                deep_get(results, "data.items")))
            # url = url_constructor("/o/v1/multi/get/content?ids=" + ids)
        else:
            results = self.get(url)

        if "data" in results:
            results = results.get("data")
            if "progress_meta" in results and type(
                    results.get("items")) is dict:
                for cID, data in results.get("progress_meta").items():
                    results["items"][cID].update(data)
        else:
            results = deep_get(results, "body.results")

        if results:
            items = results.get("items") or deep_get(
                results, "assets.items") or (results.get("map") and list(
                    results.get("map").values())) or deep_get(
                        results, "trays.items") or []
            if type(items) is dict:
                items = list(items.values())
            nextPageUrl = deep_get(
                results,
                "assets.nextOffsetURL") or results.get("nextOffsetURL")

            totalResults = deep_get(
                results, "assets.totalResults") or results.get("totalResults")
            offset = deep_get(results,
                              "assets.offset") or results.get("offset")
            allResultsPageUrl = None
            if len(items) > 0 and nextPageUrl is not None and (
                    "/season/" in nextPageUrl or items[0].get("assetType")
                    == "EPISODE") and totalResults is not None:
                allResultsPageUrl = updateQueryParams(
                    nextPageUrl, {
                        "size": str(totalResults),
                        "tas": str(totalResults),
                        "offset": "0"
                    })

            if deep_get(results, "channelClip.clipType", "") == "LIVE":
                items.insert(0, deep_get(results, "channelClip", {}))

            return items, nextPageUrl, allResultsPageUrl
        return [], None, None
 def _getPlayParams(subTag="", encryption="widevine"):
     with PersistentDict("userdata.pickle") as db:
         deviceId = db.get("deviceId")
     return {
         "os-name": "firetv",
         "desired-config": "audio_channel:stereo|encryption:%s|ladder:tv|package:dash|%svideo_codec:h264" % (encryption, subTag or ""),
         "device-id": str(deviceId),
         "os-version": "8.1.0"
     }
    def _handleError(self, e, url, _rtype, **kwargs):
        if e.__class__.__name__ == "ValueError":
            Script.log("Can not parse response of request url %s" % url,
                       lvl=Script.DEBUG)
            Script.notify("Internal Error", "")
        elif e.__class__.__name__ == "HTTPError":
            if e.response.status_code == 402 or e.response.status_code == 403:
                with PersistentDict("userdata.pickle") as db:
                    if db.get("isGuest"):
                        Script.notify("Login Error",
                                      "Please login to watch this content")
                        executebuiltin(
                            "RunPlugin(plugin://plugin.video.botallen.hotstar/resources/lib/main/login/)"
                        )
                    else:
                        Script.notify(
                            "Subscription Error",
                            "You don't have valid subscription to watch this content",
                            display_time=2000)
            elif e.response.status_code == 401:
                new_token = self._refreshToken()
                if new_token:
                    kwargs.get("headers") and kwargs['headers'].update(
                        {"X-HS-UserToken": new_token})
                    if _rtype == "get":
                        return self.get(url, **kwargs)
                    else:
                        return self.post(url, **kwargs)
                else:
                    Script.notify("Token Error", "Token not found")

            elif e.response.status_code == 474 or e.response.status_code == 475:
                Script.notify("VPN Error",
                              "Your VPN provider does not support Hotstar")
            elif e.response.status_code == 404 and e.response.headers.get(
                    "Content-Type") == "application/json":
                if e.response.json().get("errorCode") == "ERR_PB_1412":
                    Script.notify("Network Error",
                                  "Use Jio network to play this content")
            else:
                Script.notify(
                    "Invalid Response",
                    "{0}: Invalid response from server".format(
                        e.response.status_code))
            return False
        else:
            Script.log(
                "{0}: Got unexpected response for request url {1}".format(
                    e.__class__.__name__, url),
                lvl=Script.DEBUG)
            Script.notify(
                "API Error",
                "Raise issue if you are continuously facing this error")
            raise e
示例#10
0
 def login_wrapper(*args, **kwargs):
     with PersistentDict("userdata.pickle") as db:
         data = db.get("data")
     if data:
         return func(*args, **kwargs)
     else:
         # login require
         Script.notify("Login Error", "Please login to use this add-on")
         executebuiltin(
             "RunPlugin(plugin://plugin.video.jiotvplus/resources/lib/main/login/)")
         return False
示例#11
0
 def _getPlayHeaders(includeST=False):
     with PersistentDict("userdata.pickle") as db:
         token = db.get("token")
     return {
         "hotstarauth": HotstarAPI._getAuth(includeST),
         "X-Country-Code": "in",
         "X-HS-AppVersion": "3.3.0",
         "X-HS-Platform": "firetv",
         "X-HS-UserToken": token,
         "User-Agent": "Hotstar;in.startv.hotstar/3.3.0 (Android/8.1.0)"
     }
示例#12
0
 def _refreshToken(self):
     with PersistentDict("userdata.pickle") as db:
         oldToken = db.get("token")
         if oldToken:
             resp = self.get(url_constructor(
                 "/in/aadhar/v2/firetv/in/users/refresh-token"),
                             headers={
                                 "userIdentity": oldToken,
                                 "deviceId": db.get("deviceId")
                             })
             new_token = deep_get(resp, "description.userIdentity")
             db['token'] = new_token
示例#13
0
 def doLogin(self):
     with PersistentDict("userdata.pickle") as db:
         try:
             username = Settings.get_string(
                 "username",
                 "plugin.video.jiotv") or db.get("username") or Dialog(
                 ).input("Username (MobileNo / Email)")
             password = Settings.get_string(
                 "password", "plugin.video.jiotv") or db.get(
                     "password") or Dialog().input("Password")
         except RuntimeError:
             username = Dialog().input("Username (MobileNo / Email)")
             password = Dialog().input("Password")
         if username and password:
             body = {
                 "identifier":
                 username if '@' in username else "+91" + username,
                 "password": password,
                 "rememberUser": "******",
                 "upgradeAuth": "Y",
                 "returnSessionDetails": "T",
                 "deviceInfo": {
                     "consumptionDeviceName": "Jio",
                     "info": {
                         "type": "android",
                         "platform": {
                             "name": "vbox86p",
                             "version": "8.0.0"
                         },
                         "androidId": "6fcadeb7b4b10d77"
                     }
                 }
             }
             resp = urlquick.post(
                 "https://api.jio.com/v3/dip/user/unpw/verify",
                 json=body,
                 headers={
                     "x-api-key": "l7xx75e822925f184370b2e25170c5d5820a"
                 },
                 verify=False,
                 raise_for_status=False).json()
             if resp.get("ssoToken"):
                 db["data"] = resp
                 Script.notify("Login Successful",
                               "You have been logged in successfully")
             else:
                 Script.notify(
                     "Login Failed",
                     "Double check you username and password and try again")
         else:
             Script.notify("Login Required",
                           "Please login with you Jio credentials")
示例#14
0
    def login_wrapper(*args, **kwargs):

        with PersistentDict("creds") as db:
            username = db.get("username")
            password = db.get("password")

        # token is 5 days old ?
        with PersistentDict("headers") as db:
            headers = db.get("headers")
        if headers:
            return func(*args, **kwargs)
        elif username and password:
            login(username, password)
            return func(*args, **kwargs)
        else:
            Script.notify(
                'Login Error',
                'You need to login with Jio Username and password to use this add-on'
            )
            executebuiltin(
                "RunPlugin(plugin://plugin.video.jiotv/resources/lib/main/login/)"
            )
            return False
示例#15
0
def login(username, password):
    body = {
        "identifier": username if '@' in username else "+91" + username,
        "password": password,
        "rememberUser": "******",
        "upgradeAuth": "Y",
        "returnSessionDetails": "T",
        "deviceInfo": {
            "consumptionDeviceName": "Jio",
            "info": {
                "type": "android",
                "platform": {
                    "name": "vbox86p",
                    "version": "8.0.0"
                },
                "androidId": "6fcadeb7b4b10d77"
            }
        }
    }
    resp = urlquick.post(
        "https://api.jio.com/v3/dip/user/unpw/verify",
        headers={"x-api-key": "l7xx938b6684ee9e4bbe8831a9a682b8e19f"},
        json=body,
        verify=False)
    if resp.status_code == 200 and resp.json()['ssoToken']:
        data = resp.json()
        _CREDS = {
            "ssotoken": data['ssoToken'],
            "userId": data['sessionAttributes']['user']['uid'],
            "uniqueId": data['sessionAttributes']['user']['unique'],
            "crmid": data['sessionAttributes']['user']['subscriberId']
        }
        headers = {
            "User-Agent": "JioTV Kodi",
            "os": "Kodi",
            "deviceId": str(uuid4()),
            "versionCode": "226",
            "devicetype": "Kodi",
            "srno": "200206173037",
            "appkey": "NzNiMDhlYzQyNjJm",
            "channelid": "100",
            "usergroup": "tvYR7NSNn7rymo3F",
            "lbcookie": "1"
        }
        headers.update(_CREDS)
        with PersistentDict("headers", ttl=432000) as db:
            db["headers"] = headers
    else:
        Script.notify('Login Failed', 'Invalid credentials')
示例#16
0
 def _refreshToken(self):
     try:
         with PersistentDict("userdata.pickle") as db:
             oldToken = db.get("token")
             if oldToken:
                 resp = self.session.get(url_constructor("/in/aadhar/v2/firetv/in/users/refresh-token"),
                                         headers={"userIdentity": oldToken, "deviceId": db.get("deviceId")}, raise_for_status=False).json()
                 if resp.get("errorCode"):
                     return resp.get("message")
                 new_token = deep_get(resp, "description.userIdentity")
                 db['token'] = new_token
                 return True
             return "Token not found"
     except Exception, e:
         return e
示例#17
0
 def login_wrapper(*args, **kwargs):
     with PersistentDict("userdata.pickle") as db:
         if db.get("token"):
             return func(*args, **kwargs)
         elif db.get("isGuest") is None:
             db["token"] = guestToken()
             db["isGuest"] = True
             db.flush()
             return func(*args, **kwargs)
         else:
             # login require
             Script.notify(
                 "Login Error", "Please login to watch this content")
             executebuiltin(
                 "RunPlugin(plugin://plugin.video.botallen.hotstar/resources/lib/main/login/)")
             return False
示例#18
0
 def _getPlayHeaders(includeST=False, playbackUrl=None):
     with PersistentDict("userdata.pickle") as db:
         token = db.get("token")
     if playbackUrl:
         parsed_url = urlparse(playbackUrl)
         qs = parse_qs(parsed_url.query)
         hdnea = "hdnea=%s;" % qs.get("hdnea")[0]
     return {
         "hotstarauth": HotstarAPI._getAuth(includeST),
         "X-Country-Code": "in",
         "X-HS-AppVersion": "3.3.0",
         "X-HS-Platform": "firetv",
         "X-HS-UserToken": token,
         "Cookie": playbackUrl and hdnea,
         "User-Agent": "Hotstar;in.startv.hotstar/3.3.0 (Android/8.1.0)"
     }
示例#19
0
 def login_wrapper(*args, **kwargs):
     with PersistentDict("userdata.pickle") as db:
         if db.get("token"):
             return func(*args, **kwargs)
         elif db.get("isGuest") is None:
             db["token"] = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJ1bV9hY2Nlc3MiLCJleHAiOjE1ODY3OTEzMzEsImlhdCI6MTU4NjcwNDkzMSwiaXNzIjoiVFMiLCJzdWIiOiJ7XCJjb3VudHJ5Q29kZVwiOlwiaW5cIixcImN1c3RvbWVyVHlwZVwiOlwibnVcIixcImRldmljZUlkXCI6XCI4OTUyYWE5ZS1mZGY5LTQ2ZTMtYjU2Mi1jNTViMzdjZTMyYTdcIixcImhJZFwiOlwiMDBkY2FkN2M4NmQ4NDJiNTgxYmU4Mjg4OTRjMWYyMzRcIixcImlwXCI6XCIxMDMuMjEyLjE0MS4yNFwiLFwiaXNFbWFpbFZlcmlmaWVkXCI6ZmFsc2UsXCJpc1Bob25lVmVyaWZpZWRcIjpmYWxzZSxcImlzc3VlZEF0XCI6MTU4NjcwNDkzMTUzMSxcIm5hbWVcIjpcIkd1ZXN0IFVzZXJcIixcInBJZFwiOlwiNTQ1ZmQzNmE1NWM4NGExNWFkOTE3OGNlYWFhZmI0YTBcIixcInByb2ZpbGVcIjpcIkFEVUxUXCIsXCJzdWJzY3JpcHRpb25zXCI6e1wiaW5cIjp7fX0sXCJ0eXBlXCI6XCJkZXZpY2VcIixcInZlcnNpb25cIjpcInYyXCJ9IiwidmVyc2lvbiI6IjFfMCJ9.X1uJowi4-4eVquBDdTis76pbH44gso1y16i5zKTwRfg"
             db["isGuest"] = True
             db.flush()
             return func(*args, **kwargs)
         else:
             # login require
             Script.notify(
                 "Login Error", "Please login to watch this content")
             executebuiltin(
                 "RunPlugin(plugin://plugin.video.botallen.hotstar/resources/lib/main/login/)")
             return False
示例#20
0
    def refine(self, text, quality=False):
        if self.ishls:
            rpls_regx = "{{0}}/{{1}}/{{2}}_HLS/{0}\g<2>".format(quality)
            text = re.sub(
                '(\d{1})([\-\_]?\d+\.ts)', rpls_regx.format(SERVER, self.hlsrx, self.channel_name), text)
            return text.replace('https://tv.media.jio.com/streams_live', SERVER+'/streams_live')
        elif quality:
            rpls_regx = "_{}".format(quality) if quality else "_\g<1>"
            text = re.sub('\_(\d{3,4})\-', rpls_regx+"-", text)
            with PersistentDict("proxy_cache", ttl=180) as cache:
                allkeys = re.findall(
                    self.channel_name+"\_\d{3,4}\-\d{13}\.key", text)
                Script.log("Found %d different keys" %
                           len(allkeys), lvl=Script.DEBUG)
                diff = None
                for key in allkeys:
                    original_timestamp = re.search(
                        "\-(\d{13})\.key", key).group(1)
                    if cache.get(key):
                        timestamp, newIV = cache.get(key)
                        Script.log("Using cached timestamp %s" %
                                   timestamp, lvl=Script.DEBUG)
                    elif diff:
                        timestamp = int(original_timestamp) - int(diff)
                        newIV = '0x%0*X' % (32, int(timestamp))
                        cache[key] = (timestamp, newIV)
                        Script.log("Using diff predicted timestamp %s" %
                                   timestamp, lvl=Script.DEBUG)
                    else:
                        timestamp = self._find_valid_key(key)
                        diff = int(original_timestamp) - int(timestamp)
                        newIV = '0x%0*X' % (32, int(timestamp))
                        cache[key] = (timestamp, newIV)
                        Script.log("Using new valid timestamp %s" %
                                   timestamp, lvl=Script.DEBUG)

                    Script.log("Replacing old IV with %s" %
                               newIV, lvl=Script.DEBUG)
                    text = re.sub('(\_\d{{3,4}}\-){0}(\.key\",IV=)[\w\d]*'.format(original_timestamp),
                                  "\g<1>{0}\g<2>{1}".format(timestamp, newIV), text)
            return text.replace("https://tv.media.jio.com/streams_live/{0}/".format(self.channel_name), "")
        else:
            rpls_regx = "{0}/{1}/\g<1>".format(SERVER, self.channel_name)
            text = re.sub(
                '([\w_\/:\.]*\_\d{3,4}\-\d{13}\.ts)', rpls_regx, text)
            return text
示例#21
0
 def doLogin(self):
     try:
         username = Settings.get_string(
             "username", "plugin.video.jiotvx") or Dialog().input(
                 "Username (MobileNo / Email)")
         password = Settings.get_string(
             "password",
             "plugin.video.jiotvx") or Dialog().input("Password")
     except RuntimeError:
         username = Dialog().input("Username (MobileNo / Email)")
         password = Dialog().input("Password")
     if username and password:
         body = {
             "identifier":
             username if "@" in username else "+91" + username,
             "password": password,
             "rememberUser": "******",
             "upgradeAuth": "Y",
             "returnSessionDetails": "T",
             "deviceInfo": {
                 "consumptionDeviceName": "unknown sdk_google_atv_x86",
                 "info": {
                     "type": "android",
                     "platform": {
                         "name": "generic_x86",
                         "version": "8.1.0"
                     },
                     "androidId": str(uuid4())
                 }
             }
         }
         resp = self.post(
             "https://api.jio.com/v3/dip/user/unpw/verify",
             json=body,
             headers={"x-api-key": "l7xx75e822925f184370b2e25170c5d5820a"})
         if resp.get("ssoToken"):
             with PersistentDict("userdata.pickle") as db:
                 db["data"] = resp
         else:
             Script.notify(
                 "Login Failed",
                 "Double check you username and password and try again")
     else:
         Script.notify("Login Required",
                       "Please login with you Jio credentials")
示例#22
0
 def doLogin(self):
     url = url_constructor("/in/aadhar/v2/firetv/in/users/logincode/")
     resp = self.post(url, headers={"Content-Length": "0"})
     code = deep_get(resp, "description.code")
     yield (code, 1)
     for i in range(2, 101):
         resp = self.get(url + code, max_age=-1)
         token = deep_get(resp, "description.userIdentity")
         if token:
             with PersistentDict("userdata.pickle") as db:
                 db["token"] = token
                 db["deviceId"] = uuid4()
                 db["udata"] = json.loads(
                     b64decode(token.split(".")[1] + "========"))
                 db.flush()
             yield code, 100
             break
         yield code, i
示例#23
0
 def _getLiveHeaders():
     with PersistentDict("userdata.pickle") as db:
         data = db.get("data")
     return {
         "appkey": "2ccce09e59153fc9",
         "uniqueId": deep_get(data, "sessionAttributes.user.unique"),
         "srno": "200414205625",
         "channelid": "100",
         "userId": deep_get(data, "sessionAttributes.user.uid"),
         "User-Agent": "Jiotv+ Kodi",
         "versionCode": "226",
         "ssotoken": data.get("ssoToken"),
         "devicetype": "Kodi",
         "deviceId": str(uuid4()),
         "crmid": deep_get(data, "sessionAttributes.user.subscriberId"),
         "usergroup": "tvYR7NSNn7rymo3F",
         "lbcookie": "1",
         "os": "Kodi"
     }
示例#24
0
    def _handleError(self, e, url, _rtype, **kwargs):
        if e.__class__.__name__ == "ValueError":
            Script.log("Can not parse response of request url %s" % url,
                       lvl=Script.DEBUG)
            Script.notify("Internal Error", "")
        elif e.__class__.__name__ == "HTTPError":
            if e.code == 402 or e.code == 403:
                with PersistentDict("userdata.pickle") as db:
                    if db.get("isGuest"):
                        Script.notify("Login Error",
                                      "Please login to watch this content")
                        executebuiltin(
                            "RunPlugin(plugin://plugin.video.botallen.hotstar/resources/lib/main/login/)"
                        )
                    else:
                        Script.notify(
                            "Subscription Error",
                            "You don't have valid subscription to watch this content"
                        )
            elif e.code == 401:
                new_token = self._refreshToken()
                if new_token:
                    kwargs.get("headers") and kwargs['headers'].update(
                        {"X-HS-UserToken": new_token})
                    if _rtype == "get":
                        return self.get(url, **kwargs)
                    else:
                        return self.post(url, **kwargs)
                else:
                    Script.notify("Token Error", "Token not found")

            elif e.code == 474 or e.code == 475:
                Script.notify("VPN Error",
                              "Your VPN provider does not support Hotstar")
            else:
                raise urlquick.HTTPError(e.filename, e.code, e.msg, e.hdrs)
            return False
        else:
            Script.log("Got unexpected response for request url %s" % url,
                       lvl=Script.DEBUG)
            Script.notify(
                "API Error",
                "Raise issue if you are continuously facing this error")
 def _getPlayHeaders(includeST=False, playbackUrl=None, extra={}):
     with PersistentDict("userdata.pickle") as db:
         token = db.get("token")
     auth = HotstarAPI._getAuth(includeST)
     headers = {
         "hotstarauth": auth,
         "X-Country-Code": "in",
         "X-HS-AppVersion": "3.3.0",
         "X-HS-Platform": "firetv",
         "X-HS-UserToken": token,
         "User-Agent": "Hotstar;in.startv.hotstar/3.3.0 (Android/8.1.0)",
         **extra,
     }
     if playbackUrl:
         r = Request(playbackUrl)
         r.add_header("User-Agent", headers.get("User-Agent"))
         cookie = urlopen(r).headers.get("Set-Cookie", "").split(";")[0]
         if cookie:
             headers["Cookie"] = cookie
     return headers
示例#26
0
    def resolveTS(self):
        ts = self.path.split('/')[-1]

        effective_url = "{2}/{0}/{1}".format(
            self.channel_name, ts, SERVER)
        resp = urlquick.get(effective_url, raise_for_status=False, max_age=-1)

        if resp.status_code == 404:
            with PersistentDict("proxy_cache", ttl=180) as cache:
                if cache.get(ts):
                    Script.log("Found cached ts effective url",
                               lvl=Script.DEBUG)
                    resp = urlquick.get(
                        cache.get(ts), raise_for_status=False, max_age=-1)
                else:
                    for i in range(1, 5):
                        timestamp = re.search("\-(\d{13})\.ts", ts).group(1)
                        ts = ts.replace(timestamp, str(int(timestamp)+(i*2000))
                                        if i % 2 == 0 else str(int(timestamp)-(i*2000)))
                        effective_url = "{2}/{0}/{1}".format(
                            self.channel_name, ts, SERVER)
                        resp = urlquick.get(
                            effective_url, raise_for_status=False, max_age=-1)
                        if resp.status_code == 200:
                            cache[ts] = effective_url
                            break
        if resp.status_code == 200:
            self.proxy.send_response(resp.status_code, 'OK')
            self.proxy.send_header('Content-Type', 'video/mp2t')
            self.proxy.send_header('Connection', 'keep-alive')
            self.proxy.send_header('Content-Length', len(resp.content))
            self.proxy.end_headers()
            self.proxy.wfile.write(resp.content)
        elif resp.status_code == 411 or resp.status_code == 451:
            Script.notify(
                "Error", "JioTV can not be accessed from outside India")
            self.proxy.send_error(resp.status_code)
        elif resp.status_code >= 400:
            self.proxy.send_error(resp.status_code)
        else:
            self.proxy.send_response(resp.status_code)
示例#27
0
 def _getPlayHeaders():
     with PersistentDict("userdata.pickle") as db:
         data = db.get("data")
     return {
         "ssotoken": data.get("ssoToken"),
         "x-multilang": "true",
         "appkey": "2ccce09e59153fc9",
         "x-apisignatures": "543aba07839",
         "devicetype": "tv",
         "os": "Android",
         "User-Agent": "Jiotv+ Kodi",
         "AppName": "Jiotv+",
         "deviceId": str(uuid4()),
         "ua": "JioCinemaAndroidOS",
         "subid": deep_get(data, "sessionAttributes.user.subscriberId"),
         "lbcookie": "1",
         "AppVersion": "62"
     }, {
         "uniqueId": deep_get(data, "sessionAttributes.user.unique"),
         "bitrateProfile": "xxhdpi"
     }
示例#28
0
def login(plugin):
    isKeyboard = Dialog().yesno("Login",
                                "Select Login Type",
                                yeslabel="Keyboard",
                                nolabel="WEB")
    if isKeyboard:
        username = keyboard("Enter your Jio mobile number or email")
        password = keyboard("Enter your password", hidden=True)
        ULogin(username, password)
    else:
        pDialog = DialogProgress()
        pDialog.create(
            'JioTV', 'Visit [B]http://%s:48996/web/login[/B] to login' %
            socket.gethostbyname(socket.gethostname()))
        for i in range(120):
            sleep(1)
            with PersistentDict("headers") as db:
                headers = db.get("headers")
            if headers or pDialog.iscanceled():
                break
            pDialog.update(i)
        pDialog.close()
示例#29
0
def generate_token():

    headers = {
        'authority': 'prod-api.viewlift.com',
        'sec-ch-ua':
        '"Google Chrome";v="87", " Not;A Brand";v="99", "Chromium";v="87"',
        'accept': 'application/json, text/plain, */*',
        'sec-ch-ua-mobile': '?0',
        'user-agent':
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36',
        'x-api-key': 'dtGKRIAd7y3mwmuXGk63u3MI3Azl1iYX8w9kaeg3',
        'content-type': 'application/json;charset=UTF-8',
        'origin': 'https://www.aha.video',
        'sec-fetch-site': 'cross-site',
        'sec-fetch-mode': 'cors',
        'sec-fetch-dest': 'empty',
        'referer': 'https://www.aha.video/',
        'accept-language': 'en-US,en-IN;q=0.9,en;q=0.8',
    }
    try:
        data = '{{"email":"{0}","password":"******"}}'.format(
            Addon().getSetting("email"),
            Addon().getSetting("password"))
        response = requests.post(
            'https://prod-api.viewlift.com/identity/signin?site=aha-tv&deviceId=browser-6c83ee48-b374-5a1e-c1fe-8fbd579f1b7b',
            headers=headers,
            data=str(data))
        encoded_token = response.json()["authorizationToken"]

        with PersistentDict("userdata.pickle") as db:
            db["token"] = encoded_token
        return True
    except Exception:
        Script.notify("Error",
                      "Unable to Generate Token.Please check the credential",
                      Script.NOTIFY_ERROR)
        return False
示例#30
0
    def _buildItem(self, item):

        if item.get("assetType") in ["CHANNEL", "GENRE", "GAME", "LANGUAGE", "SHOW", "SEASON"]:
            callback = self.callbackRefs.get("menu_list") if item.get("assetType") == "GAME" or item.get(
                "pageType") == "HERO_LANDING_PAGE" else self.callbackRefs.get("tray_list")
            params = {"url": url_constructor(
                "/o/v1/tray/g/2/items?eid=%d&etid=2&tao=0&tas=100" % item.get("id")) if item.get("assetType") == "SHOW" else item.get("uri")}
        else:
            if item.get("isSubTagged"):
                with PersistentDict("userdata.pickle") as db:
                    subtag = deep_get(dict(db), "udata.subscriptions.in")
                if subtag:
                    subtag = subtag.keys()[0]
                    Script.log("Using subtag from subscription: %s" %
                               subtag, lvl=Script.DEBUG)
                else:
                    resp = urlquick.get(
                        item.get("uri"), headers=BASE_HEADERS).json()
                    item = deep_get(resp, "body.results.item")
                    if item.get("features", [{}])[0].get("subType"):
                        subtag = item.get("features", [{}])[
                            0].get("subType")
                        Script.log("Using subtag %s" %
                                   subtag, lvl=Script.DEBUG)
                    else:
                        subtag = "HotstarPremium"
                        Script.log("No subType found.Using subtag %s as default" %
                                   subtag, lvl=Script.DEBUG)
            callback = self.callbackRefs.get("play_vod")
            params = {
                "contentId": item.get("contentId"),
                "subtag": item.get("isSubTagged") and "subs-tag:%s|" % subtag,
                "label": item.get("title"),
                "drm": "com.widevine.alpha" if item.get("encrypted") else False
            }

        return {
            "label": "Season %d (%d) " % (
                item.get("seasonNo"), item.get("episodeCnt")) if item.get("assetType") == "SEASON" else item.get("title"),
            "art": {
                "icon": IMG_THUMB_H_URL % deep_get(item, "images.h"),
                "thumb": IMG_THUMB_H_URL % deep_get(item, "images.h"),
                "fanart": IMG_FANART_H_URL % deep_get(item, "images.h"),
                "poster": IMG_POSTER_V_URL % deep_get(item, "images.v")
            },
            "info": {
                "genre": item.get("genre"),
                "year": item.get("year"),
                "episode": item.get("episodeCnt"),
                "season": item.get("seasonNo") or item.get("seasonCnt"),
                "mpaa": item.get("parentalRatingName"),
                "plot": item.get("description"),
                "title": item.get("title"),
                "sorttitle": item.get("shortTitle"),
                "duration": item.get("duration"),
                "studio": item.get("cpDisplayName"),
                "premiered": item.get("startDate") and datetime.fromtimestamp(item.get("startDate")).strftime("%Y-%m-%d"),
                "path": "",
                "trailer": "",
                "dateadded": item.get("startDate") and datetime.fromtimestamp(item.get("startDate")).strftime("%Y-%m-%d"),
                "mediatype": MEDIA_TYPE.get(item.get("assetType"))
            },
            "properties": {
                "IsPlayable": False
            },
            "stream": {
                # "video_codec": "h264",
                "width": "1920",
                "height": "1080",
                # "audio_codec": "aac"
            },
            "callback": callback,
            "params": params
        }