#!/bin/bash
#Pmusic
#Copyright 2008,2009,2010,2011,2012,2013
#Sigmund Berglund - Valåmoen, Norway.
export TEXTDOMAIN=pmusic
alias wget='wget -U "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15" -t 1 --connect-timeout=1'

case "$1" in
-get_youtube_url)
	#downloading html file
	wget -O $WORKDIR/youtube "$2" -q
	#get title - first try index_webmusic_youtube
	TITLE="`grep -Fm1 "$2" "$STORAGE_DIR/index_webmusic_youtube" | cut -d'|' -f2`"
	ARTIST="`grep -Fm1 "$2" "$STORAGE_DIR/index_webmusic_youtube" | cut -d'|' -f3`"
	export NAME="$ARTIST - $TITLE"
	#if not in index, detect from youtube.com
	if [ ! "$TITLE" ]; then
		NAME=$(grep -m1 -o "<meta name=\"title\" content=\".*\">" $WORKDIR/youtube)
		NAME=`expr match "$NAME" '<meta name=\"title\" content=\"\(.*\)\">'`
		export NAME=${NAME//\//"-"}
	fi
	#---
#	XML=$(grep -o "'PLAYER_CONFIG': {.*}" $WORKDIR/youtube)
	XML=$(grep -F "'PLAYER_CONFIG':" $WORKDIR/youtube)
	#length from index_webmusic_youtube
	LENGTH="`grep -Fm1 "$2" "$STORAGE_DIR/index_webmusic_youtube" | cut -d'|' -f9`"
	[ ! "$LENGTH" ] && LENGTH=59:59 #no length is found in index_webmusic_youtube
	#define URL
#	URL=${XML#*\"fmt_url_map\": \"}
	URL=${XML#*\"url_encoded_fmt_stream_map\": \"}
#	URL=${URL%%\"*}
#	URL=`echo ${URL//,/ } | tac -s' ' | cut -d' ' -f1 | tail -n1`
#	URL=${URL#*|}
#	URL=${URL%%|*}
	URL="`echo "$URL" | cut -d, -f2`"
	URL=${URL//\\\///}
	URL=${URL//\\\u0026/&}
	export URL="$(echo $URL | cut -d= -f2- | sed -e s/\\http:[^\]]*\\.v/http:\\/\\/v/ | sed -f $APPDIR/sed_ascii2txt)"
	;;
-jamendo_top100)
	#---
	[ "$2" ] && GENRE="&tag_idstr=$2"
	echo "|$(gettext 'Connecting to') jamendo.com..." > $WORKDIR/sourcelist
	echo true > $WORKDIR/UPDATE_SOURCELIST
	#check internet connection
	LANG=C wget --spider "http://www.jamendo.com" 2> $WORKDIR/tmpinfo
	if [ ! "`grep -F 'connected' $WORKDIR/tmpinfo`" ]; then
		echo "|$(gettext 'No connection to jamendo.com')" > $WORKDIR/sourcelist
	else
		wget --tries 1 -O - "http://api.jamendo.com/get2/id+artist_name+name+album_name+numalbum+dates+genre+duration/track/plain/track_album+album_artist/?n=100&order=ratingweek_desc${GENRE}" | tr '\t' '|' | sed -e 's/Array//g' -e 's/^/http:\/\/api.jamendo.com\/get2\/stream\/track\/redirect\/?streamencoding=mp31\&id=/g' > $WORKDIR/sourcelist
	fi
	$APPDIR/func -add_to_history "pMusic: Jamendo.com $2" & #update history
	echo true > $WORKDIR/UPDATE_SOURCELIST
	;;
-build_jamendo_index)
	LANG=C wget --tries=1 -O $WORKDIR/tmp_jamendo_dump.gz http://imgjam.com/data/dbdump_artistalbumtrack.xml.gz
	gunzip $WORKDIR/tmp_jamendo_dump.gz
	COUNT=0
	TOTAL=`wc -l $WORKDIR/tmp_jamendo_dump | cut -d' ' -f1`
	echo "preparing input data..."
	echo -n > $WORKDIR/index_jamendo
	while read I; do #read index file line by line (artist by artist)
		#split all xml tags into newlines
		echo "$I" | tr '>' '\n' | grep -E "<album|</album|</id|</name|</releasedate|</id3genre|</numalbum|</track|</duration" > $WORKDIR/tmp_jamendo
		#find artist
		ARTIST="`grep -Fm1 '</name' $WORKDIR/tmp_jamendo | cut -d'<' -f1`"
		#give some progress output
		if [ "$ARTIST" ]; then
			PERCENT=$(($COUNT*100/$TOTAL))
			echo "$COUNT(${PERCENT}%) `wc -l "$STORAGE_DIR/index_jamendo" | cut -d' ' -f1` $ARTIST"
			COUNT=$(($COUNT+1))
		fi
		#find albums
		grep -FA3 '<album' $WORKDIR/tmp_jamendo | grep -F '</name' | cut -d'<' -f1 > $WORKDIR/tmp_jamendo_albums
		while read ALBUM; do
			grep -A100 -Fm1 "$ALBUM" $WORKDIR/tmp_jamendo | tac | head -n -1 | tac > $WORKDIR/tmp_jamendo2
			while read J; do
				case "$J" in
					*"</album")	#we have reach next album
						break
						;;
					*"</id")
						ID="`echo "$J" | cut -d'<' -f1`"
						;;
					*"</name")
						TITLE="`echo "$J" | cut -d'<' -f1`"
						;;
					*"</releasedate")
						YEAR="`echo "$J" | cut -d'<' -f1 | cut -d'-' -f1`"
						;;
					*"</numalbum")
						TRACK="`echo "$J" | cut -d'<' -f1`"
						;;
					*"</duration")
						TMP="`echo "$J" | cut -d'<' -f1 | cut -d. -f1`" #seconds
						MIN=$(($TMP/60))
						SEC=$(($TMP-($MIN*60)))
						LENGTH=$(printf "%02d" $MIN):$(printf "%02d" $SEC)
						;;
					*"</id3genre")
						TMP="`echo "$J" | cut -d'<' -f1`"
						if [ "$TMP" ] && [ "$TMP" != "0" ]; then #if album_id3 is set, track_id3 could be set to 0
							GENRE="`grep "^${TMP}|" $APPDIR/txt_id3genre | cut -d'|' -f2`"
						fi
						;;
					*"</track")
						 #add item to index
						 echo "+${ID}|$ARTIST|$TITLE|$ALBUM|$TRACK|$YEAR|$GENRE||||96|$LENGTH" >> "$STORAGE_DIR/index_jamendo"
						;;
				esac
			done < $WORKDIR/tmp_jamendo2
			GENRE="" #not all items/albums has genre defined, so we clear it to avoid duplication in next album
		done < $WORKDIR/tmp_jamendo_albums
	done < $WORKDIR/tmp_jamendo_dump

	sed -f $APPDIR/sed_html2txt -i "$STORAGE_DIR/index_jamendo"
	mv -f "$STORAGE_DIR/index_jamendo" "$STORAGE_DIR/index_webmusic_jamendo"
	#turn on search-filter - off by default
	echo true > $WORKDIR/SEARCH_WEBMUSIC
	#cleanup
	rm $WORKDIR/tmp_jamendo*
	;;
