import re, requests, time, xbmcgui, socket, xbmc, os
import xbmcaddon
import jsunpack

addon = xbmcaddon.Addon(id='plugin.video.streamoase')
home = addon.getAddonInfo('path').decode('utf-8')


class get_stream_link:

	def __init__(self):
		self._callback = None
		
		
	def getUrl(self, url):
		response=requests.get(url)
		html=response.content
		response.close()
		return html
		
	def postUrl(self,url,data):
	    response=requests.post(url,data)
	    html=response.content
	    return html
	    
	def getjsonUrl(self,url):
	    response=requests.get(url)
	    html=response.content
	    html=html.json()
	        
	    	
	
	def waitmsg(self, sec, msg):
		dialog = xbmcgui.DialogProgress()
		dialog.create('Resolving', '%s Link.. Wait %s sec.' % (msg, sec))
		dialog.update(0)
		
		c = 100 / int(sec)
		i = 1
		p = 0
		
		while i < int(sec):
			p += int(c)
			time.sleep(1)
			dialog.update(int(p))
			i += 1
			
		dialog.close()
		
	def check_link(self, link, gotlink):
		print "Stream -----> check link:", link
		self._callback = gotlink
		flink = False
		
		if re.match(".*?http://180upload.com/embed-.*?.html", link, re.S):
			flink = True
			self.upload(link)
			
		elif re.match(".*?http://vidplay.net/embed-.*?.html", link, re.S):
			flink = True
			self.vidplay(link)
			
		elif re.match(".*?http://www.mightyupload.*?.html", link, re.S):
			#link = link.replace('file','embed')
			flink = True
			self.mightyupload(link)
			
		elif re.match(".*?http://www.divxpress.com/embed-.*?.html", link, re.S):
			flink = True
			self.divxpress(link)

		
		elif re.match('.*?http://www.uploadnetwork.eu/embed-.*?html', link, re.S):
			flink = True
			self.uploadnetwork(link)
			
		elif re.match('.*?http://veetle.com/index.php/widget/index/.*?false', link, re.S):
			flink = True
			self.veetle(link)
				
			
		elif flink == False:
			self._callback("Not Supported")

	def upload(self, url):	
		puzzle_img = os.path.join(home, "180_puzzle.png")
		html=self.getUrl(url)
		match=re.search('(http://180upload.com/.*?)"',html)
		if re.search('>File Not Found<',html):
			print 'file wurde entfernt'
		data = {}
		r = re.findall(r'type="hidden" name="(.+?)" value="(.+?)"', html)
		if r:
			for name, value in r:
				data[name] = value
			data['referer'] = url 
		solvemedia=re.search('<iframe src="(http://api.solvemedia.com.+?)"', html)
		if solvemedia:
			html = requests.get(solvemedia.group(1)).content
			hugekey=re.search('id="adcopy_challenge" value="(.+?)">', html).group(1)
			open(puzzle_img, 'wb').write(requests.get("http://api.solvemedia.com%s" % re.search('<img src="(.+?)"', html).group(1)).content)
			img = xbmcgui.ControlImage(450,15,400,130, puzzle_img)
			wdlg = xbmcgui.WindowDialog()
			wdlg.addControl(img)
			wdlg.show()
			xbmc.sleep(2000)
			kb = xbmc.Keyboard('', 'Type the letters in the image', False)
			kb.doModal()
			capcode = kb.getText()
			if (kb.isConfirmed()):
				userInput = kb.getText()
				if userInput != '':
					solution = kb.getText()
				elif userInput == '':
					Notify('big', 'No text entered', 'You must enter text in the image to access video', '')
				else:
					return False
			wdlg.close()
			if solution:
				data.update({'adcopy_challenge': hugekey,'adcopy_response': solution})
				html=self.postUrl(url,data)	
				stream_url = re.search('id="lnk_download" href="([^"]+)', html)
				if stream_url:
					self._callback(stream_url.group(1))
				else:
					self._callback("False")
			else:
				self._callback("False")
					
	def vidplay(self,url):
		puzzle_img = os.path.join(home, "vidplay_puzzle.png")
		html=self.getUrl(url)
		if re.search('>File Not Found<',html):
			print'file wurde entfernt'
		data = {}
		r = re.findall(r'type="hidden" name="(.*?)" value="(.+?)".', html)
		if r:
			op=r[0][1]
			file_code=r[1][1]
			embed_width=r[2][1]
			embed_height=r[3][1]
			data={'op':op,'file_code':file_code,'embed_width':embed_width,'embed_height':embed_height}
		else:
			raise Exception('Unable to resolve vidplay Link')
		solvemedia = re.search('<iframe src="(http://api.solvemedia.com.+?)"', html)
		if solvemedia:
			html = requests.get(solvemedia.group(1)).content
			hugekey=re.search('id="adcopy_challenge" value="(.+?)">', html).group(1)
			open(puzzle_img, 'wb').write(requests.get("http://api.solvemedia.com%s" % re.search('<img src="(.+?)"', html).group(1)).content)
			img = xbmcgui.ControlImage(450,15,400,130, puzzle_img)
			wdlg = xbmcgui.WindowDialog()
			wdlg.addControl(img)
			wdlg.show()
			xbmc.sleep(2000)
			kb = xbmc.Keyboard('', 'Type the letters in the image', False)
			kb.doModal()
			capcode = kb.getText()
			if (kb.isConfirmed()):
				userInput = kb.getText()
				if userInput != '':
					solution = kb.getText()
				elif userInput == '':
					Notify('big', 'No text entered', 'You must enter text in the image to access video', '')
					return False
			else:
				return False
			wdlg.close()
			if solution:
				data.update({'adcopy_challenge': hugekey,'adcopy_response': solution})
				html=self.postUrl(url,data)
				stream_url = re.search("file: '([^']+)'", html)
				if stream_url:
					self._callback(stream_url.group(1))
				else:
					self._callback("False")
			else:
				self._callback("False")	
				
	def mightyupload(self,url):
		if not 'http' in url:
			url='http://'+url
		html=self.getUrl(url)
		if 'File was deleted' in html:
			xbmc.executebuiltin("XBMC.Notification(File wurde entfernt,4000)")
		else:
			stream_url=re.search('file:.*?\'(.*?)\',',html,re.S)
			if stream_url:
				self._callback(stream_url.group(1))
			else:
				self._callback("False")
				
	def divxpress(self,url):
		data = {}
		html=self.getUrl(url)
		match=re.findall('input type="hidden" name="(.*?)" value="(.*?)".',html,re.S)
		if match:
			for name, value in match:
				data[name] = value
		html=self.postUrl(url,data)
		sPattern='<div id="player_code">.*?<script type=(?:"|\')text/javascript(?:"|\')>'
		sPattern +='(eval\(function\(p,a,c,k,e,d\)\{while.*?)</script>'
		r = re.search(sPattern, html, re.DOTALL + re.IGNORECASE)
		sJavascript=r.group(1)
		sUnpacked = jsunpack.unpack(sJavascript)
		sUnpacked=str(sUnpacked).replace('\\', ' ')
		sPattern = "'file ', '(.*?)'"
		stream_url=re.search(sPattern, sUnpacked)
		if stream_url:
			self._callback(stream_url.group(1))
		else:
			self._callback("False")
				
					
	def uploadnetwork(self,url):
		data = {}
		html=self.getUrl(url)
		r=re.findall(r'"hidden" name="(.+?)" value="(.+?)".', html)
		for name,value in r:
			data[name] = value
		html=self.postUrl(url,data)
		stream_url=re.search(' "file": "(.*?)"',html,re.S)
		if stream_url:
			self._callback(stream_url.group(1))
		else:
			self._callback("False")
			
	def veetle(self,url):
		decode='http://tvmpt.x10.mx/fightnight/decode.php?id='
		temp=re.findall('http://veetle.com/index.php/widget/index/(.*?)/0/true/default/false',url)
		testid=temp[0]
		url=decode+str(testid)
		html=self.getUrl(url)
		test='m'+html+'m'
		match=re.search('m (.*?) m', test)
		veetleid=match.group(1)
		url='http://www.veetle.com/index.php/channel/ajaxStreamLocation/%s/flash' % veetleid
		stream=requests.get(url).json()
		status=stream['success']
		if status == True:
			stream_url= stream['payload']
			if stream_url:
				self._callback(stream_url)
			else:
				self._callback("False")
		else:
			self._callback("False")		
					
				
			
			
		
		
				
        	
				
				
		
				  
		
						
			
				
				
			
			
						
						
					
										
