#!/usr/bin/env python3
#~ This python script was originally the work of @nyuszika7h and then got extensivly enhanced by @kingofusers. 
#~ Unlawful distribution or even usage (yeah you heard me) is strictly prohibited. Premission is required.
#~ DISCLAIMER: We are not responsible for any damage caused by this script.
#~ Keep dogs, cats and other pets away and don't let them near you while you're working with this script.
#~ You have been warned! Nothing is impossible when Donald Trump is president. (Well besides a reasonable president of course and a reasonable government and etc. etc.)

import re
import sys
import urllib.parse
import time
from pprint import pprint
from subprocess import call
from subprocess import check_output
import bs4
import os
import requests
import platform
from send2trash import send2trash
from shutil import which

from colorama import init
init()
from colorama import Fore, Back, Style

import argparse
parser = argparse.ArgumentParser(prog='getwatchABC',formatter_class=argparse.RawTextHelpFormatter, description='This python script was originally the work of @nyuszika7h and then got extensivly enhanced by @kingofusers.\n'+
Fore.RED+Style.BRIGHT+'Unlawful distribution or even usage is strictly prohibited.\nPremission is required.\n'+Style.RESET_ALL+
'DISCLAIMER: We are not responsible for any damage caused by this script.\n'+
'Keep all pets away and don\'t let them near you while you\'re working with this script.\n'+
'You have been warned! Nothing is impossible when '+Fore.YELLOW+Style.DIM+'Donald Trump'+Style.RESET_ALL+' is president.\n(Well besides a reasonable president of course and a reasonable government and etc. etc.))')
parser.add_argument('urls',
                    help='URL from a ABC or Disney GO site', metavar='URL', nargs='*')
parser.add_argument('--keepts',
                    help='don\'t delete the ts file after merging it to mkv', action='store_true')
parser.add_argument('--live',
                    help='Don\'t download a on demand video, get the Livestream', metavar='CHANNEL')
parser.add_argument('--ShowAbbr', '-SA',
                    help='Use this to get info or download a show without knowing exactly what it is you want', metavar='SHOW ABBREVIATION')
parser.add_argument('--GetAllShows', '-gas',
                    help='Use this to get info about all shows currently present on the watchdisney site', action='store_true')
parser.add_argument('--quiet', '-q',
                    help='For extras only: Don\'t print in-between message (as to not disturb direct link output)', action='store_true')
parser.add_argument('--ZtoA',
                    help='Use this to sort the list of shows upside down', action='store_true')
parser.add_argument('--deletets', '-dts',
                    help='Removes the file instead of moving it to the trash', action='store_true')
parser.add_argument('--rgn', 
                    help='Defines the release group name (for output filename(s))')
parser.add_argument('--txtlinks', '-txt',
                    help='enables to write all links (to shorts to a txt file)', action='store_true')
#~ parser.add_argument('--GetShowInfo',
                    #~ help='Use this to get info on a show without knowing exactly what it is you want.\n Use in combination with --GetShowInfo or --GetVidEntry', action='store_true')
#~ parser.add_argument('--GetVidEntry',
                    #~ help='Use this to get info or download a show without knowing exactly what it is you want\n Use in combination with --ShowAbbr', metavar='CHANNEL')
args = parser.parse_args()

scriptversion = 3
subversion = 1
revision = 0
try:
	print('Checking if newer version is available...')
	update = requests.get('https://themanha.uber.space/getwatchabc.version')
	#~ print(update.text)
	if str(scriptversion)+'.'+str(subversion)+'.'+str(revision) == update.text:
		
		print('Oh good, you already have the newest available version.')
		#~ CELEBRATE, GOOD TIMES! COME ON! ;-D
	else:
		print('Wait -- you might want to update the script. New version is: '+update.text+'\nYou have Version '+str(scriptversion)+'.'+str(subversion)+'.'+str(revision))
		ans = input('Care to update now? (Y for yes): ')
		if ans == 'Y' or ans == 'y':
			r = requests.get('https://themanha.uber.space/getwatchabc2-new.py')
			with open('getwatchabc3.py', 'wb') as fd:
				fd.write(r.content)
			print('New script written to getwatchabc3.py')
			print('Relaunching from new script...')
			arglist = ['python','getwatchabc3.py']
			for idx, arg in enumerate(sys.argv):
				if idx > 0:
					arglist.append(arg)
			call(arglist)
			exit()

except KeyboardInterrupt:
	print('\nOkay, okay already, I won\'t update or check for it.')

