#!/usr/bin/env python

import cgi
import sys
import urllib2
# from pprint import pprint
import cgitb; cgitb.enable()

def resolve_redirects(link):
    try:
        f = urllib2.urlopen(link)
        return f.url
    except urllib2.URLError, e:
        # print e.code
        pass

    return None

def get_stream(link):
    try:
        from subprocess import Popen, PIPE
        ret = Popen(["/home/vnaum/bin/youtube-dl", "-g", link], stdout=PIPE).communicate()[0]
        ret = ret.rstrip('\n')
        ret = resolve_redirects(ret)
        return ret
    except:
        return None

def print_movie(form, stream):
    link = form.getvalue("link")
    # msg = "Hi there!<br>link = " + `link` + "<br>stream = " + `stream`
    msg = ""
    if stream:
        msg = '<a href="%s">Download flv</a>' % stream

    swf = "/stuff/ustube/player/flowplayer-3.1.0.swf"
    js = "/stuff/ustube/player/flowplayer-3.1.0.min.js"
    
    page = """
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
	<script type="text/javascript" src="%s"></script>
	<title>USTube</title>
</head><body>
		<h1>USTube</h1>
	
		<!-- this A tag is where your Flowplayer will be placed. it can be anywhere -->
		<a  
             style="display:block;width:480px;height:360px;background:black"
			 id="player"> 
		</a> 
	
		<!-- this will install flowplayer inside previous A- tag. -->
        %s
        <p> %s
        <p>
        <form method="get">
        Enter youtube url here:
        <input type="text" name="link" />
        <br>
        <input type="checkbox" name="wide"/> widescreen player
        <br>
        <input type="submit" />
        </form>
</body></html>
"""

    script = ""

    if form.getvalue("wide"):
        page = page.replace("width:480px;height:360px","width:640px;height:360px")

    if stream:
        script = """
            <script>
                      flowplayer("player", "%s", {
                        clip: {
                          url: "%s"
                      }});
            </script>
         """ % (swf, stream.replace('&', '%26'))

    print "Content-Type: text/html\n"     # HTML is following
    print page % (js, script, msg)

# get params
form = cgi.FieldStorage()
link = form.getvalue("link")
if link:
    # fetch url
    stream = get_stream(link)
    # print out movie + form
    print_movie(form, stream)
else:
    print_movie(form, None)
