import requests
import datetime
from datetime import date
import json
import re
import keys

proxy_url = "http://servicecenterpay:CpPNjQs2GE@194.87.64.54:50100"
country_code = "it"
language_code = "it"
time_offset = 60
noLinearChannels = False #set True if you don't want get Linear Channels
pin = "" #pin to get 18+ channels

def getChannels():

    try:
        headers = {
            'sec-ch-ua': '"Google Chrome";v="113", "Chromium";v="113", "Not-A.Brand";v="24"',
            'sec-ch-ua-mobile': '?0',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36',
            'Content-Type': 'application/json',
            'X-DAZN-UA': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 signin/4.30.0.42 hyper/0.8.4 (web; production; gb)',
            'Z-DAZN-UA': 'bWFkZSBieSB0aGUgY29tbXVuaXR5IGF0IGRybXNjcmlwdHMuY29t',
            'Cache-Control': 'no-cache',
            'Referer': 'https://www.dazn.com/',
            'sec-ch-ua-platform': '"Windows"',
        }
        
        json_data = {
            'Email': 'lcdsrn@gmail.com',
            'Password': 'Tiamonapoli1926',
            'Platform': 'all',
            'DeviceId': '0000000000',
            'ProfilingSessionId': '0000000000000000000000',
        }
        
        if proxy_url:
           proxies = {
                    'http': proxy_url,
                    'https': proxy_url
           }  
        else:
           proxies = None
        
        try:
           with open("authorisationToken.txt") as ftoken:
              authorisationToken = ftoken.read()
              ftoken.close()
        except FileNotFoundError:
           with requests.post('https://authentication-prod.ar.indazn.com/v5/SignIn', headers=headers, json=json_data, proxies=proxies) as responseData:
              response = responseData
           data = response.json()
           authorisationToken = data.get("AuthToken", {}).get("Token")

           if authorisationToken:
              with open("authorisationToken.txt", "w") as f:
                f.write(authorisationToken)
           else:
              print('LOGIN FAILED')
              exit()
       
        today = date.today()
        url = f"https://epg.discovery.indazn.com/eu/v2/Epg?date={today.year}-{today.month:02d}-{today.day:02d}&country={country_code}&languageCode={language_code}&openBrowse=false&timeZoneOffset={time_offset}"
        
        with requests.get(url) as responseData:
           response = responseData
        data = response.json()
        assetid_list = []

        output = []
        for tile in data.get('Tiles', []):
         VideoType = tile.get('VideoType')
         IsLinear = tile.get('IsLinear')
         competition = tile.get('Competition', [{}]).get("Id")
         LaUrl = data.get("PlaybackDetails", [{}])[0].get("LaUrl")
         if ((noLinearChannels and VideoType == "Live" and not IsLinear) or (not noLinearChannels and VideoType == "Live")): 
            canali  = {}
            canali['asset_id'] = tile.get('AssetId')
            canali['start'] = tile.get('Start')
            canali['end'] = tile.get('End')
            canali['imageurl'] = f"https://image.discovery.indazn.com/jp/v3/jp/none/{tile['Image']['Id']}/fill/center/top/none/85/1920/1083/webp/image"
            # print(canali)
            output.append(canali)
        
        channels=[]
        count = 1
        for channel in output:
            params = {
                    'AssetId': '%s' % channel['asset_id'],
                    'PlayerId': 'test',
                    'DrmType': 'WIDEVINE',
                    'Platform': 'all',
                    'Format': 'MPEG-DASH',
                    'LanguageCode': 'it',
                    'Model': 'N/A',
                    'Secure': 'true',
                    'Latitude': 'null',
                    'Longitude': 'null',
                    'Manufacturer': 'unknown',
                    'PlayReadyInitiator': 'false',
                    'MtaLanguageCode': 'en',
                    'AppVersion': '9.29.0',
            }
            
            headers = {

               'sec-ch-ua': '"Google Chrome";v="113", "Chromium";v="113", "Not-A.Brand";v="24"',
               'Referer': 'https://www.dazn.com/',
               'sec-ch-ua-mobile': '?0',
               'Authorization': 'Bearer %s' % authorisationToken,
               'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36',
               'x-dazn-device': '00000000-0000-0000-0000-000000000000',
               'sec-ch-ua-platform': '"Windows"',
               'x-age-verification-pin': pin,
            }

            with requests.get('https://api.playback.indazn.com/v5/Playback', params=params, headers=headers, proxies=proxies) as responseData:
               response = responseData
            
            if response.status_code == 401:
               headers_refresh = {
                   'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:28.0) Gecko/20100101 Firefox/28.0',
		           'Content-Type': 'application/json',
	               'Authorization': 'Bearer %s' % authorisationToken,
            
               }
               json_data_refresh = {
                  'DeviceId': '0000000000'
          
               }
               with requests.post('https://ott-authz-bff-prod.ar.indazn.com/v5/RefreshAccessToken', headers=headers_refresh, json=json_data_refresh, proxies=proxies) as responseData:
                  response_refresh = responseData
               data_refresh = response_refresh.json()
               authorisationToken = data_refresh.get("AuthToken", {}).get("Token")
               with open("authorisationToken.txt", "w") as f:
                  f.write(authorisationToken)
               headers = {
                  'sec-ch-ua': '"Google Chrome";v="113", "Chromium";v="113", "Not-A.Brand";v="24"',
                  'Referer': 'https://www.dazn.com/',
                  'sec-ch-ua-mobile': '?0',
                  'Authorization': 'Bearer %s' % authorisationToken,
                  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36',
                  'x-dazn-device': '00000000-0000-0000-0000-000000000000',
                  'sec-ch-ua-platform': '"Windows"',
                  'x-age-verification-pin': pin,
               }
               with requests.get('https://api.playback.indazn.com/v5/Playback', params=params, headers=headers, proxies=proxies) as responseData:
                  response = responseData
            
            if response.status_code == 200:
                data = response.json()
                manifestUrl = data.get("PlaybackDetails", [{}])[0].get("ManifestUrl")
                LaUrl = data.get("PlaybackDetails", [{}])[0].get("LaUrl")
                eventTitle = data.get("Asset", {}).get("Title")
                kid_key = keys.getKeys(manifestUrl, LaUrl, authorisationToken)
                canale = {
                               "Id": str(count),
                               "Name" : eventTitle,
                               "mpdUrl" : manifestUrl,
                               "startDate" : channel['start'],
                               "endDate" : channel['end'],
                               "imageurl": channel['imageurl'],
                               "kid" : kid_key.split(":")[0],
                               "key": kid_key.split(":")[1]
                }
                channels.append(canale)
                count+=1
        return json.dumps(channels)
    except Exception as e:
        print("An error occurred: %s", str(e))
        
        

json_data = getChannels()
data = json.loads(json_data)
with open("output.json", 'w+') as f:
   json.dump(data, f, indent=2)

for item in data:
   name = item.get("Name", "")
   mpd_url = item.get("mpdUrl", "")
   # imageurl = item.get("imageurl", "")
   # keys = item.get("keys", "") 
   print(f"{name}\n{mpd_url}")
   # print(f"{name}\n{mpd_url}&decryption_key={keys}")