-webmusic)
	#message 
	echo "|$(gettext 'Reading index. A moment')..." > $WORKDIR/sourcelist
	echo true > $WORKDIR/UPDATE_SOURCELIST #update source-list
	#check if db exists
	if [ ! -s "$STORAGE_DIR"/index_webmusic* ]; then
		echo -e "|$(gettext 'Missing index')|||||||||||||gtk-info\n|$(gettext 'See Setup in')\n|$(gettext 'Music sources menu')" > $WORKDIR/sourcelist
		echo true > $WORKDIR/UPDATE_SOURCELIST
		exit
	fi
	#show list of artists
	grep -F '|' "$STORAGE_DIR"/index_webmusic* | cut -d'|' -f2 | sort -u > $WORKDIR/tmp
	paste -d'|' $WORKDIR/tmp $WORKDIR/tmp > $WORKDIR/sourcelist
	sed -i 's%^.*%pmusic_webmusic_artist:&%g' $WORKDIR/sourcelist
	$APPDIR/func -add_to_history "pMusic: $(gettext 'Webmusic browse artist')" & #update history
	echo true > $WORKDIR/UPDATE_SOURCELIST
	;;
-webmusic_artist)
	#show list of albums
	echo 'pmusic_webmusic|..' > $WORKDIR/sourcelist
	grep -F "$2" "$STORAGE_DIR"/index_webmusic* | awk -F "|" '{print "pmusic_webmusic_album:"$4"|"$4"  ("$6")"}' | sort -u -nst'|' -k2,2 >> $WORKDIR/sourcelist
	$APPDIR/func -add_to_history "pMusic: $(gettext 'Webmusic browse album')" & #update history
	echo true > $WORKDIR/UPDATE_SOURCELIST #update source-list
	cp -f $WORKDIR/sourcelist $WORKDIR/sourcelist_webmusic_artist #keep a copy if user wants back
	;;
-webmusic_album)
	echo 'pmusic_webmusic_back|..' > $WORKDIR/sourcelist
	#show list of tracks
	grep -F "$2" "$STORAGE_DIR/index_webmusic_jamendo" | sed "s%+%http://api.jamendo.com/get2/stream/track/redirect/?streamencoding=mp31\&id=%" >> $WORKDIR/sourcelist
	grep -F "$2" "$STORAGE_DIR/index_webmusic_youtube" >> $WORKDIR/sourcelist
	$APPDIR/func -add_to_history "pMusic: $(gettext 'Webmusic browse tracks')" & #update history
	echo true > $WORKDIR/UPDATE_SOURCELIST #update source-list
	;;