print()
streamlinkexists = which('streamlink')
if streamlinkexists == None:
	print('streamlink not in the PATH - using the path from the script')
	globals()['streamlink'] = r'C:\Program Files (x86)\Streamlink\bin\streamlink.exe'
else:
	globals()['streamlink']=streamlinkexists
	#~ out = check_output(['streamlink'])
	
	#~ if 'usage: streamlink' in str(out):
		#~ print ('streamlink found in PATH, will use from there')
		#~ globals()['streamlink'] = 'streamlink'
#~ except FileNotFoundError:
	
	

mkvmergeexists = which('mkvmerge')
if mkvmergeexists == None:
	if platform.system() == 'Windows':
		print('mkvmerge not in the PATH - using the path from the script')
		globals()['mkvmerge'] = r'C:\Program Files\MKVToolNix\mkvmerge.exe'
	else:
		print('mkvmerge not in the PATH / no fallback for Linux/Mac defined')
		print('It\'s possible that it\'s not supported by the operating system :(')
		globals()['mkvmerge'] = 'N/A'
else:
	globals()['mkvmerge'] = mkvmergeexists
	#~ out = check_output(['mkvmerge'])
	#~ print()
	#~ if 'mkvmerge' in str(out):
		#~ print ('mkvmerge found in PATH, will use from there')
		#~ globals()['mkvmerge'] = 'mkvmerge'
#~ except FileNotFoundError:
	#~ if platform.system() == 'Windows':
		#~ print('mkvmerge not in the PATH - using the path from the script')
		#~ globals()['mkvmerge'] = r'C:\Program Files\MKVToolNix\mkvmerge.exe'
	#~ else:
		#~ print('mkvmerge not in the PATH / no fallback for Linux/Mac defined')
		#~ print('It\'s possible that it\'s not supported by the operating system :(')
		#~ globals()['mkvmerge'] = 'N/A'
	
if platform.system() == 'Windows':
	ccextractorexists = which('ccextractorwin')
elif platform.system() == 'Linux':
	ccextractorexists = which('ccextractor')
else:
	print('Unsupported Platform!')
	print('Unexpected fails are more likely.')
	ccextractorexists = which('ccextractor')
	if ccextractorexists == None:
		globals()['ccextractor'] = 'N/A'
	else:
		print ('Wow! ccextractor found in PATH, will use from there.')
		print('Please let the developer know what system you are using (It\'s: '+platform.system()+')')
		globals()['ccextractor'] = ccextractorexists

if (platform.system() == 'Windows') or (platform.system() == 'Linux'):
	winstring = ''
	if platform.system() == 'Windows':
		winstring = 'win'
	if ccextractorexists == None:
		#~ Switch commenting and enter location of the following block if you don't want to add ccextractor to PATH yet still want to use this script with the functionality
		
		print(f'ccextractor{winstring} not in the PATH - automatic subtitle extraction will be disabled :(')
		globals()['ccextractor'] = 'N/A'
		#~ globals()['ccextractor'] = r'CCEXTRACTORPATH'
		#~ print(f'ccextractor{winstring} location has been set as fallback in script ')
	else:
		print (f'ccextractor{winstring} found in PATH, will use from there')
		globals()['ccextractor'] = ccextractorexists
	#~ try:
		#~ out = check_output(['ccextractorwin', '--help'])
		#~ print()
		#~ if 'CCExtractor' in str(out):
			#~ print ('ccextractorwin found in PATH, will use from there')
			#~ globals()['ccextractor'] = 'ccextractorwin'
	#~ except FileNotFoundError:
		#~ print('ccextractorwin not in the PATH - automatic subtitle extraction will be disabled :(')
		#~ globals()['ccextractor'] = r'manualPATH'
		#~ globals()['ccextractor'] = 'N/A'
		
#~ elif platform.system() == 'Linux':
	#~ try:
		#~ out = check_output(['ccextractor', '--help'])
		#~ print()
		#~ if 'CCExtractor' in str(out):
			#~ print ('ccextractor found in PATH, will use from there')
			#~ globals()['ccextractor'] = 'mkvmerge'
	#~ except FileNotFoundError:		
		#~ Switch commenting and enter location of the following block if you don't want to add ccextractor to PATH yet still want to use this script on a Linux system.
		
		#~ print('ccextractor needs to be in PATH on linux to be used in this script')
		#~ globals()['ccextractor'] = 'N/A'
		#~ globals()['ccextractor'] = r'CCEXTRACTORPATH'
#~else:
	#~ print('Unsupported Platform!')
	#~ print('Unexpected fails are more likely.')
print()
	

