# -*- coding: utf-8 -*-

'''
    Genesis Add-on
    Copyright (C) 2015 lambda

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

import re,urllib,urlparse,sys,unicodedata,base64

from resources.lib.libraries import cleantitle
from resources.lib.libraries import client
from resources.lib.resolvers import googleplus
from resources.lib.resolvers import openload
from resources.lib.libraries import cloudflare
from resources.lib.resolvers import up2stream
from resources.lib.resolvers import streamin
from resources.lib.resolvers import nowvideo
from resources.lib.resolvers import vodlocker


class source:    

    def __init__(self):
        print 'GenesisFR ; INIT'
        self.base_link = 'http://www.voirfilms.org'
        self.search_link = 'http://www.voirfilms.org'

    def get_movie(self, imdb, title, year):
        print ''

    def get_sources(self, url, hosthdDict, hostDict, locDict):
        
        print 'GenesisFR ; VOIRFILMS-TV; GET_SOURCES'
        
        try :
            
            tempVOSTFR = None
            
            params = dict(urlparse.parse_qsl(sys.argv[2].replace('?','')))        
                
            try:
                name = params['name']
            except:
                name = None

            try:
                title = params['title']
            except:
                title = None

            try:
                year = params['year']
            except:
                year = None

            try:
                season = params['season']
            except:
                season = None

            try:
                episode = params['episode']
            except:
                episode = None

            try:
                tvshowtitle = params['tvshowtitle']
            except:
                tvshowtitle = None

            try:
                show = params['show']
            except:
                show = None

            try:
                imdb = params['imdb']
            except:
                imdb = None

            try:
                tmdb = params['tmdb']
            except:
                tmdb = None    



            titleE = tvshowtitle
            titleF =''

            aFlag = 0
            sources = []

            query = 'http://www.thetvdb.com/api/GetSeriesByRemoteID.php?imdbid=%s&language=fr' % imdb
            result = client.request(query)

            titleF = client.parseDOM(result, 'SeriesName')[0]
            titleF = ''.join((i for i in unicodedata.normalize('NFD', titleF) if unicodedata.category(i) !='Mn'))


            aFlag = 0
            sources = []
            
        except :
            pass



        try :
            print 'GenesisFR ; VOIRFILMS-TV'
            
            url = 'http://www.voirfilms.org/'

            j = 0

            titleE= titleE.replace(' ', '%20')
            
        
            url ='http://www.voirfilms.org/rechercher'
            post = urllib.urlencode({'action': 'recherche', 'story': titleF})
            result = client.source(url, post=post)
            
            result2 = result            
            result3 = re.compile('<div class=\"imagefilm\">(.+?)<span class=\"affiche\">', re.MULTILINE|re.DOTALL).findall(result2)[0]
            
            url2 = re.compile('<a href=\"(.+?)[\'|\"]').findall(result3)[0]

            titre2 = re.compile('title=\"(.+?)[\'|\"]').findall(result3)[0]
            titre2 = titre2.replace('film ', '')

            if titleF.lower() in titre2.lower():
                result4 = client.source(url2)
                result5 = re.compile('listedessaisons\">(.+?)<div class=\"cdiv\">', re.MULTILINE|re.DOTALL).findall(result4)[0]
  
                tempLookFor = '<a href=\"(.+?) saison %s\">' % season

                url3 = re.compile(tempLookFor).findall(result5)[0]
                url3 = re.compile('(.+?)[\'|\"]').findall(url3)[0]

                tempLookFor2 = ' saison %s\">' % season
 
                titre3 = re.compile('title=\"(.+?)' + tempLookFor2).findall(result5)[0]
                titre3 = titre3 + ' saison %s' % season
                titre4 = titleF + ' saison ' + season

                if titre4.lower() in titre3.lower():
                    

                    result = client.source(url3)
                    result = client.parseDOM(result, 'a', ret='href', attrs = {'class': 'n_episode2'})
                    result = [i for i in result if 'saison-%01d-episode-%01d-' % (int(season), int(episode)) in i][0]
                    
                    url = urlparse.urljoin('http://www.voirfilms.org', result)

                    result2 = client.source(url)
        except :
            pass
 

        try :
            print 'GenesisFR ; VOIRFILMS-TV -> EASYWATCH'
            
            result = re.compile('http://easywatch.tv/embed-(.+?)[\'|\"]').findall(result2)[0]
            result = client.source('http://easywatch.tv/embed-' + result)

            video_id = re.compile('file:[\"](.+?)[\'|\"]').findall(result)[0]
            label_id = re.compile('label:[\"](.+?)[\'|\"]').findall(result)[0]
  
            url = video_id
            url = url.encode('utf-8')

            sources.append({'source': '(Fr) - Easywatch', 'quality': label_id, 'provider': 'Voirfilms', 'url': url})

            j = 1

            while j <= len(result) - 1 :
                video_id = re.compile('file:[\"](.+?)[\'|\"]').findall(result)[j]
                label_id = re.compile('label:[\"](.+?)[\'|\"]').findall(result)[j]

                url = video_id
                url = url.encode('utf-8')

                sources.append({'source': '(Fr) - Easywatch', 'quality': label_id, 'provider': 'Voirfilms', 'url': url})

                j = j + 1
            

            aFlag = 1

        except :
            pass
        


        try :
            print 'GenesisFR ; VOIRFILMS-TV -> ALLVID'
            
            j = 0

            while j <= len(result) - 1 :

                result = re.compile('http://allvid.ch/embed-(.+?)[\'|\"]').findall(result2)[j]
                result = client.source('http://allvid.ch/embed-' + result)

                video_id0 = re.compile('\"><img src=\"http://(.+?)/').findall(result)[0]
                video_id = re.compile('\\|mp4\\|(.+?)\\|sources\\|setup\\|').findall(result)[0]

                url= 'http://' + video_id0 + video_id + '/v.mp4'
                url = url.encode('utf-8')
    
                sources.append({'source': '(Fr) - Allvid', 'quality': 'HD', 'provider': 'Voirfilms', 'url': url})
    
                aFlag = 1
                
                j = j + 1
                
                if j > 10 :
                    break
                
        except :
            pass
        
        
        
        try :
            print 'GenesisFR ; VOIRFILMS-TV -> EXASHARE'
            
            j = 0

            while j <= len(result2) - 1 :
                

                
                try:
                    result = re.compile('http://www.exashare.com/embed-(.+?)\"').findall(result2)[j]
                except:
                    break
          
                result = client.source('http://exashare.com/embed-' + result)
                result = re.compile('src=[\"](.+?)[\'|\"]').findall(result)[0]
                result = client.source(result)
                
                video_id = re.compile('file: [\"](.+?)[\'|\"]').findall(result)[0]
     
                url = video_id
                url = url.encode('utf-8')
                
                sources.append({'source': '(Fr) - Exashare', 'quality': 'SD', 'provider': 'Voirfilms', 'url': url})
    
                aFlag = 1
                
                j = j + 1
                
                if j > 10 :
                    break

        except :
            pass
        
        
        
        try :
            print 'GenesisFR ; VOIRFILMS-TV -> UPTOSTREAM'
            
            j = 0

            while j <= len(result2) - 1 :
                
                try:
                    result = re.compile('https://uptostream.com/iframe/(.+?)\"').findall(result2)[j]
                except:
                    break
                    
                result2a = 'https://uptostream.com/iframe/' + result
                result = client.source(result2a)

                video_id = re.compile('<source src=\'(.+?)\'').findall(result)[0]

                url = video_id
                url = url.encode('utf-8')
                
                sources.append({'source': '(Fr) - Uptostream', 'quality': 'SD', 'provider': 'Voirfilms', 'url': url})
    
                aFlag = 1
                
                j = j + 1
                
                if j > 10 :
                    break

        except :
            pass
        
        
        
        try :
            print 'GenesisFR ; VOIRFILMS-TV -> YOUWATCH'
            
            j = 0

            while j <= len(result2) - 1 :
                
                try:
                    result = re.compile('http://youwatch.org/embed-(.+?)[\'|\"]').findall(result2)[j]
                except:
                    break

                result = client.source('http://youwatch.org/embed-' + result)            

                
                video_id = re.compile('src=[\"](.+?)[\'|\"]').findall(result)[0]
                result = client.source(video_id)
    
                video_info = re.compile('\\|provider\\|(.+?)\\|setup').findall(result)[0]
                video_info_split = video_info.split('|')
                
                video_type = video_info_split[0]
                video_name = video_info_split[1]
                video_ref = video_info_split[2]
                video_port = video_info_split[3]
                video_url_prefix = video_info_split[4]
                
                url = 'http://' + video_url_prefix + '.youwatch.org:' + video_port + '/' + video_ref + '/' + video_name + '.' + video_type
                url = url.encode('utf-8')
    
                sources.append({'source': '(Fr) - Youwatch', 'quality': 'SD', 'provider': 'Voirfilms', 'url': url})
    
                aFlag = 1
                
                j = j + 1
                
                if j > 10 :
                    break

        except :
            pass
        
        

        try :
            print 'GenesisFR ; VOIRFILMS-TV -> SPEEDVIDEO'
        
            j = 0

            while j <= len(result2) - 1 :
                
                try:
                    result = re.compile('http://speedvideo.net/embed-(.+?)[\'|\"]').findall(result2)[j]

                except:
                    pass

                result = client.source('http://speedvideo.net/embed-' + result)

                video_base64 = re.compile('file: base64_decode\([\"](.+?)[\)]').findall(result)[0]
                video_base64_split = video_base64.split('\", ')
                video_base64 = video_base64_split[0]
                video_keyId = video_base64_split[1]
                
                tempLook = 'var ' + video_keyId + ' = '
                
                video_keyInt = int(re.compile(tempLook + '(.+?)[;]').findall(result)[0])
                video_part_one = video_base64[:video_keyInt]
                video_part_two = video_base64[(video_keyInt + 10):]
                
                video_url = video_part_one + video_part_two
                
                url = base64.b64decode(video_url)
                url = url.encode('utf-8')
                
                sources.append({'source': '(Fr) - Speedvideo', 'quality': 'SD', 'provider': 'Voirfilms', 'url': url})
                
                aFlag = 1
                
                j = j + 1
                
                if j > 10 :
                    break
        
        except :
            pass
        
        
        
        try :
            print 'GenesisFR ; VOIRFILMS-TV -> OPENLOAD'
            
            j = 0

            while j <= len(result2) - 1 :
                
                try:
                    result = re.compile('https://openload.io/embed/(.+?)[\'|\"]').findall(result2)[j]
                except:
                    break

                result = 'https://openload.io/embed/' + result

                url = openload.resolve(result)            
                url = url.encode('utf-8')
                
                sources.append({'source': '(Fr) - Openload', 'quality': 'SD', 'provider': 'Voirfilms', 'url': url})
                
                aFlag = 1 
                
                j = j + 1
                
                if j > 10 :
                    break
                
        except :
            pass
        
        
        
        try :
            print 'GenesisFR ; VOIRFILMS-TV -> STREAMIN'
            
            j = 0

            while j <= len(result2) - 1 :
                
                try:
                    result = re.compile('http://streamin.to/embed-(.+?)[\'|\"]').findall(result2)[j]
                except:
                    break
                
                result = 'http://streamin.to/embed-' + result
 
                url = streamin.resolve(result)            
                url = url.encode('utf-8')
                
                sources.append({'source': '(Fr) - Streamin', 'quality': 'SD', 'provider': 'Voirfilms', 'url': url})
                
                aFlag = 1 
                
                j = j + 1
                
                if j > 10 :
                    break
                
        except :
            pass
        
        
        
                
        try :
            #À vérifier plus tard ...
            print 'GenesisFR ; VOIRFILMS-TV -> NOWVIDEO'
            
            j = 0

            while j <= len(result2) - 1 :
                
                try:
                    result = re.compile('http://embed.nowvideo.sx/embed.php\?(.+?)\&').findall(result2)[j]
                except:
                    break
                
                result = 'http://embed.nowvideo.sx/embed.php\?' + result

                url = nowvideo.resolve(result)
                url = url.encode('utf-8')
                
                sources.append({'source': '(Fr) - Nowvideo', 'quality': 'SD', 'provider': 'Voirfilms', 'url': url})
                
                aFlag = 1 
                
                j = j + 1
                
                if j > 10 :
                    break
                
        except :
            pass
        
        
        try :
           
            print 'GenesisFR ; VOIRFILMS-TV -> VODLOCKER'
            
            j = 0

            while j <= len(result2) - 1 :
                
                try:
                    result = re.compile('http://vodlocker.com/embed-(.+?)[\'|\"]').findall(result2)[j]

                except:
                    break
                
                result = 'http://vodlocker.com/embed-' + result

                url = vodlocker.resolve(result)

                url = url.encode('utf-8')
                
                sources.append({'source': '(Fr) - Vodlocker', 'quality': 'SD', 'provider': 'Voirfilms', 'url': url})
                
                aFlag = 1 
                
                j = j + 1
                
                if j > 10 :
                    break
                
        except :
            pass

        
        
        return sources


    def resolve(self, url):

        try:
            if url.startswith('stack://'): return url

            url = client.request(url, output='geturl')

            if 'requiressl=yes' in url: url = url.replace('http://', 'https://')

            else: url = url.replace('https://', 'http://')

            return url

        except:
            return