# Path: lib/pirateplay/lib/rerequest.py
# class TemplateRequest:
# 	def __init__(self, re,
# 				encode_vars = lambda x: x, decode_content = lambda c, v: c,
# 				handlerchain = None):
# 		self.re = re
# 		self.encode_vars = encode_vars
# 		self.decode_content = decode_content
# 		self.handlerchain = handlerchain
# 	
# 	def create_vars(self, content, cumulated_vars):
# 		content = self.decode_content(content, cumulated_vars)
# 		
# 		#Make sure req_data and req_headers are empty
# 		if 'req_data' in cumulated_vars:
# 			del cumulated_vars['req_data']
# 		if 'req_headers' in cumulated_vars:
# 			del cumulated_vars['req_headers']
# 		
# 		for match in re.finditer(self.re, content, re.DOTALL):
# 			d = dict(cumulated_vars, **match.groupdict())
# 			d.update(self.encode_vars(d))
# 			yield d
# 	
# 	def create_req(self, cumulated_vars):
# 		url = cumulated_vars['req_url']
# 		if not url.startswith('http'):
# 			url = 'http://' + url
# 		req = urllib2.Request(url)
# 		
# 		if 'req_data' in cumulated_vars:
# 			debug_print('Adding post data to request: ' + cumulated_vars['req_data'])
# 			req.add_data(cumulated_vars['req_data'])
# 		
# 		for header, value in cumulated_vars.get('req_headers', {}).items():
# 			debug_print('Adding header to request: %s = %s' % (header, value))
# 			req.add_header(header, value)
# 		return req
# 	
# 	def create_content(self, req):
# 		debug_print('Opening URL: ' + req.get_full_url())
# 		try:
# 			try:
# 				f = urllib2.build_opener(self.handlerchain).open(req)
# 			except TypeError:
# 				f = urllib2.urlopen(req)
# 			
# 			content = f.read()
# 			f.close()
# 		except (urllib2.HTTPError, urllib2.URLError):
# 			content = ''
# 		
# 		return content
# 	
# 	def to_dict(self):
# 		return { 'test': self.re }


from ..rerequest import TemplateRequest

def init_req(domain = 'tv4play', protocol = 'http://', query = ''):
	return TemplateRequest(
				re = r'^(%s)?(www\.)?%s\.se/.*(videoid|video_id|vid)=(?P<id>\d+).*' % (protocol, domain),
				encode_vars = lambda v: { 'req_url': ('http://premium.tv4play.se/api/web/asset/%(id)s/play' + query)  % v } )

rtmp = { 'title': 'TV4-play', 'url': 'http://tv4play.se/', 'feed_url': 'http://www.tv4play.se/rss/sport/ekwall_vs_lundh',
		'items': [init_req(),
				TemplateRequest(
					re = r'(<playbackStatus>(?P<status>\w+).*?)?<bitrate>(?P<bitrate>[0-9]+)</bitrate>.*?(?P<base>rtmpe?://[^<]+).*?(?P<url>mp4:/[^<]+)(?=.*?(?P<subtitles>http://((anytime)|(prima))\.tv4(play)?\.se/multimedia/vman/smiroot/[^<]+))?',
					encode_vars = lambda v: { 'final_url': '%(base)s playpath=%(url)s swfVfy=1 swfUrl=http://www.tv4play.se/flash/tv4playflashlets.swf' % v,
											'quality': '%(bitrate)s kbps' % v,
											'suffix-hint': 'flv' } )] }

hls = { 'items': [init_req(protocol='(hls\+?)?http://', query='?protocol=hls'),
						TemplateRequest(
							re = r'<bitrate>(?P<bitrate>[0-9]+)</bitrate>.*?<url>(?P<req_url>(?P<base>http://[^<]+)master\.m3u8)(?=.*?(?P<subtitles>http://((anytime)|(prima))\.tv4(play)?\.se/multimedia/vman/smiroot/[^<]+))?' ),
							#encode_vars = lambda v: { 'quality': '%(bitrate)s kbps' % v,
							#						'suffix-hint': 'mp4' } )] }#,
						TemplateRequest(
							re = r'BANDWIDTH=(?P<bitrate>\d+).*?RESOLUTION=(?P<resolution>\d+x\d+).*?(?P<url>index[^\n]+)',
							encode_vars = lambda v: { 'final_url': '%(base)s/%(url)s' % v,
													'quality': '%s kbps' % (str(int(v['bitrate'])/1000)),
													'suffix-hint': 'mp4' })] }