API_URL = 'http://api.contents.watchabc.go.com/vp2/ws/s/contents/3000/videos/{site_id}/001/-1/-1/-1/{video_id}/-1/-1.json'
SITE_IDS = {
    'abc.go.com': '001',
    'freeform.go.com': '002',
    'watchdisneychannel.go.com': '004',
    'watchdisneyxd.go.com': '009'
}


#PROXY = 'socks5://127.0.0.1:1425'
PROXY = None

XFF_FAKE_IP = '3.49.58.72'

txtfile='getwatchabc3-links.txt'

def getVideoById(video_id, site_id, stream_type, number=None):
	if stream_type=='live':
		print('Livestream request detected.')
	if (number == None):
		r = requests.get(API_URL.format(site_id = site_id, video_id=video_id),
				 headers={'x-forwarded-for': XFF_FAKE_IP})
		video_title = data['video'][0]['title']
		access_level = data['video'][0]['accesslevel']
	else:
		video_title = data['video'][number]['title']
		access_level = data['video'][number]['accesslevel']
	if args.quiet == False:	
		print('Now processing '+video_id+' with the title '+video_title)
	if (access_level == '1'):
		print('This is a provider locked video, authentication in progress...')
		ADOBE_PASS_DATA_1 = {
		'mso_id':'Verizon',
		'requestor_id': 'Disney',
		'userMeta': '1',
		'authentication_token': '<signatureInfo>YXw48tL6RgQ5OjWvEKo/6oLeYWLi6uU9Ii0kQz4t94V1OPrTUG8PlTH3lG5W9DL+hebOfbP6BiYUdbmb2WK55iajUY1qh9IBOZIzkjPmz/4OUFCmC9PGyyJyxtU+F5e8UvbnPqBZox+cdmMcwl9fE/5sx1d3zVJGR5xUcAa3zDc=<signatureInfo><simpleAuthenticationToken><simpleTokenAuthenticationGuid>SGAHA6QYwwnr0h8Gc7xpOQ==</simpleTokenAuthenticationGuid><simpleSamlSessionIndex>pQiMBsX4yJ/nzqnsyglHJ2LxSEOyGS3i1B4GV/07zS/iLmgW8kUxHINN4wewQSkW1F51C8H+RzcW9ZJQ07xb1n5byTeigpAVLs7OjXdbkRkLPyOyu/mk80GRjoY5JCnHZ1QdPfKrwtFgCkZcPju39n2aV+b7W5LVvAEMn+x4uaF6XCK8337/Rlwe3UdN0mu96xaruKODYXF5V3i3lPfDyOmO0Mdux7Gt6+fkQsv/7vZYkG97rLEs/Q==</simpleSamlSessionIndex><simpleTokenRequestorID>Disney</simpleTokenRequestorID><simpleTokenDomainName>adobe.com</simpleTokenDomainName><simpleTokenExpires>2018/10/06 07:26:09 GMT -0700</simpleTokenExpires><simpleTokenMsoID>Verizon</simpleTokenMsoID><simpleTokenDeviceID><simpleTokenFingerprint xsi:nil=\"true\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"/><simpleTokenDeviceIDFragments><simpleTokenBrowserInfo>9ece966ae925d73a6c2133900facfd8df41221d5</simpleTokenBrowserInfo><simpleTokenPlatformInfo>ad8006a09d99767669d5fd4e7f01accfc33fb994</simpleTokenPlatformInfo><simpleTokenVendorInfo>0a92fab3230134cca6eadd9898325b9b2ae67998</simpleTokenVendorInfo><simpleTokenIpAddr>73676dbc89762f6f1d4eb0374bc3a9b1546efcdc</simpleTokenIpAddr></simpleTokenDeviceIDFragments></simpleTokenDeviceID><simpleSamlNameID>HiLwsaepwpk=</simpleSamlNameID></simpleAuthenticationToken>',
		'resource_id': '<rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title>Disney</title><item><title>DATG</title><guid>'+video_id+'</guid><media:rating scheme="urn:v-chip" /></item></channel></rss>'
		}
		headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux i686; rv:47.0) Gecko/20100101 Firefox/47.0', 'Ap_Z': 'Mozilla/5.0 (X11; Linux i686; rv:47.0) Gecko/20100101 Firefox/47.0',
		'Ap_11': 'Linux i686','Ap_42': 'anonymous'}
		getAuthorize = requests.post('https://sp.auth.adobe.com/adobe-services/authorize', data = ADOBE_PASS_DATA_1, headers = headers)


		AuthorizeData =  getAuthorize.text
		#~ print(AuthorizeData)
		authzToken = AuthorizeData[58:-22]
		authzTokenRP1 = authzToken.replace('&lt;', '<') 
		authzTokenRP2 = authzTokenRP1.replace('&gt;', '>') 
		#~ print(authzTokenRP2)

		ADOBE_PASS_DATA_2 = {'session_guid':'SGAHA6QYwwnr0h8Gc7xpOQ==',
		'hashed_guid':'false',
		'requestor_id':'Disney',
		'authz_token': authzTokenRP2
		}

		getShortAuthorize = requests.post('https://sp.auth.adobe.com/adobe-services/shortAuthorize', data = ADOBE_PASS_DATA_2, headers = headers)
		ShortAuthorizeData =  getShortAuthorize.text
		#~ print(ShortAuthorizeData)

		PROVIDER_LOGIN_INFO = { 
		    'token': ShortAuthorizeData, 
		    'token_type': 'ap',
		    'adobe_requestor_id': 'Disney',
		    'user_id': '73F6E4D8-B15F-439F-AE65-03482FB22B75',
		    'mvpd': 'Verizon',
		    'auth_flag':'1'
		    # TODO at some later point: Implement other requester ids if needed
		}
	else:
		if args.quiet == False:
			print('This is a free video, no provider details will be used.')


	if (number == None):
		assets = data['video'][0]['assets']['asset']
	else:
		assets = data['video'][number]['assets']['asset']
	need_key = True
	video_url = None
	mp4s = []

	for asset in assets:
		if asset['format'] == 'MP4':
			need_key = False

		if '/source/' in asset['value']:
			video_url = asset['value']
			break

		mp4s.append(asset['value'])

	if not video_url:
		if mp4s:
			video_url = mp4s[-1]
		else:
			video_url = assets[-1]['value']
