#!/bin/bash
#
# FLVGET Plugin for "YouTube" version 1.6
# http://www.youtube.com/
#
# This plugin is released under GPL free license.
#
# Pablo Chinea <khertz@gmail.com>
# Mark Rose <markrose@markrose.ca>
#################################################

if [[ $1 == '-q' ]]
then
	echo "FLVGET_PLUGIN|YouTube|youtube.com"
	exit 0
fi

tempfile="/tmp/flvget/tmp$$"
trap "rm -f $tempfile" 0 1 2 5 15

wget -q "$1" -O $tempfile 

# Contain content flagged as inappropriate
if [[ -n $(cat $tempfile | grep "login?next_url") ]]
then
	if [[ -z $(dcop kded kcookiejar findCookies "http://www.youtube.com" | grep -E "LOGIN_INFO=[[:alnum:]]+;") ]]
	then
		if ( kdialog --warningyesno "You must be logged into www.youtube.com (in Konqueror) to download videos flagged as inappropriate. Do you want to log in now?" --title "Log in required" --caption "FLVGET" )
		then
			user=$(kdialog --caption "YouTube Login" --inputbox "Username:")
			pass=$(kdialog --caption "YouTube Login" --password "Insert password for user $user")
			cookiedata=$(wget -q --save-cookies /dev/stdout --post-data "current_form=loginForm&username=$user&password=$pass&action_login=Log+In" "http://www.youtube.com/login" -O /dev/null | grep LOGIN_INFO | awk '{ print $7 }')
			if [[ -z $cookiedata ]]
			then
				kdialog --error "Login incorrect"
				exit 1
			fi
			dcop kded kcookiejar addCookies "http://www.youtube.com" "Set-Cookie:LOGIN_INFO=$cookiedata;domain=.youtube.com;path=/" 1
		else
			kfmclient exec "http://www.youtube.com/signup"
			exit 1
		fi
	fi
	dcop kded kcookiejar addCookies "http://www.youtube.com" "Set-Cookie:is_adult=8d3a778dcb047f7c9a6ab4917e55b74adAEAAAAx;domain=.youtube.com;path=/" 1
	rm -f $tempfile
	kfmclient copy "$1" $tempfile
fi

video_id=$(cat $tempfile | grep swfArgs | head -1 | cut -d'{' -f2 | tr ',' '\n' | grep '"video_id":' | cut -d'"' -f4)
t=$(cat $tempfile | grep swfArgs | head -1 | cut -d'{' -f2 | tr ',' '\n' | grep '"t":' | cut -d'"' -f4)
url="http://www.youtube.com/get_video?video_id=$video_id&t=$t"
filename="$(cat $tempfile | grep meta | grep title | cut -d'"' -f4 | sed -e 's/\W/_/g').flv"

echo "$url|$filename"
