#!/usr/bin/python

# To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.

__author__="suxoza"
__date__ ="$Mar 3, 2014 9:23:15 AM$"

from urlparse import parse_qs
from urllib2 import urlopen
import re,sys,json,pprint,sys
from urllib2 import build_opener, HTTPError, URLError

def get_js(videoid):
        opener = build_opener()
        watchurl = "https://www.youtube.com/watch?v=" + videoid
        #watchinfo = opener.open(watchurl).read().decode("UTF-8")
        watchinfo = urlopen(watchurl).read().decode("UTF-8")
        #print(watchinfo)
        m = re.search(r';ytplayer.config = ({.*?});', watchinfo)
        print(m.group(1))
        try:
            myjson = json.loads(m.group(1))

        except:
            raise RuntimeError('Problem handling this video')

        args = myjson['args']
        
        html5player = myjson['assets']['js']

        if html5player.startswith("//"):
            html5player = "https:" + html5player
        #js = opener.open(html5player).read().decode("UTF-8")
        js = urlopen(html5player).read().decode("UTF-8")
        return(js,args)


if __name__ == "__main__":
    aa = get_js(sys.argv[1])
    #print(aa)
