import org.serviio.library.metadata.*
import org.serviio.library.online.*
import org.serviio.util.*
import java.io.FileInputStream
import java.util.zip.GZIPInputStream

/********************************************************************
 * coolsport plugin for Serviio
 * 
 * @author JHB50
 *
 * URL to use as video webresource: http://www.coolsport.tv/
 *
 * Also displays next 2 scheduled events for each channel
 * For complete schedule see http://www.coolsport.tv/
 * 
 * Version:
 *    V1: - Nov 25, 2012 - Initial Release
 *    V2: - Dec  1, 2012 - Add dummy item if no feed items found
 *    V3: - Dec  5, 2012 - new time parameter
 *    V4: - Dec  7, 2012 - correct parameter processing
 *    V5: - Dec  8, 2012 - new web format
 *    V6: - Dec  9, 2012 - correct local time calculation
 *    V7: - Dec 16, 2012 - Add AM PM events, channel to title, fix incorrect 12:00PM
 *    V8: - Dec 17, 2012 - another new web format
 *    V9: - Dec 31, 2012 - verify network active before parsing
 *    V10 - Jan  1, 2013 - add sched=1 option for slow cpus.
 *    V11 - Jan 10, 2013 - another new web format
 *    V12 - Feb  3, 2013 - Genurls added by default to minimize extracts
 *    V13 - Feb  4, 2013 - Fix bug
 *    V14 - Feb  5, 2013 - Add timeout timer, put time first
 *    V15 - Feb 10, 2013 - Skip ch25 which never works
 *    V16 - Feb 11, 2013 - Only show language if its not ENGLISH
 *    V17 - Feb 18, 2013 - Add Custom channels
 *    V18 - Mar  8, 2013 - Increase Extract Timeout to 90 seconds 
 *    V19 - Mar 18, 2013 - Support KiwiSportz
 *    V20:- Mar.27, 2013 - update sources
 *    V21:- Apr.19, 2013 - Update icons
 *
 ********************************************************************/
 
 class Coolsport extends WebResourceUrlExtractor {
 
	long StartETime = 0
	long LastETime2 = 0
	long LastETime3 = 0
	
	List<WebResourceItem> newitems = []
	List<WebResourceItem> olditems = []

	final VALID_RESOURCE_URL = '^http://www.coolsport.tv.*?'
 
	String getExtractorName() {
		return 'coolsport'
	}
    
	boolean extractorMatches(URL resourceUrl) {
		return resourceUrl ==~ VALID_RESOURCE_URL
	}

	int getVersion() {
		return 21
	}
	
	int getExtractItemsTimeout() {
		return 90
	}	
	
	Long ETimer(String msg){
		long CurrentTime = System.currentTimeMillis()
		long Elapsed = CurrentTime - StartETime
		if (msg != null){
			log("$msg = $Elapsed msec")
		}
		return Elapsed
	}

	Long ETimer2(String msg){
		long CurrentTime = System.currentTimeMillis()
		long Elapsed = CurrentTime - LastETime2
		LastETime2 = CurrentTime
		if (msg != null){
			log("$msg = $Elapsed msec")
		}
		return Elapsed
	}
	
	Long ETimer3(String msg){
		long CurrentTime = System.currentTimeMillis()
		long Elapsed = CurrentTime - LastETime3
		LastETime3 = CurrentTime
		if (msg != null){
			log("$msg = $Elapsed msec")
		}
		return Elapsed
	}

	Boolean URLExists(String srcURL){
		URL fileURL = new URL(srcURL);
		if(((HttpURLConnection) fileURL.openConnection()).getResponseCode() == 404){
			return false
		}
		return true
	}
	
	String OpenProtURL(String srcURL,String Referrer) {        

		def rv = ""
		URL url = new URL(srcURL);
		URLConnection conn = url.openConnection();
		conn.setRequestProperty("Referer", Referrer);
		conn.setDoOutput(true);

		BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String line;
		while ((line = rd.readLine()) != null) {
			rv += line
		}
		rd.close();
		return rv
	}

	Boolean channelOffline(
		String htmlText, 
		String offlineChecker
	) {
		def offline_check = htmlText =~ offlineChecker
		if (offline_check.count > 0) {
			return true
		}
		return false
	}

	Boolean streamNotSupported(
		String htmlText, 
		String streamNotSupportedChecker
	) {
		def notsupported_check = htmlText =~ streamNotSupportedChecker
		if (notsupported_check.count > 0) {
			return true
		}
		return false
	}

    WebResourceContainer extractItems(URL resourceUrl, int maxItemsToRetrieve) {
    	
		log("Parsing with Coolsport V${getVersion()}")
		
		StartETime = System.currentTimeMillis()
		ETimer2()										

		def genurls = 1
		def curDate = new Date(System.currentTimeMillis()+300000)
		olditems = []
		if (newitems){
			def newitemssize = newitems.size()
			def nli = newitems.iterator()
			while (nli.hasNext()){
				def newEntry = nli.next()
				if(newEntry.getAdditionalInfo()['XexpiresImmediately']!= true) continue
				def SavedExpiryDate = newEntry.getAdditionalInfo()['XexpiresOn']
				if(SavedExpiryDate > new Date(0) && curDate >= SavedExpiryDate) continue
				olditems << newEntry
			}
			def olditemssize = olditems.size()
			log ( olditemssize + " items saved, " + (newitemssize - olditemssize) +  " expired" )
			olditems = olditems.drop(olditemssize-300)
			newitems = olditems
		}
		
		
		while(1) {
			def test_text = openURL(new URL("http://www.dogpile.com"),
				"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1")
			def testMatch = test_text ==~ '(?s).*?Dogpile Web Search.*?'
			if (testMatch) break
		}
			
		List<WebResourceItem> items = []
		short time = 0
		def itemsAdded = 0
		def channel_image = ""
		def srcUrl = ""
		def channel_title_text = ""
		long Refreshi = 0
		long Refresha = 0
		def sched = 2
		
		def noevents = 0


		def parmMatcher = resourceUrl =~ '^http://www.coolsport\\.tv.*?genurls=([0-1])'
		def parmMatch = resourceUrl ==~ '^http://www.coolsport\\.tv.*?genurls=[0-1].*?'
		if (parmMatch){
		    genurls = parmMatcher[0][1].trim()  
		}

		parmMatcher = resourceUrl =~ '^http://www.coolsport\\.tv.*?noevents=1'
		parmMatch = resourceUrl ==~ '^http://www.coolsport\\.tv.*?noevents=1.*?'
		if (parmMatch){
		    noevents = 1  
		}

		parmMatcher = resourceUrl =~ '^http://www.coolsport\\.tv.*?refresh=([0-9]+)'
		parmMatch = resourceUrl ==~ '^http://www.coolsport\\.tv.*?refresh=[0-9]+.*?'
		if (parmMatch){
			Refreshi = parmMatcher[0][1].trim().toLong()
			long curTime=System.currentTimeMillis()/60000
			Refresha = (System.currentTimeMillis()/60000) + Refreshi + 5
		}
	
		parmMatcher = resourceUrl =~ '^http://www.coolsport.tv.*?sched=1'
		parmMatch = resourceUrl ==~ '^http://www.coolsport.tv.*?sched=1.*?'
		if (parmMatch){
			sched = 1
		}
	
		parmMatcher = resourceUrl =~ '^http://www.coolsport.tv.*?time=([0-9]+)'
		parmMatch = resourceUrl ==~ '^http://www.coolsport.tv.*?time=[0-9]+.*?'
		if (parmMatch){
			time = parmMatcher[0][1].trim().toShort()
			if (time < 0 || time > 24) time = 0
		}
	
		def resource_text = openURL(new URL("http://www.coolsport.tv/schedule.html"),
			"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1")
			
		

		
		//def SCHEDULE_LIST_EXTRACTOR = '\\*(.*?)(\\d+)[:\\.,](\\d\\d)(.[mM])-(\\d+)[://.,](\\d\\d)(.[mM]).*?Stream.(.*?)<p>'
		def SCHEDULE_LIST_EXTRACTOR = '\\*(.*?)(\\d+)[:\\.,](\\d\\d)(.[mM])-(\\d+)[://.,](\\d\\d)(.[mM]).*?Stream.(.*?)<'

		def slm = resource_text =~ SCHEDULE_LIST_EXTRACTOR
		
	
		def CHANNEL_LIST_EXTRACTOR = '(?s)<a href="(.*?)">(.*?)<'
    	def channel_list_matcher = resource_text =~ CHANNEL_LIST_EXTRACTOR
        
		def channel_count = channel_list_matcher.count
        
		for (channel_number in 0..<channel_count) {
		
			if (ETimer() > 86000){
				log ("Time Limit of 90 Seconds Reached") 
				println "\r\nTime Limit of 90 Seconds Reached\r\n"
				break
			}

			srcUrl = channel_list_matcher[channel_number][1]
            
			if (srcUrl.contains("#") || srcUrl.contains("schedule") || srcUrl.contains("twitter") || srcUrl.contains("contact")) {
				continue;
			}
                        
			channel_image = "https://sites.google.com/site/serviiorss/" + channel_list_matcher[channel_number][2] + ".png" 
			
            channel_image = channel_image.toLowerCase().replaceAll(" ","")
			if(channel_image.contains("golf")) channel_image = "https://sites.google.com/site/serviiorss/golf.png"
			if(channel_image.contains("nfl")) channel_image = "https://sites.google.com/site/serviiorss/nfl.png"
			if(channel_image.contains("nba")) channel_image = "https://sites.google.com/site/serviiorss/nba.png"
			if(channel_image.contains("nhl")) channel_image = "https://sites.google.com/site/serviiorss/nhl.png"
			if(channel_image.contains("espn")) channel_image = "https://sites.google.com/site/serviiorss/espn.png"
			if(channel_image.contains("f1")) channel_image = "https://sites.google.com/site/serviiorss/f1.png"
			if(channel_image.contains("chelsea")) channel_image = "https://sites.google.com/site/serviiorss/chelsea.png"

			def channel_title = srcUrl
			channel_title = channel_title.replaceAll("http://www.coolsport.tv/", "")
			channel_title = channel_title.replaceAll(".html", "")
			channel_title = channel_title.replaceAll("stream", "")
			channel_title = channel_title.replaceAll("tv", "")
			channel_title = channel_title.trim()
			if (channel_title == "golf") channel_title = "GOLF Channel"
			if (channel_title == "nfl") channel_title = "NFL Network"
			if (channel_title == "nba") channel_title = "NBA Network"
			if (channel_title == "nhll") channel_title = "NHL Network"
			if (channel_title == "espnusa") channel_title = "ESPN USA"
			if (channel_title == "f1") channel_title = "F1 Channel"
			if (channel_title == "chelsea") channel_title = "Chelsea Channel"
			if (channel_title == "skynews2") channel_title = "Sky Sports News"
			
			short schedules = 0
			channel_title_text = ""

		  	for (snum in 0..<slm.count){
				
				def event = slm[snum][1].replaceFirst("</font>","")
				

 
				if (slm[snum][8] == channel_title){
					short shour = slm[snum][2].toShort()
					if (shour == 12 && (slm[snum][4] == "am" || slm[snum][4] == "AM")) shour = 0
					else
					if (shour != 12 && (slm[snum][4] == "pm" || slm[snum][4] == "PM")) shour = shour + 12 
					shour = shour + time
					if (shour > 23) shour = shour - 24

					short ehour = slm[snum][5].toShort()
					if (ehour == 12 && (slm[snum][7] == "am" || slm[snum][7] == "AM")) ehour = 0
					else
					if (ehour == 12 && (slm[snum][7] == "pm" || slm[snum][7] == "PM") && (slm[snum][4] == "pm" || slm[snum][4] == "PM") ) ehour = 0
					else
					if (ehour != 12 && (slm[snum][7] == "pm" || slm[snum][7] == "PM")) ehour = ehour + 12 
					ehour = ehour + time
					if (ehour > 23) ehour = ehour - 24
					
					if(time == 0){
						channel_title_text = channel_title_text + "*" + shour + ":" + slm[snum][3] + "-" + ehour + ":" + slm[snum][6] + "GMT*" + event 
					}
					else {
						channel_title_text = channel_title_text + "*" + shour + ":" + slm[snum][3] + "-" + ehour + ":" + slm[snum][6] + "*" + event
					}
					
					schedules = schedules + 1
				}
				if (schedules == sched) break
			}
			
			if (channel_title_text == "" && srcUrl.contains("stream")) {
				if (noevents == 0) continue  
				channel_title_text = "*No Events Scheduled*"
			}
			
			channel_title_text = channel_title + channel_title_text.replaceAll("ENGLISH\\* ","")
			

			def itemkey = "Coolsport_" + channel_title_text
			WebResourceItem item = new WebResourceItem(title: channel_title_text, 
				additionalInfo: ['itemkey':itemkey, channelURL: srcUrl, 
				thumbnailUrl: channel_image, 'refresha': Refresha])
			
			item.additionalInfo.put('gen',"false")
			if(olditems && itemkey){
				for (int oij=olditems.size(); oij > 0; oij--){
					String olditem = olditems.getAt(oij-1).toString()
					if(olditem.contains(itemkey)){
						item.additionalInfo.put('oindx',oij-1)
						if (genurls) item.additionalInfo.put('gen',"true")
						break
					}
				}
			}

			items << item
			itemsAdded++
		}  

		def Refreshat
		if (Refreshi == 0){
			log ("Folder Refresh Set to Console Default")
			Refreshat = "Console Default time"
		}
		else{
			Refreshat = new Date(Refresha*60000).format("H:mm 'on' E M/dd/yyyy ").trim()
			log ("Folder Refresh Set to " + Refreshat )
		}
		
		if (itemsAdded == 0 || Refreshi != 0){
			srcUrl = "http://lastitem"
			if (itemsAdded == 0) channel_image = "https://sites.google.com/site/serviiorss/noevents.jpg"
			else channel_image = "https://sites.google.com/site/serviiorss/nomoreitems.jpg"
			
			channel_title_text = "Next Refresh at $Refreshat"
			if (itemsAdded == 0) log ("ADDED 'NO EVENTS' - $channel_title_text")
			else log ("ADDED 'NO MORE ITEMS' - $channel_title_text")
			WebResourceItem item = new WebResourceItem(title: channel_title_text, 
				additionalInfo: ['channelURL':srcUrl,'thumbnailUrl':channel_image ,'refresha':Refresha])

			item.additionalInfo.put('gen',"false")
			items << item
		}

		ETimer("Total $itemsAdded Items Found")
		
        return new WebResourceContainer(title: "Coolsport", items: items)
    }
    
    ContentURLContainer extractUrl(WebResourceItem item, PreferredQuality requestedQuality) {
    
		def srcUrl = item.additionalInfo.channelURL
		def thumbnailUrl = item.additionalInfo.thumbnailUrl
		def secCode = ""
		def rtmpUrl = ""
		def cacheKey 
		long Refresha = item.getAdditionalInfo()['refresha']
		Date expiryDate
		def expiresImmediately
		
		String gen = item.getAdditionalInfo()['gen']

		if(gen == "false"){
		
			if (srcUrl.contains("http://lastitem")){
				if (Refresha > 0) expiryDate = new Date(Refresha * 60000)
				rtmpUrl = "rtsp://a1709.l1856953708.c18569.g.lm.akamaistream.net:554/D/1709/18569/v00/reflector:53708"
				secCode = "abcdefghi"
				cacheKey = "http://lastitem_" + secCode
				expiresImmediately = false
			}
			else{
			
				log("Source Link: $srcUrl")
			
				if (!URLExists(srcUrl)) {
					log (srcUrl + " is DEADLINK")
					return null
				}
				
				def srcUrl_text = openURL( new URL(srcUrl),
					"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1")        

				
				if (channelOffline(srcUrl_text, '<h1 class="center">This channel is offline\\.</h1>')
					|| channelOffline(srcUrl_text, '<h4 class=.*?THIS CHANNEL IS CURRENTLY OFFLINE</h4>')
					) {
					log (srcUrl + " is OFFLINE")
					return null
				}
				
				if (streamNotSupported(srcUrl_text, '<media url="rtmfp:////.*?/>')
					|| streamNotSupported(srcUrl_text, '<script.*?src=".*?player\\.ooyala\\.com.*?"></script>')                    
					) {
					log (srcUrl + " is NOTSUPPORTED")
					return null
				}
				
				
				def linkMatcher = srcUrl_text =~ '(?s)<div id="I53_html".*?src="(.*?)"'
				def linkMatched = srcUrl_text =~ '(?s).*?<div id="I53_html".*?src="(.*?)".*?'

				if (!linkMatched){
					log("No src= in " + srcUrl)
					return
				}
				
				srcUrl = linkMatcher[0][1]

				log("Source Link 2: $srcUrl")
				
				if (!URLExists(srcUrl)) {
					log (srcUrl + " is DEADLINK")
					return null
				}

				srcUrl_text = openURL( new URL(srcUrl),
				"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1") 
				
				if (srcUrl_text == "") {
					log (srcUrl + " NOT FOUND")
					return null
				}            

 
				def idMatcher = srcUrl_text =~ '(?s)<script type=["\']text/javascript["\'].*?src=["\']http://www.hdmytv.com/channel.php' 
				def idMatched = srcUrl_text ==~ '(?s).*?<script type=["\']text/javascript["\'].*?src=["\']http://www.hdmytv.com/channel.php.*?' 
				if (idMatched){
					log("Unsupported source www.hdmytv.com")
					//println srcUrl_text
					return
				}				

				idMatcher = srcUrl_text =~ '(?s)<script type=["\']text/javascript["\']>.*?src=["\']http://sawlive.tv/embed/(.*?)["\']' 
				idMatched = srcUrl_text ==~ '(?s).*?<script type=["\']text/javascript["\']>.*?src=["\']http://sawlive.tv/embed/.*?["\'].*?' 
				if (idMatched){
					srcUrl = "http://sawlive.tv/embed/" + idMatcher[0][1] 
					log("Source Link 3: $srcUrl")
					srcUrl_text = openURL( new URL(srcUrl),
						"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1") 
					def encodeMatcher = srcUrl_text =~ "(?s)unescape\\('(.*?)'"
					def encodeMatched = srcUrl_text ==~ "(?s).*?unescape\\('.*?'.*?"
					if(!encodeMatched){
						log("No encode in " + srcUrl)
						return
					}
					def decoded = URLDecoder.decode(encodeMatcher[0][1])
					
					def srcMatcher = decoded =~ '(?s)src="(.*?)$'
					def srcMatch = decoded ==~ '(?s).*?src=".*?$'
					if (!srcMatch){
						log("No src= in decoded " + srcUrl)
						return
					}
					def refererUrl = srcUrl
					srcUrl = srcMatcher[0][1]
					log("Source Link 4: $srcUrl")

					//srcUrl_text = openURL( new URL(srcUrl),
					//"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1") 
					//srcUrl_text = OpenProtURL(srcUrl,refererUrl)	

					return
				}
				else{
					idMatcher = srcUrl_text =~ '(?s)<script type=["\']text/javascript["\']>\\s?id=["\'](.*?)["\'];.*?src=["\'](.*?)["\']' 
					idMatched = srcUrl_text ==~ '(?s).*?<script type=["\']text/javascript["\']>\\s?id=["\'].*?["\'];.*?src=["\'].*?["\'].*?' 
					if (!idMatched){
						idMatcher = srcUrl_text =~ '(?s)<script type=["\']text/javascript["\']>\\s?fid=["\'](.*?)["\'];.*?src=["\'](.*?)["\']'
						idMatched = srcUrl_text ==~ '(?s).*?<script type=["\']text/javascript["\']>\\s?fid=["\'].*?["\'];.*?src=["\'].*?["\'].*?'
						if (!idMatched){
							idMatcher = srcUrl_text =~ '(?s)<script type=["\']text/javascript["\']>\\s?channel=["\'](.*?)["\'];.*?src=["\'](.*?)["\']'
							idMatched = srcUrl_text ==~ '(?s).*?<script type=["\']text/javascript["\']>\\s?channel=["\'].*?["\'];.*?src=["\'].*?["\'].*?'
							if (!idMatched){
								log("No playpath or src= in " + srcUrl)
								println srcUrl_text
								return
							}
						}
					}
					
					secCode = idMatcher[0][1]
					
					if (idMatcher[0][1] =="test") return
					
					if(idMatcher[0][2].contains("www.yycast.com")) {
						rtmpUrl = "rtmp://212.7.212.37:1935/live" + " playpath=" + secCode + " pageUrl=http://www.yycast.com/embed.php?fileid=" + idMatcher[0][1] + " swfUrl=http://cdn.yycast.com/player/player.swf live=1" 
					}
					else if(idMatcher[0][2].contains("yukons.net")) {
						rtmpUrl = "rtmp://198.144.153.139:1935/kuyo playpath=" + secCode + " pageUrl=http://www.yukons.net swfurl=http://yukons.net/yukplay.swf live=1"
					}
					else if(idMatcher[0][2].contains("reyhq.com")) {
 						rtmpUrl = "rtmp://89.248.174.117/live playpath=" + secCode + " swfUrl=http://www.reyhq.com/player/player-licensed.swf pageurl=http://www.reyhq.com live=1"
 					}
					else if(idMatcher[0][2].contains("up4free.com")) {
						secCode = secCode.replaceAll("channel","") 
						rtmpUrl = "rtmp://85.12.5.84:1935/liverepeater playpath=" + secCode + " swfurl=http://cdn.goodcast.org/player.swf pageurl=http://cdn.goodcast.org live=1"
 					}
					else if (idMatcher[0][2].contains("aka.castvideo.info/player.js") || idMatcher[0][2].contains("sportodin.com/player.js")) {
						//build rtmp link for src="http://aka.castvideo.info/player.js" or src='http://sportodin.com/player.js'></script>
						rtmpUrl = "rtmp://37.220.34.59:1935/liverepeater/_definst_/" + idMatcher[0][1] + " live=1"
					}
					else if(idMatcher[0][2].contains("coolsport.tv/livegame.js")) {
						srcUrl = "http://embeds.coolsport.tv/livegame.php?id=" + idMatcher[0][1] + "&width=640&height=460"

						log("Source Link 3: $srcUrl")
						
						srcUrl_text = openURL(new URL(srcUrl),
							"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1") 
						
						idMatcher = srcUrl_text =~ '(?s)<script type=["\']text/javascript["\']>id=["\'](.*?)["\'];.*?src=["\'](.*?)["\']'
						idMatched = srcUrl_text ==~ '(?s).*?<script type=["\']text/javascript["\']>id=["\'].*?["\'];.*?src=["\'].*?["\'].*?'
						if (!idMatched){
							log("No playpath or src= in " + srcUrl)
							return
						}


						secCode = idMatcher[0][1]

						//build rtmp link for default src="http://embeds.coolsport.tv/livegame.js"
						rtmpUrl = "rtmp://37.220.34.59:1935/liverepeater/ playpath=" + secCode + " pageUrl=http://stream4.tv/player.php swfurl=http://cdn.stream4.tv/player.swf live=1"
					}
					else if(idMatcher[0][2].contains("coolsport.tv/livegamecdn.js")) {
						srcUrl = "http://embeds.coolsport.tv/livegamecdn.php?id=" + idMatcher[0][1] + "&width=640&height=460"

						log("Source Link 3: $srcUrl")
						
						srcUrl_text = openURL(new URL(srcUrl),
							"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1") 
						
						idMatcher = srcUrl_text =~ '(?s)<script type=["\']text/javascript["\']>id=["\'](.*?)["\'];.*?src=["\'](.*?)["\']'
						idMatched = srcUrl_text ==~ '(?s).*?<script type=["\']text/javascript["\']>id=["\'].*?["\'];.*?src=["\'].*?["\'].*?'
						if (!idMatched){
							log("No playpath or src= in " + srcUrl)
							return
						}


						secCode = idMatcher[0][1]

						//build rtmp link for default src="http://embeds.coolsport.tv/livegame.js"
						rtmpUrl = "rtmp://37.220.34.59:1935/liverepeater/ playpath=" + secCode + " pageUrl=http://stream4.tv/player.php swfurl=http://cdn.stream4.tv/player.swf live=1"
					}
					else if(idMatcher[0][2].contains("coolsport.tv/livegame")) {
						def refererUrl = srcUrl
						srcUrl = "http://embeds.coolsport.tv/livegame2.php?id=" + idMatcher[0][1] + "&width=640&height=460"

						log("Source Link 3: $srcUrl")
						
						//srcUrl_text = openURL( new URL(srcUrl),
						//	"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1") 
						srcUrl_text = OpenProtURL(srcUrl,refererUrl)
						//def ua = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1" 
						//srcUrl_text = new GZIPInputStream (new URL(srcUrl).newInputStream(requestProperties:['Accept-Encoding': 'gzip,deflate', 'Referer': refererUrl, 'User-Agent': ua])).text			

						idMatcher = srcUrl_text =~ '(?s)<script type=["\']text/javascript["\']>id=["\'](.*?)["\'];.*?src=["\'](.*?)["\']'
						idMatched = srcUrl_text ==~ '(?s).*?<script type=["\']text/javascript["\']>id=["\'].*?["\'];.*?src=["\'].*?["\'].*?'
						if (!idMatched){
							log("No playpath or src= in " + srcUrl)
							println srcUrl_text
							return
						}


						secCode = idMatcher[0][1]
						
						//build rtmp link for default src="http://stream4.tv/player2.js"
						rtmpUrl = "rtmp://rtmp.stream4.tv:1935/liverepeater/ playpath=" + secCode + " pageUrl=http://stream4.tv/player2.php swfurl=http://cdn.stream4.tv/player2.swf live=1"
					}
					else{	
						log("Unsupported source " + idMatcher[0][2] + " " + secCode)
						//println srcUrl_text
						return
					}				
				}			

				log("Extracted url: " + srcUrl)
		
			
				cacheKey = "Coolsport" + '_' + secCode
			
				expiresImmediately = true

			}
	
			item.additionalInfo.put('XcontentUrl',rtmpUrl)
			item.additionalInfo.put('XthumbnailUrl',thumbnailUrl)
			item.additionalInfo.put('XexpiresOn',expiryDate)
			item.additionalInfo.put('XexpiresImmediately',expiresImmediately)
			item.additionalInfo.put('XcacheKey',cacheKey)
			def oindx = item.getAdditionalInfo()['oindx']
			if(oindx){
				newitems[oindx] = item
			}
			else {
				oindx = newitems.size()
				item.additionalInfo.put('oindx',oindx)
				newitems << item
			}
		}//END of non gen EXTRACT

		else{   //START OF gen GENERATE
			println "\r\ngenerate url"
			log ("Generated url: " + srcUrl)

			item.additionalInfo.put('gen',"false")
			def oindx = item.getAdditionalInfo()['oindx']
			rtmpUrl = olditems.getAt(oindx).getAdditionalInfo()['XcontentUrl']
			thumbnailUrl = olditems.getAt(oindx).getAdditionalInfo()['XthumbnailUrl']
			expiryDate = olditems.getAt(oindx).getAdditionalInfo()['XexpiresOn']
			expiresImmediately = olditems.getAt(oindx).getAdditionalInfo()['XexpiresImmediately']
			cacheKey = olditems.getAt(oindx).getAdditionalInfo()['XcacheKey']
		}
	
		return new ContentURLContainer(fileType: MediaFileType.VIDEO, contentUrl: rtmpUrl, thumbnailUrl: thumbnailUrl, 
			cacheKey: cacheKey, expiresOn: expiryDate, expiresImmediately: expiresImmediately, live: true)
    }
    
    static void main(args) {
        
        Coolsport extractor = new Coolsport()
        
        WebResourceContainer container = extractor.extractItems( new URL("http://www.coolsport.tv?refresh=120&time=19&sched=2&noevents=1"), -1)
		
        container.getItems().each {
            ContentURLContainer result = extractor.extractUrl(it, PreferredQuality.MEDIUM)
            println result
        }
		
		 WebResourceContainer container2 = extractor.extractItems( new URL("http://www.coolsport.tv?refresh=120&time=19&sched=1"), -1)
		
        container2.getItems().each {
            ContentURLContainer result2 = extractor.extractUrl(it, PreferredQuality.MEDIUM)
            println result2
        }

	}
}
