#~DamnVid-module:canalplus

class DamnModule_CanalPlus(DamnVideoModule):
	def __init__(self,uri):
		DamnVideoModule.__init__(self,uri)
		self.name='canalplus'
		self.regex={
			'url':re.compile('canalplus\.fr/.*pid-?(\d+)',re.IGNORECASE),
			'title':(re.compile('name="titre_video" value="([^"]+)"',re.IGNORECASE),re.compile('^(?:(?!description).)*class="[^"<>]*txt-(?:noir|blanc)\d*[^<>]*>\s*([^<>]+?)\s*</div>',re.IGNORECASE)),
			'ticket':(re.compile('aVideos\[[\s\w]+\]\[\s*[\'"]CONTENT_ID[\'"]\s*\]\s*=\s*[\'"]?(\d+)[\'"]?',re.IGNORECASE),re.compile('bandwidth="([^"]+)"><!\[CDATA\[\s*(.*?)\s*\]\]></\w+>',re.IGNORECASE),re.compile('^https?://.*?canalplus\.fr/.+',re.IGNORECASE))
		}
		self.valid=self.regex['url'].search(uri)
		self.canalplusvideos=[]
		self.gottitle=False
		if self.valid:
			self.id='c+:'+self.valid.group(1)
			self.link='http://www.canalplus.fr/pid'+self.valid.group(1)+'.html'
	def canalplus_video(self,num=None,vid=None,title=None,url=None):
		if type(num) is type(0):
			if len(self.canalplusvideos)<=num:
				num=None
		if num is None:
			self.canalplusvideos.append({
				'num':len(self.canalplusvideos),
				'vid':vid,
				'title':title,
				'url':url
			})
			return self.canalplusvideos[-1]
		if vid is not None:
			self.canalplusvideos[num]['vid']=vid
		if title is not None:
			self.canalplusvideos[num]['title']=title
		if url is not None:
			self.canalplusvideos[num]['url']=url
		return self.canalplusvideos[num]
	def getTitle(self):
		self.gottitle=True
		if self.title is not None:
			return self.title
		html=DamnURLOpen(self.link)
		titleindex=0
		vidindex=0
		for i in html:
			res1,res2,res3=self.regex['title'][0].search(i),self.regex['title'][1].search(i),self.regex['ticket'][0].search(i)
			if res1:
				self.title=DamnHtmlEntities(res1.group(1)).title()
			if res2:
				self.canalplus_video(titleindex,title=DamnHtmlEntities(res2.group(1)).replace('/','-'))
				titleindex+=1
			if res3:
				self.canalplus_video(vidindex,vid=DamnHtmlEntities(res3.group(1)))
				vidindex+=1
		return DamnVideoModule.getTitle(self)
	def canalplus_downloadVid(self,vid):
		vid=vid.split('-')
		html=DamnURLOpen('http://www.canalplus.fr/flash/xml/module/embed-video-player/embed-video-player.php',urllib.urlencode({
			'pid':vid[0],
			'content_id':vid[1]
		}))
		urls={}
		bandwidths=[]
		for i in html:
			res=self.regex['ticket'][1].search(i)
			if res:
				urls[res.group(1)]=res.group(2)
				bandwidths.append(int(res.group(1)))
		bandwidths.sort()
		bandwidths.reverse()
		final=[]
		for i in bandwidths:
			if self.regex['ticket'][2].match(urls[str(i)]):
				final.append(urls[str(i)])
		return final
	def getDownloadGetter(self):
		return self.canalplusdownloadgetter
	def addVid(self,parent):
		if not self.gottitle:
			self.getTitle()
		maxv=0
		for i in self.canalplusvideos:
			if i['vid'] is not None and i['title'] is not None:
				maxv+=1
		roottitle=self.title
		rootid=self.id
		for i in range(min((int(self.pref('maxvids')),maxv))):
			self.title=roottitle+' - '+self.canalplusvideos[i]['title']
			self.id=rootid+'-'+str(self.canalplusvideos[i]['vid'])
			self.canalplusdownloadgetter=DamnCurry(self.canalplus_downloadVid,self.id[3:])
			DamnVideoModule.addVid(self,parent)
		self.title=roottitle
		self.id=rootid
DamnRegisterModule({
	'name':'canalplus',
	'title':'Canal+',
	'type':'video',
	'version':'1.1',
	'author':{
		'name':'Etienne Perot',
		'email':'admin@biringa.com',
		'url':'http://biringa.com/'
	},
	'icon':{
		'small':'canalplus.png',
		'large':'canalplus-large.png',
	},
	'about':{
		'short':'DamnVid module for Canal+.',
		'long':"""This is a video plugin for DamnVid that adds Canal+ video downloading capabilities.
Only the last few video(s) from a given channel are downloaded.
You can customize the number of downloaded videos below.""",
		'url':'http://code.google.com/p/damnvid/wiki/Modules'
	},
#    'sites':[
#        {
#            'title':'Canal+',
#            'icon':'canalplus.png',
#            'url':'http://www.canalplus.fr/'
#        }
#    ],
	'class':DamnModule_CanalPlus,
	'preferences':{
		'profile':{
			'name':'Default profile',
			'type':DV.preference_type_profile,
			'kind':'profile',
			'strict':True,
			'default':3
		},
		'outdir':{
			'name':'Output directory',
			'type':DV.preference_type_misc,
			'kind':'dir',
			'strict':True,
			'default':'?DAMNVID_MY_VIDEOS?/DamnVid/CanalPlus/'
		},
		'maxvids':{
			'name':'Number of videos to download',
			'type':DV.preference_type_misc,
			'kind':'int:1-8',
			'strict':True,
			'default':1
		}
	},
	'register':{
		'listicons':{
			'canalplus':'canalplus.png'
		}
	}
})
