import org.serviio.library.metadata.*
import org.serviio.library.online.*

/**
 * ORF-IPTV content URL extractor plugin. 
 * 
 * http://rss.orf.at/iptv.xml
 *  
 * @author Gerwin Szabo
 *
 */
class Orf extends FeedItemUrlExtractor {
    
    final VALID_FEED_URL = '^http(s)*://rss.orf.at/.*$'   

    String getExtractorName() {
        return getClass().getName()
    }
    
    boolean extractorMatches(URL feedUrl) {
        return feedUrl ==~ VALID_FEED_URL
    }
    
    ContentURLContainer extractUrl(Map links, PreferredQuality requestedQuality) {
        def linkUrl = links.default
	def contentUrl
	def thumbnailUrl = "http://iptv.orf.at/mojo/storyserver//iptv/images/logo.orfon.png"

		def contentHtml
		def url = new URL(''+linkUrl)
		def connection = url.openConnection()
		if(connection.responseCode == 200){
			contentHtml = connection.content.text
		}
		else{
			return null
		}
		// example of match: rtmp://fl11.c91005.cdn.qbrick.com/91005/_definst_/kluster/20110922/PG-1146034-001A-MITTINATUREN2-02-mp4-e-v1.mp4 
		def matcher = (contentHtml =~ '.*(http.*\\.flv)')
		assert matcher != null
		if(matcher.size() > 0)
		{
			contentUrl = matcher[0][1]
			printf contentUrl

			matcher = (contentHtml =~ '.*(http.*\\.jpg)')
			assert matcher != null
			if(matcher.size() > 0)
			{
				thumbnailUrl = matcher[0][1]
				printf thumbnailUrl
			}		
		}
		else
		{
			return null
		}		

        return new ContentURLContainer(fileType: MediaFileType.VIDEO, contentUrl: contentUrl, thumbnailUrl: thumbnailUrl)
    }
    
    static void main(args) {
	// this is just to test
        Orf extractor = new Orf()
		
		assert extractor.extractorMatches( new URL("http://rss.orf.at/iptv.xml") )
		assert !extractor.extractorMatches( new URL("http://google.com/feeds/api/standardfeeds/top_rated?time=today") )
		
        Map links = ['default': new URL('http://rss.orf.at/iptv.xml')] 
        ContentURLContainer result = extractor.extractUrl(links, PreferredQuality.MEDIUM)
        println "Result: $result"
    }
}