#~ 92637 +2
	if need_key:
		if (stream_type == 'live'):
			AUTH_URL = 'https://api.entitlement.watchabc.go.com/vp2/ws-secure/entitlement/2020/playmanifest_secure.json'
			postdata = {
			'video_type': 'live',
			'brand': site_id,
			'device': '022',
			'video_id': video_id,
			'zipcode':'07642',
			'uplynk_ct':'c'
			}
			postdata.update(PROVIDER_LOGIN_INFO)
			r = requests.post(AUTH_URL, postdata,
				headers={'x-Forwarded-for': XFF_FAKE_IP})
			INFOdata = r.json()
			endresultM3U8 = INFOdata['channels']['channel'][0]['assets']['asset'][0]['value']
		else:
			AUTH_URL = 'https://api.entitlement.watchabc.go.com/vp2/ws-secure/entitlement/2020/authorize.json'
			postdata = {
			'video_type': 'lf',
			'brand': site_id,
			'device': '022',
			'video_id': video_id
			}
			print('Getting playlist authorization data', end='...')
			#~ print(postdata)
			if (access_level == '1'):
				postdata.update(PROVIDER_LOGIN_INFO)
			r = requests.post(AUTH_URL, postdata,
			headers={'x-Forwarded-for': XFF_FAKE_IP})#proxies={'http': PROXY, 'https': PROXY}

			KEYdata = r.json()

			if 'errors' in KEYdata and KEYdata['errors']['count'] > 0:				
				print('\nError {0}'.format(KEYdata["errors"]["errors"][0]["message"]))
				sys.exit(1)

			session_key = KEYdata['uplynkData']['sessionKey']
			print(' Done.')
			

			endresultM3U8 = '{0}?{1}'.format(video_url, session_key)
		#~ print(endresultM3U8)
		print('Checking the quality of the video...')
		out = check_output([globals()['streamlink'],'hlsvariant://'+endresultM3U8])
		#~ print(out)
		global streamquality
		streamquality = 'best'
		if (str(out).find('1080p') != -1):
			streamquality = '1080p'
		elif (str(out).find('720p') != -1):
			streamquality = '720p'
		else:
			streamquality = '480p'
		print('This video has been detected as: '+streamquality)
		
		
		def sanitize_filename(name):
			return re.sub(r'[/*<>?:"]', '_', name)
			
			
		ccextractorpath = r'C:\Users\Lucas Halbig\Downloads\ccextractor.0.85b-windows.binaries'
		if args.rgn != None:
			rgn = args.rgn
		else:	
			rgn = 'kingofusers'
							
		def removeTsFile():
			if args.keepts==False:
				if args.deletets == True:
					print('Deleting .ts file', end='...')
					try:
						os.remove(filetitle+'.ts')
						print('Done.')
					except PermissionError:
						print('Whoa!')
						print('You are playing the .ts file already, am I right?')
						print('Well whatever it is... seems like your system doesn\'t want to give it up... you\'ll have to delete it manually.')
						print('Anywho... bye-bye.')
				else:
					print('Moving .ts file to trash', end='...')
					try:
						send2trash(filetitle+'.ts')
						print('Done.')
					except PermissionError:
						print('Whoa!')
						print('You are playing the .ts file already, am I right?')
						print('Well whatever it is... seems like your system doesn\'t want to give it up... you\'ll have to delete or move it to trash it manually.')
						print('Anywho... bye-bye.')
					
		
			
		if (stream_type == 'lf'):
			if (number == None):
				video_showname = sanitize_filename(data['video'][0]['show']['title'])
				video_title_sanitized = sanitize_filename(video_title)
				video_type = data['video'][0]['show']['type']
			else:
				video_showname = sanitize_filename(data['video'][number]['show']['title'])
				video_title_sanitized = sanitize_filename(video_title)
				video_type = data['video'][number]['show']['type']
			
			if (video_type=='Show'):
				print('This video is categorized: TV show, title: '+video_showname, end='')
				if (number == None):
					video_SeasonNumber = data['video'][0]['season']['numWithPadding']
					video_EpNum = int(data['video'][0]['episodenumber'])
				else:
					video_SeasonNumber = data['video'][number]['season']['numWithPadding']
					video_EpNum = int(data['video'][number]['episodenumber'])
				video_EpNumber = f'{video_EpNum:02}'
				
				if video_title_sanitized.startswith(video_showname):
					print('/Special Show')
					videotitle2 = ')'+video_title_sanitized[len(video_showname):]
					filetitle = video_showname+' (E'+video_EpNumber+videotitle2.replace('_','')+' '+streamquality+' DSNY WEB-DL AAC2.0 x264-'+rgn
					print(r'Download//conversion//mergeing of files has launched.')
					call([globals()['streamlink'],'hlsvariant://'+endresultM3U8+' name_key=bitrate', 'best', '--hls-timeout','120', '--stream-segment-timeout', '2','-o', filetitle+'.ts'])
					if globals()['ccextractor'] != 'N/A':
						call([ccextractorpath+r'\ccextractorwin.exe',  '-autoprogram', '-out=srt', '-bom', '-utf8', '--norollup', filetitle+'.ts'])
					if globals()['mkvmerge'] != 'N/A':
						call([globals()['mkvmerge'],'--ui-language', 'de', '--output', filetitle+'.mkv', filetitle+'.ts', '--default-track', '0:no', filetitle+'.srt','--track-order', '0:1,0:0,1:0'])
						removeTsFile()
				else:		
					print('/regular TV Episode')
					filetitle = video_showname+' S'+video_SeasonNumber+'E'+video_EpNumber+' '+video_title_sanitized+' '+streamquality+' DSNY WEB-DL AAC2.0 x264-'+rgn
					print(r'Download/conversion/mergeing of files has launched.')
					call([globals()['streamlink'],'hlsvariant://'+endresultM3U8+' name_key=bitrate' , 'best',  '--hls-timeout','120', '--stream-segment-timeout', '2', '-o', filetitle+'.ts'])
					if globals()['ccextractor'] != 'N/A':
						call([ccextractorpath+r'\ccextractorwin.exe',  '-autoprogram', '-out=srt', '-bom', '-utf8', '--norollup', filetitle+'.ts'])
					if globals()['mkvmerge'] != 'N/A':
						call([globals()['mkvmerge'],'--ui-language', 'de', '--output', filetitle+'.mkv', filetitle+'.ts', '--default-track', '0:no', filetitle+'.srt','--track-order', '0:1,0:0,1:0'])
						removeTsFile()
								
			elif (video_type=='Movie'):
				filetitle =  video_title_sanitized+' '+streamquality+' DSNY WEB-DL AAC2.0 x264-'+rgn
				print(r'Download/conversion/mergeing of files has launched.')
				call([globals()['streamlink'],'hlsvariant://'+endresultM3U8+' name_key=bitrate', 'best', '--hls-timeout','120', '--stream-segment-timeout', '2','-o', filetitle+'.ts'])
				
				if globals()['ccextractor'] != 'N/A':
					call([ccextractorpath+r'\ccextractorwin.exe',  '-autoprogram', '-out=srt', '-bom', '-utf8', '--norollup', filetitle+'.ts'])
				if globals()['mkvmerge'] != 'N/A':
					call([globals()['mkvmerge'],'--ui-language', 'de', '--output', filetitle+'.mkv', filetitle+'.ts', '--default-track', '0:no', filetitle+'.srt','--track-order', '0:1,0:0,1:0'])
					removeTsFile()
		elif (stream_type == 'live'):		
			filetitle = args.live+time.strftime(' - %y-%m-%d %H-%M-%S')
			print('You have selected the '+args.live+'livestream.')
			call([globals()['streamlink'],'hlsvariant://'+endresultM3U8+' name_key=bitrate', 'best', '--hls-timeout','120', '--stream-segment-timeout', '2', '-o', filetitle+'.ts'])
			if globals()['ccextractor'] != 'N/A':
				call([ccextractorpath+r'\ccextractorwin.exe',  '-autoprogram', '-out=srt', '-bom', '-utf8', '--norollup', filetitle+'.ts'])
			if globals()['mkvmerge'] != 'N/A':
				call([globals()['mkvmerge'],'--ui-language', 'de', '--output', filetitle+'.mkv', filetitle+'.ts', '--default-track', '0:no', filetitle+'.srt','--track-order', '0:1,0:0,1:0'])
				if (args.keepts==False):
					print('.ts will not be deleted for a live feed since it\'s usually needed to edit stuff.')
					#~ removeTsFile()
	else:
		print(video_url)
		return video_url

