import org.serviio.library.metadata.*
import org.serviio.library.online.*

/**
 * Tv4Play.se content URL extractor plugin. - 
 *
 * @version 1.0
 * 
 *	http://www.tv4play.se/rss/film_och_serier
 *	http://www.tv4play.se/rss/noje
 *	http://www.tv4play.se/rss/film_och_serier/den_som_draper
 *	http://www.tv4play.se/rss/sport
 *  
 * @author Tomas Falemo
 *
 */

 /**

	Useful stuff
	------------
	program url:
	http://www.tv4play.se/noje/pengarna_pa_bordet?title=pengarna_pa_bordet_del_3&videoid=2082183
	http://www.tv4play.se/noje/pengarna_pa_bordet?title=pengarna_pa_bordet_del_3&videoid=[VIDEOID]

	videoinfo:
	premium.tv4play.se/api/web/asset/2082183/play
	premium.tv4play.se/api/web/asset/[VIDEOID]/play
		videourl:
		<url>mp4:/mp4root/2011-10-17/pid3473614_2082183_T3MP425_.mp4</url>
		subtitles:
		http://anytime.tv4.se/multimedia/vman/smiroot/2011-10-17/pid3473614!2082183,T3HSMIL!.smi?

	playcommand:
	ffmpeg -i "rtmpe://cp70051.edgefcs.net:1935/tv4ondemand swfUrl=http://www.tv4play.se/flash/tv4playflashlets.swf playpath=mp4:/mp4root/2011-03-30/pid3046273_1542857_T3MP425_.mp4 swfVfy=1"

	metadata:
	www.tv4play.se/search/search.json?vmanid=2082183
		"thumbnail":"http://img.tv4.se/?resize=180x101&source=http://cdn01.tv4.se/polopoly_fs/1.2316577!picture/2865477220.jpg"

 */
class Tv4Play extends FeedItemUrlExtractor {
    
    final VALID_FEED_URL = '^http(s)*://www.tv4play.se/rss/.*$'   

    String getExtractorName() {
        return getClass().getName()
    }
    
    boolean extractorMatches(URL feedUrl) {
        return feedUrl ==~ VALID_FEED_URL
    }
    
    ContentURLContainer extractUrl(Map links, PreferredQuality requestedQuality) {
		// Extract VideoID
		// http://www.tv4play.se/noje/pengarna_pa_bordet?title=pengarna_pa_bordet_del_3&videoid=2082183
	    def linkUrl = ""+links.default
		// [http://www.tv4play.se/noje/pengarna_pa_bordet?title , pengarna_pa_bordet_del_3&videoid, 2082183]
		def linkparts =  linkUrl.split("=")
		// 2082183
		def progID = linkparts[linkparts.length-1]
		
		def contentUrl
		def contentHtml

		// Get the page containing the actual video url
		// premium.tv4play.se/api/web/asset/2082183/play
		def url = new URL('http://premium.tv4play.se/api/web/asset/'+progID+'/play')
		def connection = url.openConnection()
		if(connection.responseCode == 200){
			contentHtml = connection.content.text
		}
		else{
			return null
		}

		// Extract the video url
		// example of match: mp4:/mp4root/2011-10-17/pid3473614_2082183_T3MP425_.mp4
		def matcher = (contentHtml =~ '.*<url>(mp4.*?)</url>')
		// matcher will contain url:s ordered by quality with highest quality first 
		assert matcher != null
		if(matcher.size() > 0)
		{
			// HIGH and if only 1 quality found then use it
			contentUrl = matcher[0][1]
			if(matcher.size() > 1)
			{
				if(requestedQuality == PreferredQuality.MEDIUM)
				{
					contentUrl = matcher[1][1]
				}
				if(requestedQuality == PreferredQuality.LOW)
				{
					int index = matcher.size()-1
					contentUrl = matcher[index][1]
				}
			}
			// Build ffmpeg string
			contentUrl = 'rtmpe://cp70051.edgefcs.net:1935/tv4ondemand swfUrl=http://www.tv4play.se/flash/tv4playflashlets.swf playpath='+contentUrl+' swfVfy=1'
		}
		else
		{
			return null
		}		
		
		// Get the metadata for the video - we need this for thumbnail
		url = new URL('http://www.tv4play.se/search/search.json?vmanid='+progID)
		connection = url.openConnection()
		if(connection.responseCode == 200){
			contentHtml = connection.content.text
		}
		
		// Extract the thumbnail url
		// example of match: "thumbnail":"http://img.tv4.se/?resize=180x101&source=http://cdn01.tv4.se/polopoly_fs/1.2316577!picture/2865477220.jpg"
		def imageMatcher = (contentHtml =~ '.*thumbnail\\"\\:\\"(http.*?\\.jpg|http.*?\\.gif)')
		def thumbUrl = ""
		if(imageMatcher.size() > 0)
		{
			thumbUrl = imageMatcher[0][1]
		}
        return new ContentURLContainer(fileType: MediaFileType.VIDEO, contentUrl: contentUrl, thumbnailUrl: thumbUrl)
    }
    
    static void main(args) {
		// this is just to test
        Tv4Play extractor = new Tv4Play()
		
		assert extractor.extractorMatches( new URL("http://www.tv4play.se/rss/film_och_serier") )
		assert !extractor.extractorMatches( new URL("http://google.com/feeds/api/standardfeeds/top_rated?time=today") )
		
        //Map links = ['default': new URL('http://www.tv6play.se/play/234829/')] 
        //ContentURLContainer result = extractor.extractUrl(links, PreferredQuality.MEDIUM)
        //println "Result: $result"
		
		// premium-only show
		//Map links = ['default': new URL('http://www.tv4play.se/dokumentarer/akutmottagningen?title=akutmottagningen_del_15&videoid=1142950')]
        Map links = ['default': new URL('http://www.tv4play.se/noje/pengarna_pa_bordet?title=pengarna_pa_bordet_del_3&videoid=2082183')] 
        ContentURLContainer result1 = extractor.extractUrl(links, PreferredQuality.LOW)
		ContentURLContainer result2 = extractor.extractUrl(links, PreferredQuality.MEDIUM)
		ContentURLContainer result3 = extractor.extractUrl(links, PreferredQuality.HIGH)
        println "Result Low: $result1"
        println "Result Medium: $result2"
        println "Result High: $result3"
    }
}