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

/**
 * Content URL extractor plugin for Hypem audio feeds.
 * 
 * The AUTH cookie might expire with time, it will then have to be replaced with a
 * new one (from the browser)
 *
 * @author Petr Nejedly
 *
 */
class Hypem extends FeedItemUrlExtractor {
	
	final VALID_FEED_URL = '^(?:https?://)?(?:www\\.)?hypem\\.com/feed/.*$'
	final USER_AGENT = 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.186 Safari/535.1'
	final COOKIES = ['AUTH':'03%3A2c74bfb5c1711f11115de69c8aa345f9%3A1342866525%3A1524063429%3AH9-GB']
	
	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 matcher = linkUrl =~ '^.+/item/(\\w+)/'
		assert matcher != null
		assert matcher.hasGroup()
		
		def itemId = matcher[0][1]

		// load the video web page
		String pageHtml = openURL(linkUrl, USER_AGENT, COOKIES)
		String regex = "(?s)id:\'$itemId\',.*?key:.*?\'(\\w+)\'"
		def pageMatcher = pageHtml =~ regex
		assert pageMatcher != null
		def contentId = pageMatcher[0][1]
		String timestamp = new Date().getTime()
		String infoUrl = "http://hypem.com/serve/source/$itemId/$contentId?_=$timestamp"
		String contentInfo = openURL(new URL(infoUrl), USER_AGENT, COOKIES)
		
		// get file URL
		def contentMatcher = contentInfo =~ '(?s)\"url\":\"(.+?)\"'
		assert contentMatcher != null
		contentUrl = contentMatcher[0][1].replaceAll('\\\\','')
		
		return new ContentURLContainer(fileType: MediaFileType.AUDIO, contentUrl: contentUrl)
	}
	
	static void main(args) {
		// this is just to test
		Hypem extractor = new Hypem()
		
		assert extractor.extractorMatches( new URL("http://hypem.com/feed/popular/3day/1/feed.xml") )
		assert !extractor.extractorMatches( new URL("http://google.com/feeds/api/standardfeeds/top_rated?time=today") )
		
		Map videoLinks = ['default': new URL('http://hypem.com/item/1nje9/Cassette+Club+-+Flash+(Ben+Macklin+Remix)')]
		ContentURLContainer result = extractor.extractUrl(videoLinks, PreferredQuality.MEDIUM)
		println "Result: $result"		 
	}
}