import org.serviio.library.metadata.*
import org.serviio.library.online.*
import org.serviio.util.*
import groovy.util.XmlParser
import java.net.*;
import java.io.*;
import java.util.*;
import java.text.*
import java.util.regex.PatternSyntaxException
import java.util.regex.Pattern
import java.util.regex.Matcher
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder


/**
 * WebResource plugin for Ustream
 * @author insane822
 * Version 1.0
 *
 */

class Ustream extends WebResourceUrlExtractor {

    // Feed URL regex
    final VALID_FEED_URL = '^http://www.ustream.tv/.*'

    // Plug-in name
    String getExtractorName() {
        return 'Ustream'
    }

    // Valid URL
    boolean extractorMatches(URL feedUrl) {
        return feedUrl ==~ VALID_FEED_URL
    }

    String user_agent = "Mozilla/5.0"


    // Resource Container
    WebResourceContainer extractItems(URL resourceUrl, int maxItems) {
        List<WebResourceItem> items = []
 
        def html = openURL(resourceUrl, user_agent)
        def amf_url = html =~ "www.ustream.tv/embed/(\\d+)"
        amf_url = "http://cgw.ustream.tv/Viewer/getStream/1/${amf_url[0][1]}.amf"
        def amf_data = openURL(new URL(amf_url), user_agent)
        def rtmp_match = amf_data =~ ".*(rtmp://.+?)\\x00.*"
        def rtmp_play_match = amf_data =~ ".*streamName\\W\\W\\W(.+?)[/]*\\x00.*"
        def swf_url = new URL("http://www.ustream.tv/flash/viewer.swf")
        def thumbnail = html =~ /"og:image" content="(.*?)"/
        String thumbnail_url = thumbnail[0][1]
        def title_match = html =~ "<meta name=\"title\" content=\"(.*?)\""
        String title = title_match[0][1]
        HttpURLConnection connection = (HttpURLConnection) swf_url.openConnection();
        connection.setInstanceFollowRedirects(false);

        // RTMP server
        String rtmp_server = rtmp_match[0][1]
        // RTMP playpath
        String rtmp_playpath = rtmp_play_match[0][1]
        // RTMP swfUrl
        String swf_url_final = connection.getHeaderField("Location")
        // RTMP pageURL
        String page_url = resourceUrl
        print html
        String rtmp_url = "${rtmp_server} playpath=${rtmp_playpath} swfUrl=${swf_url_final} pageUrl=http://live.twit.tv swfVfy=1 live=true"

        
        
        items << new WebResourceItem(title: title, additionalInfo: [thumbnailUrl: thumbnail_url, stream: rtmp_url])

        return new WebResourceContainer(title: title, items: items)

    }


    // Content URL
    ContentURLContainer extractUrl(WebResourceItem item, PreferredQuality requestedQuality) {


        String cacheKey = item.additionalInfo.stream
        println "ffmpeg.exe -i \"${item.additionalInfo.stream}\"  w45hgewfq4334.avi"

        return new ContentURLContainer(contentUrl: item.additionalInfo.stream, cacheKey: cacheKey, expiresImmediately: true, live:  true, thumbnailUrl: item.additionalInfo.thumbnailUrl)
    }

    // This is just to test, not actual code used for the plugin
    static void main(args) {

        Ustream extractor = new Ustream()

        String series_url = "http://www.ustream.tv/ffrc"
        WebResourceContainer container = extractor.extractItems( new URL(series_url), -1)
        //print container
        container.getItems().each {
            ContentURLContainer result = extractor.extractUrl(it, PreferredQuality.HIGH)
            println result
        }
        println container


    }
}

