import requests
from subprocess import call
import sys
from os import path
from time import sleep

headersforadobe = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0', 'ap_z': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0',
		'ap_11': 'Win32','Ap_42': 'anonymous'}
		
authtoken_adobe = '<signatureInfo>NDOVXOHraEzX1qXRrQru+8+gd4A8Vu9yQehV+rlZe4hwiXb+iZ2CymmIjlJpAIOQjVTVe4WyUrwrX8NqCSHlltuDrO/ysXz0/s600xxGoLKAr5Y6p0erdjMRzLhgCPKRQ8uJA4g/huqnDuiJ9racsyggzYZbg9J4ThFaGAzo4wc=<signatureInfo><simpleAuthenticationToken><simpleTokenAuthenticationGuid>SGAHA6QYwwnr0h8Gc7xpOQ==</simpleTokenAuthenticationGuid><simpleSamlSessionIndex>pQiMBsX4yJ/nzqnsyglHJ2LxSEOyGS3i1B4GV/07zS/ws32DyyMDS0S6Nf67X9RtDPfzL521C5sma2Cn0S+WdJ6eF72nIEv7MWxL+gS0dsoas/k00OEW+6bsbIZWzC7gotLkXvliBbr0bJT+DrYvwbmXmJ9NVM4HXW7D2SWFyH2eXSiEOcp8aK0DJRAJ7j5Zpip5SFXEY8bapOIoTg2ArprVL60TlW1RdOgrEteBxwfMVAYExi+K+A==</simpleSamlSessionIndex><simpleTokenRequestorID>ComedyCentral</simpleTokenRequestorID><simpleTokenDomainName>adobe.com</simpleTokenDomainName><simpleTokenExpires>2018/08/31 20:42:13 GMT -0700</simpleTokenExpires><simpleTokenMsoID>Verizon</simpleTokenMsoID><simpleTokenDeviceID><simpleTokenFingerprint>fae66fb0743b4acdb1b317a318dff7c7</simpleTokenFingerprint><simpleTokenDeviceIDFragments><simpleTokenBrowserInfo>f3c67ccc7a9b255837ebdbbec971be5d2a8067ca</simpleTokenBrowserInfo><simpleTokenPlatformInfo>7b653c1a1342f29b6e1ca16ef44b1d14c98a11e3</simpleTokenPlatformInfo><simpleTokenVendorInfo>0a92fab3230134cca6eadd9898325b9b2ae67998</simpleTokenVendorInfo><simpleTokenIpAddr>6e9f4386f03542df2c7cb07460c29eca4bba662e</simpleTokenIpAddr></simpleTokenDeviceIDFragments></simpleTokenDeviceID><simpleSamlNameID>HiLwsaepwpk=</simpleSamlNameID><ttl>2592000</ttl></simpleAuthenticationToken>'

#~ auth_t = '%3CsignatureInfo%3ENDOVXOHraEzX1qXRrQru%2B8%2Bgd4A8Vu9yQehV%2BrlZe4hwiXb%2BiZ2CymmIjlJpAIOQjVTVe4WyUrwrX8NqCSHlltuDrO%2FysXz0%2Fs600xxGoLKAr5Y6p0erdjMRzLhgCPKRQ8uJA4g%2FhuqnDuiJ9racsyggzYZbg9J4ThFaGAzo4wc%3D%3CsignatureInfo%3E%3CsimpleAuthenticationToken%3E%3CsimpleTokenAuthenticationGuid%3ESGAHA6QYwwnr0h8Gc7xpOQ%3D%3D%3C%2FsimpleTokenAuthenticationGuid%3E%3CsimpleSamlSessionIndex%3EpQiMBsX4yJ%2FnzqnsyglHJ2LxSEOyGS3i1B4GV%2F07zS%2Fws32DyyMDS0S6Nf67X9RtDPfzL521C5sma2Cn0S%2BWdJ6eF72nIEv7MWxL%2BgS0dsoas%2Fk00OEW%2B6bsbIZWzC7gotLkXvliBbr0bJT%2BDrYvwbmXmJ9NVM4HXW7D2SWFyH2eXSiEOcp8aK0DJRAJ7j5Zpip5SFXEY8bapOIoTg2ArprVL60TlW1RdOgrEteBxwfMVAYExi%2BK%2BA%3D%3D%3C%2FsimpleSamlSessionIndex%3E%3CsimpleTokenRequestorID%3EComedyCentral%3C%2FsimpleTokenRequestorID%3E%3CsimpleTokenDomainName%3Eadobe.com%3C%2FsimpleTokenDomainName%3E%3CsimpleTokenExpires%3E2018%2F08%2F31+20%3A42%3A13+GMT+-0700%3C%2FsimpleTokenExpires%3E%3CsimpleTokenMsoID%3EVerizon%3C%2FsimpleTokenMsoID%3E%3CsimpleTokenDeviceID%3E%3CsimpleTokenFingerprint%3Efae66fb0743b4acdb1b317a318dff7c7%3C%2FsimpleTokenFingerprint%3E%3CsimpleTokenDeviceIDFragments%3E%3CsimpleTokenBrowserInfo%3Ef3c67ccc7a9b255837ebdbbec971be5d2a8067ca%3C%2FsimpleTokenBrowserInfo%3E%3CsimpleTokenPlatformInfo%3E7b653c1a1342f29b6e1ca16ef44b1d14c98a11e3%3C%2FsimpleTokenPlatformInfo%3E%3CsimpleTokenVendorInfo%3E0a92fab3230134cca6eadd9898325b9b2ae67998%3C%2FsimpleTokenVendorInfo%3E%3CsimpleTokenIpAddr%3E6e9f4386f03542df2c7cb07460c29eca4bba662e%3C%2FsimpleTokenIpAddr%3E%3C%2FsimpleTokenDeviceIDFragments%3E%3C%2FsimpleTokenDeviceID%3E%3CsimpleSamlNameID%3EHiLwsaepwpk%3D%3C%2FsimpleSamlNameID%3E%3Cttl%3E2592000%3C%2Fttl%3E%3C%2FsimpleAuthenticationToken%3E'