hds = { 'items': [init_req(),

# Path: lib/pirateplay/lib/rerequest.py
# class TemplateRequest:
# 	def __init__(self, re,
# 				encode_vars = lambda x: x, decode_content = lambda c, v: c,
# 				handlerchain = None):
# 		self.re = re
# 		self.encode_vars = encode_vars
# 		self.decode_content = decode_content
# 		self.handlerchain = handlerchain
# 	
# 	def create_vars(self, content, cumulated_vars):
# 		content = self.decode_content(content, cumulated_vars)
# 		
# 		#Make sure req_data and req_headers are empty
# 		if 'req_data' in cumulated_vars:
# 			del cumulated_vars['req_data']
# 		if 'req_headers' in cumulated_vars:
# 			del cumulated_vars['req_headers']
# 		
# 		for match in re.finditer(self.re, content, re.DOTALL):
# 			d = dict(cumulated_vars, **match.groupdict())
# 			d.update(self.encode_vars(d))
# 			yield d
# 	
# 	def create_req(self, cumulated_vars):
# 		url = cumulated_vars['req_url']
# 		if not url.startswith('http'):
# 			url = 'http://' + url
# 		req = urllib2.Request(url)
# 		
# 		if 'req_data' in cumulated_vars:
# 			debug_print('Adding post data to request: ' + cumulated_vars['req_data'])
# 			req.add_data(cumulated_vars['req_data'])
# 		
# 		for header, value in cumulated_vars.get('req_headers', {}).items():
# 			debug_print('Adding header to request: %s = %s' % (header, value))
# 			req.add_header(header, value)
# 		return req
# 	
# 	def create_content(self, req):
# 		debug_print('Opening URL: ' + req.get_full_url())
# 		try:
# 			try:
# 				f = urllib2.build_opener(self.handlerchain).open(req)
# 			except TypeError:
# 				f = urllib2.urlopen(req)
# 			
# 			content = f.read()
# 			f.close()
# 		except (urllib2.HTTPError, urllib2.URLError):
# 			content = ''
# 		
# 		return content
# 	
# 	def to_dict(self):
# 		return { 'test': self.re }


# Path: lib/pirateplay/lib/services/tv4.py
from ..rerequest import TemplateRequest


def init_req(domain = 'tv4play', protocol = 'http://', query = ''):
	return TemplateRequest(
				re = r'^(%s)?(www\.)?%s\.se/.*(videoid|video_id|vid)=(?P<id>\d+).*' % (protocol, domain),
				encode_vars = lambda v: { 'req_url': ('http://premium.tv4play.se/api/web/asset/%(id)s/play' + query)  % v } )

rtmp = { 'title': 'TV4-play', 'url': 'http://tv4play.se/', 'feed_url': 'http://www.tv4play.se/rss/sport/ekwall_vs_lundh',
		'items': [init_req(),
				TemplateRequest(
					re = r'(<playbackStatus>(?P<status>\w+).*?)?<bitrate>(?P<bitrate>[0-9]+)</bitrate>.*?(?P<base>rtmpe?://[^<]+).*?(?P<url>mp4:/[^<]+)(?=.*?(?P<subtitles>http://((anytime)|(prima))\.tv4(play)?\.se/multimedia/vman/smiroot/[^<]+))?',
					encode_vars = lambda v: { 'final_url': '%(base)s playpath=%(url)s swfVfy=1 swfUrl=http://www.tv4play.se/flash/tv4playflashlets.swf' % v,
											'quality': '%(bitrate)s kbps' % v,
											'suffix-hint': 'flv' } )] }

hls = { 'items': [init_req(protocol='(hls\+?)?http://', query='?protocol=hls'),
						TemplateRequest(
							re = r'<bitrate>(?P<bitrate>[0-9]+)</bitrate>.*?<url>(?P<req_url>(?P<base>http://[^<]+)master\.m3u8)(?=.*?(?P<subtitles>http://((anytime)|(prima))\.tv4(play)?\.se/multimedia/vman/smiroot/[^<]+))?' ),
							#encode_vars = lambda v: { 'quality': '%(bitrate)s kbps' % v,
							#						'suffix-hint': 'mp4' } )] }#,
						TemplateRequest(
							re = r'BANDWIDTH=(?P<bitrate>\d+).*?RESOLUTION=(?P<resolution>\d+x\d+).*?(?P<url>index[^\n]+)',
							encode_vars = lambda v: { 'final_url': '%(base)s/%(url)s' % v,
													'quality': '%s kbps' % (str(int(v['bitrate'])/1000)),
													'suffix-hint': 'mp4' })] }

hds = { 'items': [init_req(),

				TemplateRequest(