# download video from its id
# first visit http://www.youtube.com/watch?v={0}
# get video_id and t in "var swfArgs = { }"
# download file via this url
# http://www.youtube.com/get_video?fmt='+(isHDAvailable?'22':'18')+ \
# '&video_id='+swfArgs['video_id']+'&t='+swfArgs['t']}
# 
# by dong (http://guod.cn)
#
import sys
MSG='>>>>>>>>>>>>%(msg)s<<<<<<<<<<<<<'
URL_youtube_video_watch_page='http://www.youtube.com/watch?v=%(video_id)s'
URL_youtube_video_download ='http://www.youtube.com/get_video?fmt=%(fmt)s&video_id=%(video_id)s&t=%(t)s'
def msg(m):
	print MSG%{'msg':m}
def get_watch_url(video_id):
	return URL_youtube_video_watch_page%{'video_id':video_id}
def fetch_one_page(url):
    import urllib
    return urllib.urlopen(url).read()
def get_video_id_t(html):
	import re
	rrr=re.findall('"video_id": "([^"]+)"',html)
	video_id=rrr[0] if len(rrr)>0 else ''
	rrr=re.findall('"t": "([^"]+)"',html)
	t=rrr[0]  if len(rrr)>0 else ''
	rrr=re.findall('<title>([^<]*)</title>',html)
	title=rrr[0] if len(rrr)>0 else ''
	return (video_id,t,title)
def get_download_url(video_id,t,fmt):
	return URL_youtube_video_download%{'fmt':fmt,'video_id':video_id,'t':t}
def download(url,localfile):
	import urllib
	msg(url);
	try:
		webFile = urllib.urlopen(url)
		localFile = open(localfile, 'w')
		localFile.write(webFile.read())
		webFile.close()
		localFile.close()
		return 0
	except:
		return 1
	
#def download1(url,localfile):
#	import urlgrabber, urlgrabber.progress
#	prog = urlgrabber.progress.text_progress_meter()
#	urlgrabber.urlgrab(url,localfile,progress_obj=prog)
def download2(url,localfile):
	import os
	cmd_str='wget -O %(localfile)s "%(url)s"'
	cmd=cmd_str%{'localfile':localfile,'url':url}
	print cmd
	return os.system(cmd)
def get_video_by_id(id,localfile,fmt):	
	msg('Analyzing the page')
	html=fetch_one_page(get_watch_url(id))
	video_id,t,title=get_video_id_t(html)
	if download2(get_download_url(video_id,t,fmt),localfile): 
		print 'download failed as fmt', fmt, 'please try other fmt'
	return title

def main(argv=sys.argv):	
	import sys,re
	if len(argv)<4:
		print "getVideoByID [localfile] [video_id|URL] [fmt]" 
		return
	fmt=argv[3];
	url=argv[2];
	localfile=argv[1];
	rrr = re.compile("\?v=(.*)").findall(url)
	video_id = rrr[0] if len(rrr)>0 else url
	msg('video_id='+video_id)
	get_video_by_id(video_id,localfile,fmt)
	msg("done")

if __name__=='__main__':
	sys.exit(main())