#~ TODO: How long does a authz token last?
dataforadobe = {'resource_id':'ComedyCentral',
	'requestor_id':'ComedyCentral',
	'authentication_token':authtoken_adobe,
	'mso_id':'Verizon',
	'userMeta':'1'}
print('Sending authorization to Adobe...')
auth = requests.post('https://sp.auth.adobe.com/adobe-services/authorize', data = dataforadobe, headers = headersforadobe)
#~ print(auth.text)
#~ input()

authzToken = auth.text[58:-22]
authzTokenRP1 = authzToken.replace('&lt;', '<') 
authzTokenRP2 = authzTokenRP1.replace('&gt;', '>') 

#~ print(authzTokenRP2)

ADOBE_PASS_DATA_2 = {'session_guid':'SGAHA6QYwwnr0h8Gc7xpOQ==',
		'hashed_guid':'false',
		'requestor_id':'ComedyCentral',
		'authz_token': authzTokenRP2,
		'generic_data':'{}'
		}
print('Sending second authorization to Adobe...')		
getShortAuthorize = requests.post('https://sp.auth.adobe.com/adobe-services/shortAuthorize', data = ADOBE_PASS_DATA_2, headers = headersforadobe)
SAD =  getShortAuthorize.text

#~ print(SAD)
#~ SAD = 'XD'
#~ print(SAD)
def getCCM3U8():
	headers = {'X-VIA-TVE-MEDIATOKEN':SAD,
		'Origin':'http://www.cc.com','Referer':'http://www.cc.com/','User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0','Content-Type':'application/json'}
	jsres = requests.get('https://media-utils-live.mtvnservices.com/services/MediaGenerator/mgid:arc:live:comedycentral.com:e3e2f5a5-8680-4d6f-85c7-a7136f128b2a?arcPlatforms=7ac7942e-6481-457f-b39a-2b1aedb29f29,b995f21c-e76f-4e58-8d0f-0964dc76efd3,6caa8f01-72e5-4707-abd6-608a0146e2ee,39dfe10c-cc2a-40f9-a20d-962d2604d543,0a16f611-d105-436a-8188-33ea8871171e,f17d0e9b-657a-4785-b3ca-dae9e78563a1&ssid=comedy_central_channel&euid.ssus=true&euid=0adb954c-3638-4d6c-b202-55fbbfa34098&format=json&acceptMethods=hls&tveprovider=Verizon', headers = headers)
	
	
	def swc(tts):
		for i in range(0,tts):
			if i == tts-1:
				end = '\n'
			else:
				end = ', '
			print(f'{i+1}', end = end, flush=True)
			sleep(1)
		
	if  'content.incapsula.com' in jsres.text:
		print('Seems like you might be using SmartDNS proxy or a similar service and your IP isn\'t up to date...')
		if path.isfile('SDPupdatelink.txt'):
			print('Oh, good, you have the file already in place...')
			file = open('SDPupdatelink.txt','r')
			line = file.readline()
			r = requests.get(line.strip())
			jr = r.json()
			status = jr['Status']
			message = jr['Message']
			if status == 1:
				print(f'Something went wrong, SmartDNS proxy says {message!r}')
				sys.exit(1)
			else:
				#TODO: Check if the given sleep time is always enough!  (Better a bit more than to little -- but not too much either.)
				st = 60
				print('Good, API call seems to have been successfull.')
				print(f'Exact response was {message!r}')
				print(f'Sleeping {st} seconds to give SmartDNS some time to actually update the IP...')
				swc(st)
				getCCM3U8()
				exit()
				#~ print(line)
		else:
			print('If you put the link for the API call as the only line in a file called \'SDPupdatelink.txt\' it can be done automatically in this script...')
	else:

		jsres = jsres.json()
		#~ print(jsres.text)
		video_item = jsres['package']['video']['item'][0]
		
		print()

		if 'rendition' in video_item:
			m3u8_master = video_item['rendition'][0]['src']
			print(m3u8_master)
			print('streamlink will be called...')
			call(['streamlink', f'hlsvariant://{m3u8_master}', 'best','-o',f'CClive_{sys.argv[1]}.ts'])
		elif 'type' in video_item:
			if video_item['type'] == 'text':
				error_text = video_item['text']
				print(f'Oops: {error_text}')

		#~ print(jsres)

		#~ print(m3u8_master)
getCCM3U8()