if (len(args.urls)>0):
	#~ print(Fore.RED + 'some red text')
	#~ print(Style.RESET_ALL)
	video_ids = list()
	site_ids = list()
	print('Found a total of '+str(len(args.urls))+' URLs to process.')
	for aURL in args.urls:
		#~ if (len(sys.argv)>=2):
		URL = aURL
		#~ else:
			#~ print('A parameter is required.')
			#~ sys.exit(1)
		

		#~ video_id = sys.argv[1]

		print('Attempting to find vdka ID in URL',end='...')
		if ('vdka' in URL) or ('VDKA' in URL):
		    video_id = re.search(r'/(vdka[a-z0-9_]+)/', URL, flags=re.IGNORECASE).groups()[0]
		    print(' sucess: '+video_id+' !')
		    video_ids.append(video_id)
		else:
			print(Fore.RED+' failed.'+Style.RESET_ALL)
			print('Now trying to find vdka ID in HTML of the given URL',end='...')
			r = requests.get(URL, headers={'x-forwarded-for': XFF_FAKE_IP})
			soup = bs4.BeautifulSoup(r.text, 'html.parser')

			try:
				video_id = soup.find('div', {'class': 'videoContainer m-videoplayer-embed m-videoplayer-embed-lf'}).get('data-video-id')
				if video_id == None:
					print(' sorry, no ID was found.')
					sys.exit(1)
				else:
					print('\nThis is the vidoe ID I found: '+video_id)
					video_ids.append(video_id)
			except AttributeError:
				try:
					video_id = soup.find('freeform-player').get('data-video-id')
					if video_id == None:
						print(Fore.RED+' sorry, no ID was found.'+Style.RESET_ALL)
						sys.exit(1)
					else:
						print('\nThis is the vidoe ID I found: '+video_id[1:-1])
						video_ids.append(video_id[1:-1])
				except AttributeError:
					print(Fore.RED+' sorry, no ID was found.'+Style.RESET_ALL)
					sys.exit(1)

		try:
		    site_id = SITE_IDS[urllib.parse.urlparse(URL).netloc]
		    
		    print('Using the site_id '+Fore.GREEN+Style.DIM+site_id+Style.RESET_ALL+' for '+Fore.YELLOW+Style.BRIGHT+urllib.parse.urlparse(URL).netloc+Style.RESET_ALL)
		    site_ids.append(site_id)
		except KeyError:
		    print('Error: Unsupported site')
		    sys.exit(1)
	#~ print(API_URL.format(site_id = site_id, video_id=','.join(video_ids)))
	r = requests.get(API_URL.format(site_id = site_id, video_id=','.join(video_ids)),
		 headers={'x-forwarded-for': XFF_FAKE_IP})
	data = r.json()
	for idx, id in enumerate(video_ids):
		getVideoById(video_ids[idx], site_ids[idx], data['video'][idx]['type'], number=(len(video_ids)-1)-idx)
		
		#~ getVideoById(video_id=video_id, site_id=site_id, stream_type='lf')
