import org.serviio.library.metadata.*
import org.serviio.library.online.*


/********************************************************************
 * USTREAM plugin for Serviio
 *
 * Logic by forum member: piscui - http://piscui.webear.net/ustream.php
 * 
 * @author X S Inattar
 *
 * Must be installed as a Video WebResource
 * Sample URLs: 
 *    http://www.ustream.tv/nasahdtv
 * 
 * Version:
 *    V1: July 28, 2012 - Initial Release
 *
 ********************************************************************/

class USTREAM extends WebResourceUrlExtractor {
    
    final VALID_FEED_URL = '^(?:http://)?(?:www\\.)?ustream\\.tv/(.*?)(?:/)?$'
    final BASE_URL = 'http://www.ustream.tv/'
    final CHANNEL_ID_EXTRACTOR = 'cid=(.*?)&amp'
    final THUMBNAIL_EXTRACTOR_1 = '<img class="image" alt="(.*?)" width="66" height="66" src="(.*)" rel="(.*)" />'
    final THUMBNAIL_EXTRACTOR_2 = '<img src="(.*)" alt="(.*?)" title="(.*?)" />'
    final TITLE_EXTRACTOR = '<meta property="og:title" content="(.*)" />'
    final PLAYPATH_EXTRACTOR = "streamName\\W\\W\\W(.+?)\\x00"
    final TCURL_EXTRACTOR_1 = "cdnUrl\\W\\W\\S(.*?)\\x00"
    final TCURL_EXTRACTOR_2 = "fmsUrl\\W\\W\\S(.*?)\\x00"
    final SWF_URL = 'http://static-cdn1.ustream.tv/swf/live/viewer.rsl:96.swf'
    final AMF_URL = 'http://cgw.ustream.tv/Viewer/getStream/1/<!--ChannelID-->.amf';

    String getExtractorName() {
        return 'ustream.tv'
    }
    
    boolean extractorMatches(URL feedUrl) {
        return feedUrl ==~ VALID_FEED_URL
    }
       
    WebResourceContainer extractItems(URL resourceUrl, int maxItemsToRetrieve) {
            
        List<WebResourceItem> items = []
        def itemsAdded = 0

        def channelCodeMatcher = resourceUrl.toString() =~ VALID_FEED_URL
        if (channelCodeMatcher.count <= 0 ) {
            return null
        }
        def channelText = new URL(BASE_URL + channelCodeMatcher[0][1]).getText()
        
        def channelIdMatcher = channelText =~ CHANNEL_ID_EXTRACTOR
        if (channelIdMatcher.count <= 0) {
            return null
        }
        def channelId = channelIdMatcher[0][1]
        println channelId

        def channelTitle = channelCodeMatcher        
        def channelTitleMatcher = channelText =~ TITLE_EXTRACTOR
        if (channelTitleMatcher.count > 0) {
            channelTitle = channelTitleMatcher[0][1]
        }
        println channelTitle
        
        def channelThumb = null
        def channelThumbMatcher_1 = channelText =~ THUMBNAIL_EXTRACTOR_1
        if (channelThumbMatcher_1.count > 0) {
            channelThumb = channelThumbMatcher_1[0][2]
        }
        else {
            def channelThumbMatcher_2 = channelText =~ THUMBNAIL_EXTRACTOR_2
            if (channelThumbMatcher_2.count > 0) {
                channelThumb = channelThumbMatcher_2[0][1]
            }
        }
        println channelThumb
        
        items << new WebResourceItem(title: channelTitle, additionalInfo: [GUID: channelId, thumbnailUrl: channelThumb] )                        
        
        return new WebResourceContainer(title: channelTitle, items: items)
    }

    ContentURLContainer extractUrl(WebResourceItem item, PreferredQuality requestedQuality) {
        
        def dataurl = AMF_URL
        dataurl = dataurl.replaceAll("<!--.*?-->", item.additionalInfo.GUID)
        println dataurl           
        def data = new URL(dataurl).getText()
        
        def playpath_matcher = data =~ PLAYPATH_EXTRACTOR
        if (playpath_matcher.count <= 0) {
            return null
        }
        def playpath = playpath_matcher[0][1]
        
        def rtmpurl = ''
        def tcurl_matcher_1 = data =~ TCURL_EXTRACTOR_1
        if (tcurl_matcher_1.count > 0) {
            rtmpurl = tcurl_matcher_1[0][1]
        }
        else {
            def tcurl_matcher_2 = data =~ TCURL_EXTRACTOR_2
            if (tcurl_matcher_2.count > 0) {
                rtmpurl = tcurl_matcher_2[0][1]
                rtmpurl = rtmpurl.replaceAll('/ustreamVideo', ':1935/ustreamVideo')
                rtmpurl = rtmpurl + '/'
            }
            else {
                return null
            }
        }
        
        def contentUrl = rtmpurl + ' playpath=' + playpath + ' swfUrl=' + SWF_URL + ' swfVfy=1 live=1'  
        
        def cacheKey = 'USTREAM_' + item.additionalInfo.GUID              
       
        return new ContentURLContainer(contentUrl: '"' + contentUrl + '"', thumbnailUrl: item.additionalInfo.thumbnailUrl, expiresImmediately: true, cacheKey : cacheKey, live: true)    
    }
        
    static void main(args) {
    
        USTREAM extractor = new  USTREAM()
        
        WebResourceContainer container = extractor.extractItems( new URL("http://www.ustream.tv/nasahdtv"), 20)
        container.getItems().each {
            ContentURLContainer result = extractor.extractUrl(it, PreferredQuality.MEDIUM)
            println result 
        }   
    }
}