-webmusic_back)
	cp -f $WORKDIR/sourcelist_webmusic_artist $WORKDIR/sourcelist
	$APPDIR/func -add_to_history "pMusic: $(gettext 'Webmusic browse album')" & #update history
	echo true > $WORKDIR/UPDATE_SOURCELIST #update source-list
	;;
-webmusic_manager)
	. $APPDIR/func -reset_gtk
	export pmusic_webmusic='
	<window title="pMusic - '$(gettext 'Web Music setup')'" icon-name="pmusic">
	<vbox>
	 '"$($APPDIR/func_svg -heading "$(gettext 'Web Music')")"'
	 <notebook labels=" '$(gettext 'Install')' | '$(gettext 'Advanced')' ">
	  <frame>
	   <text><label>"'$(gettext 'The WebMusic index is a file containing the information of all music at jamendo.com. pMusic will play WebMusic tracks without this index file, but it will benefit of it when it comes to browsing and advanced searching.

The index file will be 20Mb+ when installed, and contains info about 500000+ music tracks.')'"</label></text>
	   <hbox homogeneous="true"><hbox>
	    <button>
	     <input file stock="gtk-apply"></input>
	     <label>'$(gettext 'Install')'</label>
	     <action>EXIT:install</action>
	    </button>
	   </hbox></hbox>
	  </frame>
	  <frame>
	   <text><label>"'$(gettext 'The installable index may not hold the latest tracks at jamendo.com. You can build the index file yourself of the very recent info.

Depending on your system this process may take some hours.')'"</label></text>
	   <hbox homogeneous="true"><hbox>  
	    <button>
	     <label>'$(gettext 'Build index')'</label>
	     <action>EXIT:build</action>
	    </button>
	   </hbox></hbox>
	  </frame>
	 </notebook>
	 <hbox>
	  <text use-markup="true"><label>"<b>'$(gettext 'Date of index')':</b>"</label></text>
	  <text><input>find "'$STORAGE_DIR'/index_webmusic_jamendo" -printf "%Td.%Tb %TY   (%TH:%TM)"</input></text>
	  <text use-markup="true"><label>"  <b>'$(gettext 'WebMusic Tracks')':</b>"</label></text>
	  <text><input>grep -c ^ "'$STORAGE_DIR'/index_webmusic_jamendo"</input></text>
	  <button cancel></button>
	 </hbox>
	</vbox>
	</window>'
	I=$IFS; IFS=""
	for STATEMENTS in $($GTKDIALOG -p pmusic_webmusic); do
		eval $STATEMENTS
	done
	IFS=$I
	
	case $EXIT in
		install)
			echo "$(gettext 'Downloading WebMusic index.')" > $WORKDIR/splashtext
			$APPDIR/box_splash &
			#check internet connection
			LANG=C wget --spider "$FTP_SERVER/pmusic_index_webmusic_jamendo.gz" 2> $WORKDIR/tmp
			if [ "`grep -Ei "unable to resolve host|file does not exist" $WORKDIR/tmp`" ]; then
				#let's try the alternative ftp server
				LANG=C wget --spider "$FTP_SERVER_2/pmusic_index_webmusic_jamendo.gz" 2> $WORKDIR/tmp
				if [ "`grep -Ei "unable to resolve host|file does not exist" $WORKDIR/tmp`" ]; then
					sleep 0.2
					echo 100 > $WORKDIR/splash
					TXT1="<b>$(gettext 'No connection to server')</b>"
					. $APPDIR/box_ok
					exit
				else
					MY_SERVER="$FTP_SERVER_2"
					MY_USER="$FTP_USER_2"
					MY_PASSWORD="$FTP_PASSWORD_2"
				fi
			else
				MY_SERVER="$FTP_SERVER"
				MY_USER="$FTP_USER"
				MY_PASSWORD="$FTP_PASSWORD"
			fi
			#---
			wget --tries=1 --user $MY_USER --password $MY_PASSWORD --output-document="$STORAGE_DIR/index_webmusic_jamendo.gz" "$MY_SERVER/pmusic_index_webmusic_jamendo.gz"
			gunzip -f "$STORAGE_DIR/index_webmusic_jamendo.gz"
			#turn on search-filter - off by default
			echo true > $WORKDIR/SEARCH_WEBMUSIC
			echo 100 > $WORKDIR/splash
			;;
		build)
			xterm -hold -e $APPDIR/func_webmusic -build_jamendo_index &
			;;
	esac
#	$APPDIR/func_webmusic -webmusic &
#	echo true > $WORKDIR/UPDATE_SOURCELIST
	;;
esac
	