# -*- 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

class source:    

    def __init__(self):
        print 'GenesisFR TV ; INIT'
        self.base_link = 'http://libre-stream.org/series/version-francaise/'
        self.search_link = 'http://libre-stream.org/index.php?search_start=1&result_from=1&q=%s&genrelist[]=30'

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

    def get_sources(self, url, hosthdDict, hostDict, locDict):
        try :

            print 'GenesisFR TV; TMDB'
            
            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'))


            url = 'http://libre-stream.org/'
            
            cookie = client.request(url, output='cookie')
            post = 'action=login&login_name=ilovestreaming&login_password=ilovestreaming&Submit=&login=submit'
            cookie = client.request(url, post=post, output='cookie')
            result = client.request(url, cookie=cookie)
            
        except :
            pass



        try :
            print 'GenesisFR TV; LIBRESTREAM'

            video_season = ' - Saison ' + season
            
            url = 'http://libre-stream.org/index.php?search_start=1&result_from=1&q=%s&genrelist[]=30' % urllib.quote_plus(titleF + ' ' + video_season)
            print '### url 0 ### %s' % url
            
            result = client.source(url)
            #print result
            
            tempVOSTFR = '' 
            try:
                #<a href="http://libre-stream.org/series/vostfr/">VOSTFR</a>
                tempSearchVOSTFR = 'http://libre-stream.org/series/vostfr/\">'
                tempVOSTFR = re.compile(tempSearchVOSTFR + '(.+?)<').findall(result)[0]
                print tempVOSTFR
                
            except:
                tempVOSTFR = 'VF'
            
            theSearch = 'window.location.href=(.+?) - Saison %s<' % season
        
            video_id = re.compile(theSearch).findall(result)[0]
            video_title = re.compile('\'\">(.+?)$').findall(video_id)[0]
            video_id = re.compile('\'(.+?)\'\">').findall(video_id)[0]        


      
            
            result = client.source(video_id)
            result2 = result

            video_search = 'class=\"number-bubble\">%s(.+?).html' % episode
            video_id = re.compile(video_search, re.MULTILINE|re.DOTALL).findall(result2)[0]
            video_id = video_id + '.html\"'
            
            result2 = video_id
            
        except :
            pass
        
        

        try :
            print 'GenesisFR ; TV; LIBRESTREAM -> 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 - ' + tempVOSTFR, 'quality': label_id, 'provider': 'LibreStream', '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 - ' + tempVOSTFR, 'quality': label_id, 'provider': 'LibreStream', 'url': url})

                j = j + 1
            

            aFlag = 1

        except :
            pass
        


        try :
            print 'GenesisFR ; TV; LIBRESTREAM -> ALLVID'
            result = re.compile('http://allvid.ch/embed-(.+?)[\'|\"]').findall(result2)[0]
            result = client.source('http://allvid.ch/embed-' + result)

            video_id = re.compile('file:[\"](.+?)[\'|\"]').findall(result)[0]

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

            sources.append({'source': '(Fr) - Allvid - ' + tempVOSTFR, 'quality': 'HD', 'provider': 'LibreStream', 'url': url})

            j = 1

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

                sources.append({'source': '(Fr) - Allvid - ' + tempVOSTFR, 'quality': 'HD', 'provider': 'LibreStreamm', 'url': url})

                j = j + 1

            aFlag = 1

        except :
            pass
        
        
        
        try :
            print 'GenesisFR ; TV; LIBRESTREAM -> EXASHARE'
            result = re.compile('http://www.exashare.com/embed-(.+?)[\'|\"]').findall(result2)[0]
            result = client.source('http://www.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 - ' + tempVOSTFR, 'quality': 'SD', 'provider': 'LibreStream', 'url': url})

            aFlag = 1 

        except :
            pass
        
        
        
        try :
            print 'GenesisFR ; TV; LIBRESTREAM -> YOUWATCH'
            result = re.compile('http://youwatch.org/embed-(.+?)[\'|\"]').findall(result2)[0]
            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 - ' + tempVOSTFR, 'quality': 'SD', 'provider': 'LibreStream', 'url': url})

            aFlag = 1

        except :
            pass
        
        

        try :
            print 'GenesisFR ; TV; LIBRESTREAM -> SPEEDVIDEO'
        
            result = re.compile('http://speedvideo.net/embed-(.+?)[\'|\"]').findall(result2)[0]
            result = client.source('http://speedvideo.net/embed-' + result)

            video_base64 = re.compile('var linkfile =[\"](.+?)[\'|\"]').findall(result)[0]
            video_keyId = re.compile('linkfile, (.+?);').findall(result)[0]
            video_keyId = video_keyId[:-1]   #[1:-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 - ' + tempVOSTFR, 'quality': 'SD', 'provider': 'LibreStream', 'url': url})
            
            aFlag = 1 
        
        except :
            pass
        
        
        
        try :
            print 'GenesisFR ; TV; LIBRESTREAM -> EASYVID'
            result = re.compile('http://easyvid.org/embed-(.+?)[\'|\"]').findall(result2)[0]
            result = client.source('http://easyvid.org/embed-' + result)

            url = re.compile('file: \"(.+?)[\'|\"]').findall(result)[1]
            url = url.encode('utf-8')
            
            sources.append({'source': '(Fr) - Easyvid - ' + tempVOSTFR, 'quality': 'SD', 'provider': 'LibreStream', 'url': url})
            
            aFlag = 1 
        
        except :
            pass
        
        
        
        try :
            print 'GenesisFR ; TV; LIBRESTREAM -> OPENLOAD'
            result = re.compile('https://openload.co/embed/(.+?)[\'|\"]').findall(result2)[0]
            result = 'https://openload.co/embed/' + result
           
            url = openload.resolve(result)            
            url = url.encode('utf-8')
            
            sources.append({'source': '(Fr) - Openload - ' + tempVOSTFR, 'quality': '1080p', 'provider': 'LibreStream', 'url': url})
            
            aFlag = 1 
        
        except :
            pass
        
        
        
        try :
            print 'GenesisFR ; TV; LIBRESTREAM -> VIDZI'
            result = re.compile('http://vidzi.tv/embed-(.+?)[\'|\"]').findall(result2)[0]
            result = client.source('http://vidzi.tv/embed-' + result)

            theList = re.compile('\|position\|(.+?)\|sources\|').findall(result)[0]
            theList = theList.split('|')

            nbElementTheList = theList.__len__()
            theIndex = theList.index('mp4')

            url_part1 = 'http://' + theList[5] + '.' + theList[4] + '.' + theList[3] + '.' + theList[2] + ':' + theList[1] + '/'
            url_part2 = theList[theIndex+2] + '/' + theList[theIndex+1] + '/chunk.' + theList[theIndex+5]
            url = url_part1 + url_part2
            url = url.encode('utf-8')
            
            sources.append({'source': '(Fr) - Vidzi - ' + tempVOSTFR, 'quality': 'SD', 'provider': 'LibreStream', 'url': url})
            
            aFlag = 1 
        
        except :
            pass
        
        
        
        try :
            print 'GenesisFR ; TV; LIBRESTREAM -> MYSTREAM'
            result = re.compile('http://mystream.la/external/(.+?)[\'|\"]').findall(result2)[0]
            result = client.source('http://mystream.la/external/' + result)
            
            url = re.compile('file: \'(.+?)[\'|\"]').findall(result)[0]
            url = url.encode('utf-8')
            
            sources.append({'source': '(Fr) - Mystream - ' + tempVOSTFR, 'quality': 'SD', 'provider': 'LibreStream', 'url': url})
            
            aFlag = 1 
        
        except :
            pass
        
        
        
        try :
            print 'GenesisFR ; TV; LIBRESTREAM -> WATCHING'
            result = re.compile('http://watching.to/external/(.+?)[\'|\"]').findall(result2)[0]
            result = client.source('http://watching.to/external/' + result)
            
            url = re.compile('file:\"(.+?)[\'|\"]').findall(result)[0]
            url = url.encode('utf-8')
            
            sources.append({'source': '(Fr) - Watching', 'quality': 'SD', 'provider': 'LibreStream', 'url': url})
            
            
            url = re.compile('.smil\"\},\{file: \"(.+?)[\'|\"]').findall(result)[0]
            url = url.encode('utf-8')

            
            sources.append({'source': '(Fr) - Watching - ' + tempVOSTFR, 'quality': 'SD', 'provider': 'LibreStream', 'url': url})
            
            aFlag = 1 
        
        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