import sys, urllib

# YouTube video grabber. Currently supports mp4 and flv download types.

if __name__ == '__main__':

  print ""

  # YouTube movie URLs look like this: http://youtube.com/watch?v=uPROl1R_FAU
  if len(sys.argv) != 3:
    print "Usage: python ytgrabber.py <youtube video url> <output file name>"
    exit(0)
    
  yturl = sys.argv[1]
  
  # Grab the html sitting at the specified url
  yturldata = urllib.urlopen(yturl)
  yturltxt = yturldata.read()
  
  # Find the indices that reveal the location of the url we want.
  #   In the above example, the url is the following:
  #   http://www.youtube.com/get_video.php?&video_id=ZlWaTAZUxUQ&l=61&sk=b6kcclU691Wf895SDVWU2wwvwFYS1LHAC&fmt_map=&t=OEgsToPDskIGrKHugwx8uMJR4EuKYNrd&hl=en&plid=AARP8p0Q-uInLkjcAAAAoABAAAA&tk=-M272mgIDsi4d_ERZ-NdKkFKXWWnfhRQNdSTafilyA2W0skDDcWYRg%3D%3D

  lidx = yturltxt.find("&video_id=")
  ridx = yturltxt.find("&title=", lidx)
 
  # The output file name.
  videoname = sys.argv[2]

  # The video data sits at this url.
  resulturl = "http://www.youtube.com/get_video.php?" + yturltxt[lidx:ridx]

  if videoname.endswith(".mp4"):
    resulturl = resulturl + "&fmt=18"
  elif videoname.endswith(".flv"):
    pass
  else:
    print "Unsupported file extension. .flv and .mp4 only!"
    exit(0)
  
  print "The video url is : "
  print "    ", resulturl

  print ""
  print "Downloading file. (Depending on the size, this could take a few minutes)"
  print ""

  ytfile = open(videoname, "w")

  ytfileref = urllib.urlopen(resulturl)
  filedata = ytfileref.read()

  print "Done reading video file. Writing contents to", videoname
  print ""

  ytfile.write(filedata)
  ytfile.close()

  print "Done!"
  print ""

