
import org.serviio.library.metadata.*
import org.serviio.library.online.*
import org.serviio.util.*

/**
 * Content URL extractor plugin for Daily Motion video feeds.
 *
 * @author Petr Nejedly
 *
 */
class DailyMotion extends FeedItemUrlExtractor {
	
	final VALID_FEED_URL = '^(?:https?://)?(?:www\\.)?dailymotion\\.[a-z]{2,3}/rss/.*$'
	
	String getExtractorName() {
		return 'DailyMotion'
	}
	
	boolean extractorMatches(URL feedUrl) {
		return feedUrl ==~ VALID_FEED_URL
	}
	
	ContentURLContainer extractUrl(Map links, PreferredQuality requestedQuality) {
		def linkUrl = links.default
		def contentUrl
		
		def matcher = linkUrl =~ '^.+/video/([^_/]+)_([^/]+)$'
		assert matcher != null
		assert matcher.hasGroup()
		
		def videoId = matcher[0][1]
		
		// load the video web page and look for stream URL
		String pageHtml = linkUrl.getText()
		def vidUrlMatcher = pageHtml =~ '(?s)%22video_url%22%3A%22(.*?)%22'
		assert vidUrlMatcher != null
		String vidUrl = URLDecoder.decode(vidUrlMatcher[0][1],'UTF-8')		
		return new ContentURLContainer(contentUrl: URLDecoder.decode(vidUrl,'UTF-8')		)
	}
	
	def String findSuitableQuality(List items, PreferredQuality requestedQuality) {
		if(requestedQuality == PreferredQuality.LOW) {
			// worst quality, get the first from the list
			return items.head()
		} else if (requestedQuality == PreferredQuality.MEDIUM) {
			// get item from the middle
			return items.get(Math.floor(items.size()/2).toInteger())
		} else {
			// best quality, take the last url
			return items.last()
		}
	}
	
	static void main(args) {
		// this is just to test
		DailyMotion extractor = new DailyMotion()
		
		assert extractor.extractorMatches( new URL("http://www.dailymotion.com/rss/gb/visited-today/creative-official/1") )
		assert !extractor.extractorMatches( new URL("http://google.com/feeds/api/standardfeeds/top_rated?time=today") )
		
		Map videoLinks = ['default': new URL('http://www.dailymotion.com/video/xm6cn9_ajax-lose-10-goal-thriller_sport')]
		ContentURLContainer result = extractor.extractUrl(videoLinks, PreferredQuality.MEDIUM)
		println "Result: $result"		 
	}
}