import groovy.json.JsonSlurper
import org.serviio.library.metadata.*
import org.serviio.library.online.*
import org.serviio.util.*

/**
 * WebResource extractor plugin for sopcast
 * 
 * @author jhb50
 *
 * Version 1 - Aug 27, 2012
 * Version 2 - Sept. 1, 2012 - Add Items option; expand description below.
 * Version 3 - Check if stream exists before adding to avoid 60 ffmpeg delay on refresh
 * Version 4 - Refresh of V3 which was never uploaded.
 * Version 5 - Feb 17, 2013 - Fix parameter processing
 *
 * This groovy supports the play of SOPCAST streams on Serviio Clients
 * It should be added to Serviio as a webresource using the dummy link www.sopcast.com?port=nnnn&items=mm
 * where nnnn is the port used by SOPCAST for its streams eg http://localhost:8902
 * and mm is the number of Sopcast feed items you would like in the SOPCAST folder.
 * 7 SOPCAST items are provided by default which will automatically handle 6 stream breaks. 
 *
 * After a Sopcast stream is started using SOPCAST or IE, the Serviio Online Sopcast folder
 * may then be opened and the Sopcast#1 menu item selected. If there are no items in the folder,
 * or if the stream does not play correctly, simply refresh the Serviio Webresource.
 * This will cause the current SOPCAST stream at http://localhost:nnnn to be analysed
 * and the appropriate transcoding for the characteristics of that stream to be initiated.
 *
 * Should playback be interrupted by a stream error, Serviio will automatically reopen
 * the next SOPCAST menu item and resume playback of the SOPCAST stream.
 *
 *
 */
class Sopcast extends WebResourceUrlExtractor {
	
	final VALID_FEED_URL = '^http://www.sopcast.com.*?'
	
	String getExtractorName() {
		return 'Sopcast'
	}
	
	int getVersion() {
		return 5
	}

	Boolean URLExists(URL fileURL){
		if(((HttpURLConnection) fileURL.openConnection()).getResponseCode() == 404){
			return false
		}
		return true
	}

	boolean extractorMatches(URL feedUrl) {
		return feedUrl ==~ VALID_FEED_URL
	}
	
	WebResourceContainer extractItems(URL resourceUrl, int maxItems) {

		log("Parsing with Sopcast V5")
	
		List<WebResourceItem> items = []
		def itemsAdded = 0;

		String pageTitle = "SOPCAST"
		String pageThumb = "https://sites.google.com/site/serviiorss/sopcast.jpg"
		String linkUrl = "http://localhost"
		String thumbUrl = "https://sites.google.com/site/serviiorss/sopcast.jpg"
		String videoRoot = "Sopcast"
		String Port = "8902"
		int numItems = 7
		String videoTitle
		
		def parmMatcher = resourceUrl =~ '^http://www.sopcast.com.*?port=([0-9]+)'
		def parmMatch = resourceUrl ==~ '^http://www.sopcast.com.*?port=[0-9]+.*?'
		if (parmMatch){
			Port = parmMatcher[0][1].trim()
		}
		parmMatcher = resourceUrl =~ '^http://www.sopcast.com.*?items=([0-9]+)'
		parmMatch = resourceUrl ==~ '^http://www.sopcast.com.*?items=[0-9]+.*?'
		if (parmMatch){
			numItems = parmMatcher[0][1].trim().toInteger()
		}
		
		linkUrl = linkUrl + ":" + Port

		for( int j = 0; j < numItems; j++) {
			int itemNo = j+1
			videoTitle = videoRoot + " #" + itemNo
				
			WebResourceItem item = new WebResourceItem(title: videoTitle, additionalInfo: ['linkUrl':linkUrl,'thumbUrl':thumbUrl,'port':Port])
			items << item
		}
		return new WebResourceContainer(title: pageTitle, thumbnailUrl: pageThumb, items: items)
	}
		
	ContentURLContainer extractUrl(WebResourceItem item, PreferredQuality requestedQuality) {		
		String videoTitle = item.title
		String linkUrl = item.getAdditionalInfo()['linkUrl']

		if (!URLExists(new URL(linkUrl))) return

		String thumbnailUrl = item.getAdditionalInfo()['thumbUrl']
		String Port = item.getAdditionalInfo()['port']
		long curTime = System.currentTimeMillis()/60000
		
		def cacheKey = "sopcast" + Port + curTime
		
		log("refeshing " + videoTitle)
		return new ContentURLContainer(fileType: MediaFileType.VIDEO, contentUrl: linkUrl, thumbnailUrl: thumbnailUrl, live: true, expiresImmediately: true, cacheKey: cacheKey)
	}

	
	static void main(args) {
		Sopcast extractor = new Sopcast()		
		assert extractor.extractorMatches( new URL("http://www.sopcast.com?port=8902")) 
		WebResourceContainer container = extractor.extractItems( new URL("http://www.sopcast.com?port=8904&items=4"), -1)

		container.getItems().each {
            ContentURLContainer result = extractor.extractUrl(it, PreferredQuality.MEDIUM)
            println result 
        }   
	}
}