else:
	if (args.live==None):
		if (args.ShowAbbr == None):
			if (args.GetAllShows == False):
				print('You must specify at least\nA) one URL\nB) nor a live channel\nC) or use the GetAllShows (currently only works with watchdisneychannel) flag.\nI think that should be enough options. :P')
			else:
				r = requests.get('http://watchdisneychannel.go.com/')
				soup = bs4.BeautifulSoup(r.text, 'html.parser')
				findallshowlinksreverse = []
				findallshownamesreverse = []
				shownameslist = []
				findallshowlinks = soup.find_all('a',{'class':'background-link aspect-ratio-buffer aspect-1x1'})
				findallshownames = soup.find_all('div',{'class':'tile-show-name truncate-text'})
				if (args.ZtoA == True):
					findallshowlinks.reverse()
					findallshownames.reverse()
				for item in findallshownames:
					shownameslist.append(item.text)
				showIDs = list()
				showAbbrs = list()
				global selectedShow
				selectedShow = None
				DCOM = 1
				print('Now getting and processing links... this may take a while...')
				def selectShow():
						print()
						try:
							try:
								globals()['selectedShow'] = input('Abbreviation of the show you want to have: ')
							except EOFError:
								print('You managed to produce an EOFError - sadly even the developer does not know why :P')
							if (globals()['selectedShow'] not in showAbbrs):
								print('Nope, try again.')
								selectShow()
							else:
								print('Show selected sucessfully')
						except KeyboardInterrupt:
							print('\nKeyboard Cancel')
							sys.exit(1)
				print()
				try:
					for idx, a in enumerate(findallshowlinks):
						#~ print (f'Processing... {idx+1:02}: '+a.get('href'))
						getShowID = requests.get('http://watchdisneychannel.go.com/'+a.get('href'))
						soup = bs4.BeautifulSoup(getShowID.text, 'html.parser')
						findsection = soup.find('section', {'data-m-type':'tilegroup'})
						showID = str(findsection.get('data-show-id'))
						if (showID != 'None'):
							showIDs.append(showID)
							getShowAbbr = requests.get('http://api.contents.watchabc.go.com/vp2/ws/contents/3000/videos/004/001/-1/'+showID+'/-1/-1/-1/-1.json')
							getShowAbbrJson = getShowAbbr.json()
							ShowAbbr = getShowAbbrJson['video'][0]['show']['showPrefix']
							if ShowAbbr == 'DCOM':
								ShowAbbr += str(DCOM)
								DCOM += 1
							showAbbrs.append(ShowAbbr)
							#~ print('ShowAbbr :'+ShowAbbr)
						elif (a.get('href')=='/disney-channel-originals-collection'):
							showIDs.append('[Unsupported]')
							showAbbrs.append('DCColl')
						else:
							print('Something unexpected happened. Please let the developer know (detailed reproducing steps please).\nPossible error: new and unhandled collection available')
							sys.exit(1)
						if (args.ZtoA == True):
							print(f'Done processing {len(findallshownames)-(idx):02}: '+findallshownames[idx].text)
						else:
							print(f'Done processing {idx+1:02}: '+findallshownames[idx].text)
				except KeyboardInterrupt:
						#~ print('Length of ShowNames: '+str(len(findallshownames)))
						#~ print('Length of ShowIDs: '+str(len(showIDs)))
						print()
						#~ if (args.ZtoA == True):
							#~ showAbbrs.reverse()
							#~ shownameslist.reverse()
							
						for idx, item in enumerate(showAbbrs):
							if (showIDs[idx] != '[Unsupported]'):
								print (item+': '+shownameslist[idx])
							else:  
								print ('Unsupported show not shown to avoid confusion')
						if len(showAbbrs)==1:
							globals()['selectedShow']=showAbbrs[0]
						else:
							selectShow()
					
				def GetShowByShowID(ID):
					API_URL = 'http://api.contents.watchabc.go.com/vp2/ws/contents/3000/videos/{site_id}/001/-1/{show_id}/-1/-1/-1/-1.json'
					#~ print(API_URL.format(site_id = site_id, show_id=show_id))
					rShow = requests.get(API_URL.format(site_id = '004', show_id=ID))				
					dataShow = rShow.json()
					dataShowVideo = dataShow['video']
					print('Here\'s the list of available videos for '+dataShow['video'][0]['show']['title']+':')
					for idx, item in enumerate(dataShowVideo):
						video_EpNum = int(item['episodenumber'])
						video_EpNumber = f'{video_EpNum:02}'
						if item['type']=='lf':
							print(f'{idx+1:02}: '+dataShow['video'][0]['show']['title']+' S'+item['season']['numWithPadding']+'E'+video_EpNumber+' '+item['title'])
						elif item['type']=='sf':
							print(f'{idx+1:02}: '+dataShow['video'][0]['show']['title']+' S'+item['season']['numWithPadding']+' '+item['title']+' (Clip)')
					def enterNumber():
						enteredNumber = input('Select a video number (or type "ALL"): ')
						if (enteredNumber != 'ALL'):
							try:
								global enteredInt
								enteredInt = int(enteredNumber)
							except:
								print('Invalid number!')
								enterNumber()
							global data
							data = dataShow
							getVideoById(video_id=dataShowVideo[enteredInt-1]['id'],site_id='004', stream_type='lf', number=enteredInt-1)
						else:
							globals()['data'] = dataShow
							directlinks = []
							for idx, item in enumerate(dataShowVideo):
								directlink = getVideoById(video_id=item['id'],site_id='004', stream_type='lf', number=idx)
								if directlink == None:
									print('Printing for M3U8-Sources not implemented.')
								else:									
									directlinks.append(directlink)
							if args.txtlinks == True:
								if len(directlinks)>0:
									f = open('getwatchabc3-links.txt','w') 
									f.write('\n'.join(directlinks)) 
									print('Textfile written')
								else:
									print('Nothing to write, so nothing was written')
							else:
								if len(directlinks)>0:
									print()
									print('FYI you can now use the CLI option "-txt" to create a txt-file with the direct links.')
					enterNumber()
					
				
				
				if (selectedShow == None):	
					for idx, item in enumerate(showAbbrs):
						if (showIDs[idx] != '[Unsupported]'):
							print (item+': '+findallshownames[idx].text)
						else: 
							print ('Unsupported show not shown to avoid confusion')
					#~ try:
					selectShow()
					#~ except KeyboardInterrupt:
						#~ print('\n\nCancelled by user!')
				
				GetShowByShowID(showIDs[showAbbrs.index(selectedShow)])
				
										
				
		else:
			def GetShowAbbr(ShowAbbr):
				print('This function is obsolete, it\'s at the moment at least not in further development')
				print()
				SHOW_IDS = {'AM':'SH553715218','STM':'SH552722455'}
				SHOW_NAMES = {'AM':'Andi Mack','STM':'Stuck in the Middle'}
				SITE_IDS = {'AM':'004','STM':'004'}
				try:
					show_id = SHOW_IDS[ShowAbbr]
					show_name = SHOW_NAMES[ShowAbbr]
					site_id = SITE_IDS[ShowAbbr]
					print('Using the show_id '+Fore.GREEN+Style.DIM+show_id+Style.RESET_ALL+' for '+Fore.YELLOW+Style.BRIGHT+show_name+Style.RESET_ALL)
				except KeyError:
					print('Error: Unsupported site')
					sys.exit(1)
				API_URL = 'http://api.contents.watchabc.go.com/vp2/ws/contents/3000/videos/{site_id}/001/-1/{show_id}/-1/-1/-1/-1.json'
				#~ print(API_URL.format(site_id = site_id, show_id=show_id))
				rShow = requests.get(API_URL.format(site_id = site_id, show_id=show_id))				
				dataShow = rShow.json()
				dataShowVideo = dataShow['video']
				print('Here\'s the list of available videos for'+show_name+':')
				for idx, item in enumerate(dataShowVideo):
					video_EpNum = int(item['episodenumber'])
					video_EpNumber = f'{video_EpNum:02}'
					if item['type']=='lf':
						print(f'{idx+1:02}: '+show_name+' S'+item['season']['numWithPadding']+'E'+video_EpNumber+' '+item['title'])
					elif item['type']=='sf':
						print(f'{idx+1:02}: '+show_name+' S'+item['season']['numWithPadding']+' '+item['title']+' (Clip)')
				def enterNumber():
					enteredNumber = input('Select a video number: ')
					try:
						global enteredInt
						enteredInt = int(enteredNumber)
					except:
						print('Invalid number!')
						enterNumber()
				enterNumber()
				global data
				data = dataShow
				getVideoById(video_id=dataShowVideo[enteredInt-1]['id'],site_id=site_id, stream_type='lf', number=enteredInt-1)
			GetShowAbbr(args.ShowAbbr)
			
		
	elif (args.live=='DisneyChannel'):
		r = requests.get(API_URL.format(site_id = '004', video_id='VDKA0_239n6lc2'))
		data = r.json()
		getVideoById(video_id='VDKA0_239n6lc2',site_id='004', stream_type='live')
	else:
		print('Channel not available')
	