示例#1
0
 def get_oneepg(self, sTitle):
     
     sUrl = self.get_url(sTitle)
     if not sUrl:
         dialog().VSinfo('EPG introuvable')
         return
     
     oRequestHandler = cRequestHandler(sUrl)
     sHtmlContent = oRequestHandler.request();
     sHtmlContent = sHtmlContent.replace('<br>', '')
     text = ''
     sPattern = '<div .*?class="broadcast">.+?<span class="hour">(.+?)</span>.+?<div class="programme">.+?<.+?class="title" title=".+?">(.+?)</.+?>.+?(?:<span class="subtitle">(.+?)</span>.+?|)<span class="type">(.+?)</span>'
     
     oParser = cParser()
     aResult = oParser.parse(sHtmlContent, sPattern)
     if (aResult[0] == True):
         for aEntry in aResult[1]:
             #hour
             text += "[B]"+aEntry[0]+"[/B] : "
             #type
             text += "[I]"+aEntry[3]+"[/I] - "
             #title
             text += "[COLOR khaki][UPPERCASE]"+aEntry[1]+"[/UPPERCASE][/COLOR] "
             #subtitle
             text += aEntry[2]
             
             #retour line
             text += "\r\n"
             
         return text
     else:
         return ''
def load():
    oGui = cGui()
    addons = addon()
    oPremiumHandler = cPremiumHandler('uptobox')

    if (addons.getSetting('hoster_uptobox_username') == '') and (addons.getSetting('hoster_uptobox_password') == ''):
        oGui.addText(SITE_IDENTIFIER, '[COLOR red]' + 'Nécessite Un Compte Uptobox Premium ou Gratuit' + '[/COLOR]')
        oOutputParameterHandler = cOutputParameterHandler()
        oOutputParameterHandler.addParameter('siteUrl', 'http://venom/')
        oGui.addDir(SITE_IDENTIFIER,'opensetting', addons.VSlang(30023), 'none.png', oOutputParameterHandler)
    else:
        if (GestionCookie().Readcookie('uptobox') != ''):

            oOutputParameterHandler = cOutputParameterHandler()
            oOutputParameterHandler.addParameter('siteUrl', 'http://venom/')
            oGui.addDir(SITE_IDENTIFIER, 'showFile', 'Mes Fichiers et Dossiers', 'genres.png', oOutputParameterHandler)

        else:
            Connection = oPremiumHandler.Authentificate()
            if (Connection == False):
                dialog().VSinfo('Connexion refusée')
                return

            oOutputParameterHandler = cOutputParameterHandler()
            oOutputParameterHandler.addParameter('siteUrl', 'http://venom/')
            oGui.addDir(SITE_IDENTIFIER, 'showFile', 'Mes Fichiers et Dossiers', 'genres.png', oOutputParameterHandler)


    oGui.setEndOfDirectory()
def ouTMyTmdb():
    addons = addon()
    addons.setSetting('tmdb_session', '')
    addons.setSetting('tmdb_account', '')

    dialog().VSinfo(addons.VSlang(30320))
    VSupdate()
    showMyTmdb()
    return
    def __getMediaLinkForGuest(self):
        url=[]
        qua=[]
        api_call = ''
        
        #reformatage du lien
        sId = self.__getIdFromUrl(self.__sUrl)
        sUrl = 'https://drive.google.com/file/d/' + sId + '/view' #?pli=1

        req = urllib2.Request(sUrl)
        response = urllib2.urlopen(req)
        sHtmlContent = response.read()

        Headers = response.headers
        response.close()

        #listage des cookies
        c = Headers['Set-Cookie']
        c2 = re.findall('(?:^|,) *([^;,]+?)=([^;,\/]+?);', c)
        if c2:
            cookies = ''
            for cook in c2:
                cookies = cookies + cook[0] + '=' + cook[1] + ';'

        sPattern = '\["fmt_stream_map","([^"]+)"]'

        oParser = cParser()
        aResult = oParser.parse(sHtmlContent, sPattern)
        if not aResult[0]:
            if '"errorcode","150"]' in sHtmlContent:
                dialog().VSinfo("Nombre de lectures max dépassé")
            return False,False

        sListUrl = aResult[1][0]

        if sListUrl:
            aResult2 = oParser.parse(sHtmlContent, '([0-9]+)\/([0-9]+x[0-9]+)\/')

        #liste les qualitee
            r = oParser.parse(sListUrl, '([0-9]+)\|([^,]+)')
            for item in r[1]:
                url.append(item[1].decode('unicode-escape'))
                for i in aResult2[1]:
                    if item[0] == i[0]:
                        qua.append(i[1])
       
        #Afichage du tableau
        api_call = dialog().VSselectqual(qua, url)
        api_call = api_call + '|User-Agent=' + UA + '&Cookie=' + cookies
        
        if (api_call):
            return True, api_call

        return False, False
示例#5
0
    def getUpdate(self):
        addons = addon()
        service_time = addons.getSetting('service_time')
        service_version = addons.getSetting('service_version')
        #service_version = ""

        #Si pas d'heure indique = premiere install
        if not (service_time):
            #On memorise la date d'aujourdhui
            addons.setSetting('service_time', str(datetime.datetime.now()))
            #Mais on force la maj avec une date a la con
            service_time = '2000-09-23 10:59:50.877000'

        if not (service_version):
            #version de l'addon
            addons.setSetting('service_version', str(addons.getAddonInfo("version")))
            service_version = addons.getAddonInfo("version")

        #si addon = 0.7.0 et service_version 0.6.35 pas de mise ajour.
        if (addons.getAddonInfo("version") > service_version):
            addons.setSetting('service_version', str(addons.getAddonInfo("version")))
            service_version = addons.getAddonInfo("version")


        if (service_time):
            #delay mise a jour
            time_sleep = datetime.timedelta(hours=72)
            time_now = datetime.datetime.now()
            time_service = self.__strptime(service_time, "%Y-%m-%d %H:%M:%S.%f")
            #pour test
            #if (time_sleep):
            if (time_now - time_service > time_sleep):
                #verifier la nouvelle version

                sUrl = 'https://api.github.com/repos/Kodi-vStream/venom-xbmc-addons/releases/latest'
                oRequestHandler = cRequestHandler(sUrl)
                sHtmlContent = oRequestHandler.request()
                result = json.loads(sHtmlContent)

                #pour test
                #if (result['tag_name']):
                if (result['tag_name'] > service_version):
                    addons.setSetting('service_futur', str(result['tag_name']))
                    addons.setSetting('home_update', str('true'))
                    addons.setSetting('service_time', str(datetime.datetime.now()))
                    dialog().VSinfo("Mise à jour disponible")
                else:
                    addons.setSetting('service_time', str(datetime.datetime.now()))
                    addons.setSetting('home_update', str('false'))
                    VSlog('Prochaine verification de MAJ le : ' + str(time_sleep + time_service) )
        return
示例#6
0
    def getUpdate_old(self):
        addons = addon()
        service_time = addons.getSetting('service_time')

        #Si pas d'heure indique = premiere install
        if not (service_time):
            #On memorise la date d'aujourdhui
            addons.setSetting('service_time', str(datetime.datetime.now()))
            #Mais on force la maj avec une date a la con
            service_time = '2000-09-23 10:59:50.877000'

        if (service_time):
            #delay mise a jour
            time_sleep = datetime.timedelta(hours=72)
            time_now = datetime.datetime.now()
            time_service = self.__strptime(service_time, "%Y-%m-%d %H:%M:%S.%f")
            #pour test
            #if (time_sleep):
            if (time_now - time_service > time_sleep):
                #test les fichier pour mise a jour
                #self.checkupdate()
                result = self.resultGit()
                sDown = 0

                if result:
                    for i in result:
                        try:
                            rootpath = self.getRootPath(i['path'])

                            if self.checksize(rootpath,i['size']):
                                sDown = sDown+1
                                break #Si on en trouve un, pas besoin de tester les autres.

                        except:
                            VSlog('erreur : verification MAJ' )
                            return

                    if (sDown != 0):
                        addons.setSetting('home_update', str('true'))
                        addons.setSetting('service_time', str(datetime.datetime.now()))
                        dialog().VSinfo("Mise à jour disponible")
                    else:
                        #cConfig().showInfo('vStream', 'Fichier a jour')
                        addons.setSetting('service_time', str(datetime.datetime.now()))
                        addons.setSetting('home_update', str('false'))

            else:
                VSlog('Prochaine verification de MAJ le : ' + str(time_sleep + time_service) )
                #Pas besoin de memoriser la date, a cause du cache kodi > pas fiable.
        return
def ProtectstreamBypass(url):

    #lien commencant par VID_
    Codedurl = url
    oRequestHandler = cRequestHandler(Codedurl)
    sHtmlContent = oRequestHandler.request()

    oParser = cParser()
    sPattern = 'var k=\"([^<>\"]*?)\";'
    aResult = oParser.parse(sHtmlContent, sPattern)

    if (aResult[0] == True):
        postdata = 'k=' + aResult[1][0]

        dialog().VSinfo('Décodage en cours', "Patientez", 5)
        xbmc.sleep(5000)

        UA = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0'

        oRequest = cRequestHandler(URL_MAIN + 'secur22.php')
        oRequest.setRequestType(1)
        oRequest.addHeaderEntry('User-Agent', UA)
        #oRequest.addHeaderEntry('Host', 'www.protect-stream.com')
        oRequest.addHeaderEntry('Referer', Codedurl)
        oRequest.addHeaderEntry('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
        oRequest.addHeaderEntry('Content-Type', 'application/x-www-form-urlencoded')
        oRequest.addParametersLine(postdata)
        sHtmlContent = oRequest.request()

        #Test de fonctionnement
        aResult = oParser.parse(sHtmlContent, sPattern)
        if aResult[0]:
            dialog().VSinfo('Lien encore protégé', "Erreur", 5)
            return ''

        #recherche du lien embed
        sPattern = '<iframe src=["\']([^<>"\']+?)["\']'
        aResult = oParser.parse(sHtmlContent, sPattern)
        if (aResult[0] == True):
            return aResult[1][0]

        #recherche d'un lien redirigee
        sPattern = '<a class=.button. href=["\']([^<>"\']+?)["\'] target=._blank.>'
        aResult = oParser.parse(sHtmlContent, sPattern)
        if (aResult[0] == True):
            return aResult[1][0]

    return ''
示例#8
0
    def __getMediaLinkForGuest(self):

        oParser = cParser()
        oRequest = cRequestHandler(self.__sUrl)
        sHtmlContent = oRequest.request()

        sPattern =  'src: *"([^"]+)".+?label:"([^"]+)"'
        oParser = cParser()
        aResult = oParser.parse(sHtmlContent, sPattern)
        if (aResult[0] == True):
            #initialisation des tableaux
            url=[]
            qua=[]
            #Remplissage des tableaux
            for i in aResult[1]:
                url.append(str(i[0]))
                qua.append(str(i[1]))

            #dialogue qualité
            api_call = dialog().VSselectqual(qua, url)

        if (api_call):
            return True, api_call

        return False, False
示例#9
0
    def __getMediaLinkForGuest(self):
        api_call = False

        oRequest = cRequestHandler(self.__sUrl)
        sHtmlContent = oRequest.request()

        #type1
        oParser = cParser()
        sPattern = '<source *src="([^"]+)" *type=\'video/.+?\''
        aResult = oParser.parse(sHtmlContent, sPattern)
        if (aResult[0] == True):
            api_call = aResult[1][0]

        #type2?
        sPattern =  '<script type=\'text/javascript\'>(.+?)</script>'
        aResult = oParser.parse(sHtmlContent, sPattern)
        if (aResult[0] == True):
            stri = cPacker().unpack(aResult[1][0])
            sPattern =  'file:"([^"]+)",label:"([0-9]+)"}'
            aResult = oParser.parse(stri, sPattern)
            if (aResult[0] == True):
                url=[]
                qua=[]

                for aEntry in aResult[1]:
                    url.append(aEntry[0])
                    qua.append(aEntry[1][:3] + '*' + aEntry[1][3:])

                api_call = dialog().VSselectqual(qua, url)

        if (api_call):
            return True, api_call

        return False, False
示例#10
0
    def __getMediaLinkForGuest(self):

        #VSlog(self.__sUrl)
        api_call = False
          
        oRequest = cRequestHandler(self.__sUrl)
        #oRequest.addHeaderEntry('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0')
        #oRequest.addHeaderEntry('Upgrade-Insecure-Requests','1')
        #oRequest.addHeaderEntry('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
        #oRequest.addHeaderEntry('Accept-Encoding','gzip, deflate, br')
        sHtmlContent = oRequest.request()
        
        #fh = open('c:\\test.txt', "w")
        #fh.write(sHtmlContent)
        #fh.close()
        
        oParser = cParser()
        sPattern =  '"file":"([^"]+)","label":"([0-9]+)p"'
        aResult = oParser.parse(sHtmlContent, sPattern)
        
        if (aResult[0]):
            url=[]
            qua=[]
            
            for aEntry in aResult[1]:
                url.append(aEntry[0])
                qua.append(aEntry[1])

            #tableau
            api_call = dialog().VSselectqual(qua, url)

        if (api_call):
            return True, api_call
        
        return False, False
示例#11
0
    def __getMediaLinkForGuest(self):

        sUrl = self.__sUrl

        oRequest = cRequestHandler(sUrl)
        sHtmlContent = oRequest.request()

        if 'File was deleted' in sHtmlContent:
            return False,False

        oParser = cParser()
        sPattern = '(eval\(function\(p,a,c,k,e(?:.|\s)+?\))<\/script>'
        aResult = oParser.parse(sHtmlContent,sPattern)

        if (aResult[0] == True):
            sHtmlContent = cPacker().unpack(aResult[1][0])

        sPattern = '{file:"([^"]+)",label:"([^"]+)"}'
        aResult = oParser.parse(sHtmlContent,sPattern)
        if (aResult[0] == True):
            #initialisation des tableaux
            url=[]
            qua=[]
        
            #Remplissage des tableaux
            for i in aResult[1]:
                url.append(str(i[0]))
                qua.append(str(i[1]))
                
            api_call = dialog().VSselectqual(qua,url)

        if (api_call):
            return True, api_call

        return False, False
示例#12
0
    def __getMediaLinkForGuest(self):
        api_call = False

        oRequest = cRequestHandler(self.__sUrl)
        sHtmlContent = oRequest.request()

        oParser = cParser()
        sPattern =  "var vsuri = \'(.+?)\'"
        aResult = oParser.parse(sHtmlContent, sPattern)

        if (aResult[0]):
            oRequest = cRequestHandler(aResult[1][0])
            sHtmlContent1 = oRequest.request()

            sPattern1 =  '"([^"]+)":"([^"]+)"'
            aResult1 = oParser.parse(sHtmlContent1, sPattern1)

        if (aResult1[0]):

            url=[]
            qua=[]
            api_call = False

            for aEntry in aResult1[1]:
                url.append(aEntry[1])
                qua.append(aEntry[0])

            api_call = dialog().VSselectqual(qua, url)

            if (api_call):
                return True, api_call

        return False, False
示例#13
0
    def __getMediaLinkForGuest(self):

        oRequestHandler = cRequestHandler(self.__sUrl)
        sHtmlContent = oRequestHandler.request()

        oParser = cParser()
        sPattern = '(\s*eval\s*\(\s*function(?:.|\s)+?{}\)\))'
        #sPattern = '(eval\(function\(p,a,c,k,e(?:.|\s)+?\))<\/script>'
        aResult = oParser.parse(sHtmlContent, sPattern)
        
        if (aResult[0] == True):

            sHtmlContent = cPacker().unpack(aResult[1][0])

            sPattern = 'file":"([^"]+)".+?"label":"([^"]+)"'
            aResult = oParser.parse(sHtmlContent, sPattern)

            if (aResult[0] == True):
                url=[]
                qua=[]

                for aEntry in aResult[1]:
                    url.append(aEntry[0])
                    qua.append(aEntry[1])

                api_call = dialog().VSselectqual(qua, url)

        if (api_call):
            return True, api_call

        return False, False
示例#14
0
    def getMediaLink(self):
        self.oPremiumHandler = cPremiumHandler(self.getPluginIdentifier())
        if (self.oPremiumHandler.isPremiumModeAvailable()):

            try:
                mDefault = int(self.ADDON.getSetting("hoster_uptobox_mode_default"))
            except AttributeError:
                mDefault = 0

            if mDefault is 0:
                ret = dialog().select('Choissisez votre mode de fonctionnement', ['Passer en Streaming (via Uptostream)', 'Rester en direct (via Uptobox)'])
            else:
                # 0 is ask me, so 1 is uptostream and so on...
                ret = mDefault - 1

            #mode DL
            if ret == 1:
                self.stream = False
            #mode stream
            elif ret == 0:
                self.__sUrl = self.__sUrl.replace('uptobox.com/', 'uptostream.com/')
            else:
                return False

            return self.__getMediaLinkByPremiumUser()

        else:
            VSlog('no premium')
            return self.__getMediaLinkForGuest()
示例#15
0
    def __getMediaLinkForGuest(self):

        oParser = cParser()
        oRequest = cRequestHandler(self.__sUrl)
        sHtmlContent = oRequest.request()

        #accelère le traitement
        sHtmlContent = oParser.abParse(sHtmlContent, 'var player', 'vvplay')

        sPattern =  '([^"]+\.mp4)'
        oParser = cParser()
        aResult = oParser.parse(sHtmlContent, sPattern)
        if (aResult[0] == True):
            #initialisation des tableaux
            url=[]
            qua=["HD", "SD"] #sd en 2eme pos generalement quand sd
            api_call = ''

            #Remplissage des tableaux
            for i in aResult[1]:
                url.append(str(i))

            #dialogue qualité
            api_call = dialog().VSselectqual(qua, url)

        if (api_call):
            return True, api_call

        return False, False
示例#16
0
    def showNumBoard(self, sDefaultNum=''):
        dialogs = dialog()
        numboard = dialogs.numeric(0, 'Entrer la page', sDefaultNum)
        #numboard.doModal()
        if numboard != None:
                return numboard

        return False
示例#17
0
def getToken():
    ADDON = addon()
    oGui = cGui()

    username = oGui.showKeyBoard(heading="Rentrer votre nom d'utilisateurs")
    password = oGui.showKeyBoard(heading="Rentrer votre mots de passe")
    oRequestHandler = cRequestHandler('https://api.alldebrid.com/user/login?agent=mySoft&username='******'&password='******'"token":"(.+?)"'

    oParser = cParser()
    aResult = oParser.parse(sHtmlContent, sPattern)
    VSlog(aResult)
    ADDON.setSetting('token_alldebrid', ''.join(aResult[1]))
    dialog().VSinfo('Token Ajouter', "Extreme-Download", 15)
    oGui.setEndOfDirectory()
def Display_protected_link():
    #print 'entering Display_protected_link'
    oGui = cGui()
    oParser = cParser()
    oInputParameterHandler = cInputParameterHandler()
    sMovieTitle = oInputParameterHandler.getValue('sMovieTitle')
    sUrl = oInputParameterHandler.getValue('siteUrl')
    sThumb = oInputParameterHandler.getValue('sThumb')

    #Est ce un lien dl-protect ?
    if '/l.k.s/' in sUrl:
        sHtmlContent = DecryptddlProtect(sUrl)

        if sHtmlContent:
            #Si redirection
            if sHtmlContent.startswith('http'):
                aResult_dlprotect = (True, [sHtmlContent])
            else:
                sPattern_dlprotect = '<p><a href="(.+?)">.+?</a></p>'
                aResult_dlprotect = oParser.parse(sHtmlContent, sPattern_dlprotect)

        else:
            oDialog = dialog().VSok('Désolé, problème de captcha.\n Veuillez en rentrer un directement sur le site, le temps de réparer')
            aResult_dlprotect = (False, False)

    elif 'keeplinks' in sUrl:
        oDialog = dialog().VSinfo('Keeplinks non pris en charge', 'cinemegatoil', 10)
    #Si lien normal
    else:
        if not sUrl.startswith('http'):
            sUrl = 'http://' + sUrl
        aResult_dlprotect = (True, [sUrl])

    if (aResult_dlprotect[0]):
        for aEntry in aResult_dlprotect[1]:
            sHosterUrl = aEntry

            sTitle = sMovieTitle

            oHoster = cHosterGui().checkHoster(sHosterUrl)
            if (oHoster != False):
                oHoster.setDisplayName(sTitle)
                oHoster.setFileName(sTitle)
                cHosterGui().showHoster(oGui, oHoster, sHosterUrl, sThumb)

    oGui.setEndOfDirectory()
示例#19
0
    def get_epg(self, sTitle, sTime):
        #ce soir
        if sTime == 'direct':
            sUrl = 'http://playtv.fr/programmes-tv/en-direct/canalsat/'
        elif sTime == 'soir':
            sUrl = 'http://playtv.fr/programmes-tv/'+date+'/20h-23h/'
        else :
            sUrl = 'http://playtv.fr/programmes-tv/'+date+'/20h-23h/'
            

        oRequestHandler = cRequestHandler(sUrl)
        sHtmlContent = oRequestHandler.request();
        text = ''
        
        sPattern = '<a class="channel-img".+?<img.+?alt="(.+?)".+?|<span class="start" title="(.+?)">(.+?)</span>.+?<span class="program-gender small">.+?<span>(.+?)</span>.+?<a href=".+?" title=".+?">(.+?)</a>'
        
          
        oParser = cParser()
        aResult = oParser.parse(sHtmlContent, sPattern)
        if (aResult[0] == True):
            for aEntry in aResult[1]:
                #chaine
                if aEntry[0]:
                    text += "[COLOR red]"+aEntry[0]+"[/COLOR]\r"
                #heure
                if aEntry[2]:
                    text += "[B]"+aEntry[2]+"[/B] -"
                #duréé
                if aEntry[1]:
                    text += aEntry[1]+" : "
                #type
                if aEntry[3]:
                    text += "("+aEntry[3]+") "   

                #title
                if aEntry[4]:
                    text += "     [COLOR khaki][UPPERCASE]"+aEntry[4]+"[/UPPERCASE][/COLOR] "
                
                #retour line
                text += "\r\n"
                
            self.TextBoxes(sTitle,text)
        else:
            dialog().VSinfo('Impossible de trouver le guide tv')
示例#20
0
    def getMediaLink(self):

        self.oPremiumHandler = cPremiumHandler(self.getPluginIdentifier())
        print self.oPremiumHandler.isPremiumModeAvailable()

        if (not self.oPremiumHandler.isPremiumModeAvailable()):
            oDialog = dialog().VSok('ATTENTION, Pas de streaming sans premium.')
            return False, False

        return self.__getMediaLinkByPremiumUser()
def getCat():

    disp = ['1','2']
    dialogs = dialog()
    dialog_select = 'Films', 'Series'

    ret = dialogs.select('TMDB', dialog_select)

    if ret > -1:
        sType = disp[ret]
    return sType
def getWatchlist():
    grab = cTMDb()
    addons = addon()

    tmdb_session = addons.getSetting('tmdb_session')
    tmdb_account = addons.getSetting('tmdb_account')

    if not tmdb_session:
        return

    if not tmdb_account:
        return

    oInputParameterHandler = cInputParameterHandler()


    sCat = oInputParameterHandler.getValue('sCat')
    if not sCat:
        return

    #dans le doute si meta active
    sTMDB = oInputParameterHandler.getValue('sTmdbId')
    sSeason = oInputParameterHandler.getValue('sSeason')
    sEpisode = oInputParameterHandler.getValue('sEpisode')

    sCat = sCat.replace('1', 'movie').replace('2', 'tv')
 
    if not sTMDB:
        sTMDB = grab.get_idbyname(oInputParameterHandler.getValue('sFileName'), '', sCat)
    if not sTMDB:
        return

    sPost = {"media_type": sCat, "media_id": sTMDB, 'watchlist': True}
    sAction = 'account/%s/watchlist' % tmdb_account

    data = grab.getPostUrl(sAction, sPost)

    if len(data) > 0:
        dialog().VSinfo(data['status_message'])

    return
示例#23
0
    def SearchBA(self):

            url = "https://www.googleapis.com/youtube/v3/search?part=id,snippet&q=%s&maxResults=1&relevanceLanguage=fr&key=%s" % (self.search, self.key)

            req = urllib2.Request(url)
            try:
                gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
                response = urllib2.urlopen(req,context=gcontext)
            except:
                response = urllib2.urlopen(req)
            sHtmlContent = response.read()
            result = json.loads(sHtmlContent)
            response.close()

            try:
                ids = result['items'][0]['id']['videoId']

                url = 'http://www.youtube.com/watch?v=%s' % ids
                from resources.hosters.youtube import cHoster
                hote = cHoster()
                hote.setUrl(url)
                api_call = hote.getMediaLink()[1]
                if not api_call:
                    return

                oGuiElement = cGuiElement()
                oGuiElement.setSiteName(SITE_IDENTIFIER)
                oGuiElement.setTitle(self.search.replace('+',' '))
                oGuiElement.setMediaUrl(api_call)
                oGuiElement.setThumbnail(oGuiElement.getIcon())

                oPlayer = cPlayer()
                oPlayer.clearPlayList()
                oPlayer.addItemToPlaylist(oGuiElement)
                oPlayer.startPlayer()

            except:
                dialog().VSinfo(addon().VSlang(30204))
                return
            return
def getAction():
    grab = cTMDb()
    dialogs = dialog()

    oInputParameterHandler = cInputParameterHandler()

    sAction= ''
    if not sAction:
        sAction, sFow, sYn = getContext()
    if not sAction:
        return

    sCat = oInputParameterHandler.getValue('sCat')
    if not sCat:
        sCat = getCat()
    if not sCat:
        return

    #dans le doute si meta active
    sTMDB = oInputParameterHandler.getValue('sTmdbId')
    sSeason = oInputParameterHandler.getValue('sSeason')
    sEpisode = oInputParameterHandler.getValue('sEpisode')

    sCat = sCat.replace('1', 'movie').replace('2', 'tv')

    if not sTMDB:
        sTMDB = grab.get_idbyname(oInputParameterHandler.getValue('sFileName'), '', sCat)
    if not sTMDB:
        return


    if sAction == 'vote':
        #vote /movie/{movie_id}/rating
        #/tv/{tv_id}/rating
        numboard = dialogs.numeric(0, 'Min 0.5 - Max 10')
        if numboard != None:
            sAction = '%s/%s/rating' % (sCat, sTMDB)
            sPost = {"value": numboard}
        else :
            return

    else:

        sPost = {"media_type": sCat, "media_id": sTMDB, sFow: sYn}


    data = grab.getPostUrl(sAction, sPost)

    if len(data) > 0:
        dialogs.VSinfo(data['status_message'])

    return
示例#25
0
    def __getMediaLinkForGuest(self):
        stream_url = False

        oParser = cParser()

        sID = self.__getIdFromUrl(self.__sUrl)
        sRestUrl = self.__getRestFromUrl(self.__sUrl)

        api = 'http://rutube.ru/api/play/options/' + sID + '/?format=json&no_404=true&referer=' + urllib.quote(self.__sUrl, safe = '')
        api = api + '&' + sRestUrl

        oRequest = cRequestHandler(api)
        sHtmlContent = oRequest.request()

        sPattern = '"m3u8": *"([^"]+)"'
        aResult = oParser.parse(sHtmlContent, sPattern)

        if not (aResult):
            sPattern = '"default": *"([^"]+)"'
            aResult = oParser.parse(sHtmlContent, sPattern)

        if (aResult[0] == True):
            url2 = aResult[1][0]
        else:
            return False,False

        oRequest = cRequestHandler(url2)
        sHtmlContent = oRequest.request()

        sPattern = '(http.+?\?i=)([0-9x_]+)'
        aResult = oParser.parse(sHtmlContent, sPattern)

        if (aResult[0] == True):
            url=[]
            qua=[]

            for aEntry in aResult[1]:
                url.append(aEntry[0] + aEntry[1])
                qua.append(aEntry[1])

            #tableau
            stream_url = dialog().VSselectqual(qua, url)

        if (stream_url):
            return True, stream_url
        else:
            return False, False

        return False, False
示例#26
0
    def __getMediaLinkForGuest(self):

        api_call = False
        aResult = False

        request_headers = {
        "User-Agent": UA
        }

        #thevideo.me doesn't exist so take redirection
        req = urllib2.Request(self.__sUrl,headers=request_headers)
        gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        response = urllib2.urlopen(req,context=gcontext)
        #sHtmlContent = response.read()
        self.__sUrl = response.geturl()
        response.close()

        Json_url = 'https://vev.io/api/serve/video/' + self.__getIdFromUrl( self.__sUrl )

        req = urllib2.Request(Json_url,headers=request_headers)
        gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        response = urllib2.urlopen(req, data="{}" ,context=gcontext)
        sHtmlContent = response.read()
        aResult = json.loads(sHtmlContent)
        response.close()

        #VSlog(aResult['qualities'])

        if (aResult):
            #initialisation des tableaux
            url=[]
            qua=[]

            #Remplissage des tableaux
            for i in aResult['qualities']:
                url.append(aResult['qualities'][i])
                qua.append(str(i))

            #dialog qualiter
            api_call = dialog().VSselectqual(qua, url)

        #xbmc.sleep(5000)

        if (api_call):
            return True, api_call

        return False, False
示例#27
0
 def TextBoxes(self, anounce):
     # activate the text viewer window
     xbmc.executebuiltin( "ActivateWindow(%d)" % ( 10147, ) )
     # get window
     win = window(10147)
     #win.show()
     # give window time to initialize
     xbmc.sleep(100)
     # set heading
     win.getControl(1).setLabel("vStream mise à jour")
     win.getControl(5).setText(anounce)
     while xbmc.getCondVisibility("Window.IsActive(10147)"):
         xbmc.sleep(100)
     ret = dialog().VSok('Mise à jour terminée')
     if ret:
         xbmc.executebuiltin("Container.Refresh")
     return
示例#28
0
    def __getMediaLinkForGuest(self):

        api_call = self.__sUrl
        #full moviz lien direct final nowvideo
        if 'zerocdn.to' in api_call:
            UA = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'
            api_call = api_call + '|User-Agent=' + UA

        #Special pour mangacity
        if 'pixsil' in api_call:
            api_call = api_call.split('|')[0] + '|Referer=http://www.mangacity.org/jwplayer/player.swf'

        #Modif pr aliez
        if 'aplayer1.me' in api_call:
            UA = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0'
            api_call = api_call + '|User-Agent=' + UA

        if 'sport7' in api_call:
            UA= 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0'
            api_call = api_call + '|User-Agent=' + UA + '&referer=' + self.__sUrl

        #Special pour hd-stream.in et film-streaming.co
        if 'playlist.m3u8' in api_call:
            base = re.sub(r'(playlist.m3u8*.+)', '', api_call)
            oRequest = cRequestHandler(api_call)
            sHtmlContent = oRequest.request()
            sPattern =  ',NAME="([^"]+)".+?(chunklist.+?.m3u8)'
            oParser = cParser()
            aResult = oParser.parse(sHtmlContent, sPattern)
            if (aResult[0] == True):
                #initialisation des tableaux
                url=[]
                qua=[]
                api_call = ''
                #Remplissage des tableaux
                for i in aResult[1]:
                    url.append(str(i[1]))
                    qua.append(str(i[0]))

                #Affichage du tableau
                api_call = dialog().VSselectqual(qua, url)

        if (api_call):
            return True, api_call

        return False, False
def DecryptDlProtecte(url):

    VSlog('DecryptDlProtecte : ' + url)
    dialogs = dialog()

    if not (url):
        return ''
    #VSlog(url)

    # 1ere Requete pour recuperer le cookie
    oRequestHandler = cRequestHandler(url)
    oRequestHandler.addHeaderEntry('User-Agent', UA)
    sHtmlContent = oRequestHandler.request()

    cookies = GestionCookie().Readcookie('www_dl-protect1_com')
    #VSlog( 'cookie'  + str(cookies))

    #Tout ca a virer et utiliser oRequestHandler.addMultipartFiled('sess_id':sId,'upload_type':'url','srv_tmp_url':sTmp) quand ca marchera
    import string
    _BOUNDARY_CHARS = string.digits
    boundary = ''.join(random.choice(_BOUNDARY_CHARS) for i in range(15))
    multipart_form_data = {'submit':'continuer','submit':'Continuer'}
    data, headersMulti = encode_multipart(multipart_form_data, {}, boundary)

    #2 eme requete pour avoir le lien
    oRequestHandler = cRequestHandler(url)
    oRequestHandler.setRequestType(1)
    oRequestHandler.addHeaderEntry('Host', 'www.dl-protect1.com')
    oRequestHandler.addHeaderEntry('Referer', url)
    oRequestHandler.addHeaderEntry('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
    oRequestHandler.addHeaderEntry('User-Agent', UA)
    oRequestHandler.addHeaderEntry('Accept-Language', 'fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3')
    oRequestHandler.addHeaderEntry('Content-Length', headersMulti['Content-Length'])
    oRequestHandler.addHeaderEntry('Content-Type', headersMulti['Content-Type'])
    oRequestHandler.addHeaderEntry('Cookie', cookies)
    oRequestHandler.addHeaderEntry('Accept-Encoding', 'gzip, deflate')

    oRequestHandler.addParametersLine(data)

    sHtmlContent = oRequestHandler.request()

    #fh = open('d:\\test.txt', "w")
    #fh.write(sHtmlContent)
    #fh.close()

    return sHtmlContent
def getContext():
    addons = addon()
    dialogs = dialog()

    tmdb_account = addons.getSetting('tmdb_account')

    if tmdb_account == "":
        dialogs.VSerror(addons.VSlang(30442))
        return False, False, False

    disp = []
    lang = []
    fow = []
    yn  = []

    disp.append('vote')
    fow.append('vote')
    yn.append(True)
    lang.append(addons.VSlang(30443))

    disp.append('account/%s/watchlist' % tmdb_account)
    fow.append('watchlist')
    yn.append(True)
    lang.append(addons.VSlang(30444))

    disp.append('account/%s/favorite' % tmdb_account)
    fow.append('favorite')
    yn.append(True)
    lang.append(addons.VSlang(30445))

    disp.append('account/%s/watchlist' % tmdb_account)
    fow.append('watchlist')
    yn.append(False)
    lang.append(addons.VSlang(30446))

    disp.append('account/%s/favorite' % tmdb_account)
    fow.append('favorite')
    yn.append(False)
    lang.append(addons.VSlang(30447))


    ret = dialogs.select('TMDB',lang)

    if ret > -1:
        return disp[ret], fow[ret], yn[ret]
    return False
class cPremiumHandler:
    ADDON = addon()
    DIALOG = dialog()

    def __init__(self, sHosterIdentifier):
        self.__sHosterIdentifier = sHosterIdentifier.lower()
        self.__sDisplayName = 'Premium mode'
        self.isLogin = False
        self.__LoginTry = False
        self.__ssl = False

        self.__Ispremium = False
        bIsPremium = self.ADDON.getSetting('hoster_' +
                                           str(self.__sHosterIdentifier) +
                                           '_premium')
        if (bIsPremium == 'true'):
            VSlog("Utilise compte premium pour hoster " +
                  str(self.__sHosterIdentifier))
            self.__Ispremium = True
        else:
            VSlog("Utilise compte gratuit pour hoster: " +
                  str(self.__sHosterIdentifier))

    def isPremiumModeAvailable(self):
        return self.__Ispremium

    def getUsername(self):
        sUsername = self.ADDON.getSetting('hoster_' +
                                          str(self.__sHosterIdentifier) +
                                          '_username')
        return sUsername

    def getPassword(self):
        sPassword = self.ADDON.getSetting('hoster_' +
                                          str(self.__sHosterIdentifier) +
                                          '_password')
        return sPassword

    def AddCookies(self):
        cookies = GestionCookie().Readcookie(self.__sHosterIdentifier)
        return 'Cookie=' + cookies

    def Checklogged(self, code):
        if 'uptobox' in self.__sHosterIdentifier:
            if '//uptobox.com/?op=logout&' in code or 'Success' in code:
                return True

        if 'onefichier' in self.__sHosterIdentifier:
            if 'premium' in code or 'jqueryFileTree' in code or '1fichier.com/logout' in code:  # test ok mais pas convaincu....
                return True

        return False

    def CheckCookie(self):
        cookies = GestionCookie().Readcookie(self.__sHosterIdentifier)
        if cookies != '':
            return True
        return False

    def Authentificate(self):

        # un seul essais par session, pas besoin de bombarder le serveur
        if self.__LoginTry:
            return False
        self.__LoginTry = True

        if not self.__Ispremium:
            return False

        post_data = {}

        if 'uptobox' in self.__sHosterIdentifier:
            url = 'https://uptobox.com/?op=login&referer=homepage'
            post_data['login'] = self.getUsername()
            post_data['password'] = self.getPassword()

        elif 'onefichier' in self.__sHosterIdentifier:
            url = 'https://1fichier.com/login.pl'
            post_data['mail'] = self.getUsername()
            post_data['pass'] = self.getPassword()
            post_data['lt'] = 'on'
            post_data['purge'] = 'on'
            post_data['valider'] = 'Send'

        elif 'uploaded' in self.__sHosterIdentifier:
            url = 'http://uploaded.net/io/login'
            post_data['id'] = self.getUsername()
            post_data['pw'] = self.getPassword()

        # si aucun de trouve on retourne
        else:
            return False

        oRequestHandler = cRequestHandler(url)
        oRequestHandler.setRequestType(1)

        if 'uptobox' in self.__sHosterIdentifier:
            oRequestHandler.disableRedirect()

            oRequestHandler.addHeaderEntry('User-Agent', UA)
            oRequestHandler.addHeaderEntry(
                'Content-Type', "application/x-www-form-urlencoded")
            oRequestHandler.addHeaderEntry('Referer', url)
            oRequestHandler.addHeaderEntry('Content-Length',
                                           str(len(post_data)))

        for data in post_data:
            oRequestHandler.addParameters(data, post_data[data])

        sHtmlContent = oRequestHandler.request()
        head = oRequestHandler.getResponseHeader()

        if 'uptobox' in self.__sHosterIdentifier:
            if 'xfss' in head['Set-Cookie']:
                self.isLogin = True
            else:
                self.DIALOG.VSinfo('Authentification rate',
                                   self.__sDisplayName)
                return False
        elif 'onefichier' in self.__sHosterIdentifier:
            if 'You are logged in. This page will redirect you.' in sHtmlContent:
                self.isLogin = True
            else:
                self.DIALOG.VSinfo('Authentification rate',
                                   self.__sDisplayName)
                return False
        elif 'uploaded' in self.__sHosterIdentifier:
            if sHtmlContent == '':
                self.isLogin = True
            else:
                self.DIALOG.VSinfo('Authentification rate',
                                   self.__sDisplayName)
                return False
        else:
            return False

        # get cookie
        cookies = ''
        if 'Set-Cookie' in head:
            oParser = cParser()
            sPattern = '(?:^|,) *([^;,]+?)=([^;,\/]+?);'
            aResult = oParser.parse(str(head['Set-Cookie']), sPattern)
            # print(aResult)
            if (aResult[0] == True):
                for cook in aResult[1]:
                    if 'deleted' in cook[1]:
                        continue
                    cookies = cookies + cook[0] + '=' + cook[1] + ';'

        # save cookie
        GestionCookie().SaveCookie(self.__sHosterIdentifier, cookies)

        self.DIALOG.VSinfo('Authentification reussie', self.__sDisplayName)
        VSlog('Auhentification reussie')

        return True

    def GetHtmlwithcookies(self, url, data, cookies):
        oRequestHandler = cRequestHandler(url)
        oRequestHandler.addHeaderEntry('User-Agent', UA)
        if not (data == None):
            oRequestHandler.addParametersLine(data)
            oRequestHandler.addHeaderEntry('Referer', url)

        oRequestHandler.addHeaderEntry('Cookie', cookies)

        sHtmlContent = oRequestHandler.request()
        return sHtmlContent

    def GetHtml(self, url, data=None):
        cookies = GestionCookie().Readcookie(self.__sHosterIdentifier)

        # aucun ne marche sans cookies
        if (cookies == '') and not self.__LoginTry and self.__Ispremium:
            self.Authentificate()
            if not self.isLogin:
                return ''
            cookies = GestionCookie().Readcookie(self.__sHosterIdentifier)

        sHtmlContent = self.GetHtmlwithcookies(url, data, cookies)

        # Les cookies ne sont plus valables, mais on teste QUE si la personne n'a pas essaye de s'authentifier
        if not self.Checklogged(
                sHtmlContent) and not self.__LoginTry and self.__Ispremium:
            VSlog('Cookies non valables')
            self.Authentificate()
            if self.isLogin:
                cookies = GestionCookie().Readcookie(self.__sHosterIdentifier)
                sHtmlContent = self.GetHtmlwithcookies(url, data, cookies)
            else:
                return ''

        return sHtmlContent

    def setToken(self, sToken):
        self.ADDON.setSetting(
            'hoster_' + str(self.__sHosterIdentifier) + '_token', sToken)

    def getToken(self):

        # pas de premium, pas de token
        if not self.__Ispremium:
            return None

        # le token est connu, on le retourne
        sToken = self.ADDON.getSetting('hoster_' +
                                       str(self.__sHosterIdentifier) +
                                       '_token')
        if sToken:
            return sToken

        # token alldebrid était connu avec un aute setting
        if 'alldebrid' in self.__sHosterIdentifier:
            sToken = self.ADDON.getSetting(
                'token_alldebrid'
            )  # ancien nom, à supprimer après quelques temps
            if sToken:
                self.ADDON.setSetting(
                    'hoster_' + str(self.__sHosterIdentifier) + '_token',
                    sToken)
            return sToken

        # Si pas de token pour uptobox, on le récupère depuis le compte
        if 'uptobox' in self.__sHosterIdentifier:

            if not self.isLogin:
                self.Authentificate()

            # on retrouve le token et on le sauvegarde
            if self.isLogin:
                sHtmlContent = self.GetHtml('https://uptobox.com/my_account')
                sPattern = 'Token:.+?<span class=\'none\'>(.+?)</span>'
                aResult = cParser().parse(sHtmlContent, sPattern, 1)
                if aResult[0]:
                    sToken = aResult[1][0]
                    self.ADDON.setSetting(
                        'hoster_' + str(self.__sHosterIdentifier) + '_token',
                        sToken)
                    return sToken

        return None
示例#32
0
class cViewing:

    DIALOG = dialog()
    ADDON = addon()

    # Suppression d'un bookmark, d'une catégorie, ou tous les bookmarks
    def delViewing(self):
        oInputParameterHandler = cInputParameterHandler()
        sTitleWatched = oInputParameterHandler.getValue('sTitleWatched')
        sCat = oInputParameterHandler.getValue('sCat')

        if not sTitleWatched:    # confirmation if delete ALL
            if not self.DIALOG.VSyesno(self.ADDON.VSlang(30456)):
                return False

        meta = {}
        meta['titleWatched'] = sTitleWatched
        meta['cat'] = sCat


        if cDb().del_viewing(meta):
            self.DIALOG.VSinfo(addon().VSlang(30072))
            cGui().updateDirectory()
        return True

    # Suppression d'un bookmark depuis un Widget
    def delViewingMenu(self):
        sTitle = xbmc.getInfoLabel('ListItem.OriginalTitle')
        if not sTitle:    # confirmation if delete ALL
            if not self.DIALOG.VSyesno(self.ADDON.VSlang(30456)):
                return False
        sCat = xbmc.getInfoLabel('ListItem.Property(sCat)')
        meta = {}
        meta['titleWatched'] = sTitle
        meta['cat'] = sCat
        if cDb().del_viewing(meta):
            self.DIALOG.VSinfo(addon().VSlang(30072))
            cGui().updateDirectory()

        return True

    def getViewing(self):
        oGui = cGui()
        DB = cDb()
        oInputParameterHandler = cInputParameterHandler()

        row = DB.get_viewing()
        if not row:
            oGui.setEndOfDirectory()
            return

        for data in row:

            try:
                title = data['title'].encode('utf-8')
            except:
                title = data['title']

            try:
                try:
                    siteurl = data['siteurl'].encode('utf-8')
                except:
                    siteurl = data['siteurl']

                if isMatrix():
                    siteurl = UnquotePlus(siteurl.decode('utf-8'))
                    title = str(title, 'utf-8')
                else:
                    siteurl = UnquotePlus(siteurl)

                sTitleWatched = data['title_id']
                site = data['site']
                function = data['fav']
                cat = data['cat']
                sSeason = data['season']
                sTmdbId = data['tmdb_id']# if 'tmdb_id' in data else None

                oOutputParameterHandler = cOutputParameterHandler()
                oOutputParameterHandler.addParameter('siteUrl', siteurl)
                oOutputParameterHandler.addParameter('sMovieTitle', title)
                oOutputParameterHandler.addParameter('sTmdbId', sTmdbId)
                oOutputParameterHandler.addParameter('sTitleWatched', sTitleWatched)
                oOutputParameterHandler.addParameter('sSeason', sSeason)
                oOutputParameterHandler.addParameter('sCat', cat)
                oOutputParameterHandler.addParameter('isViewing', True)

                # pourcentage de lecture
                meta = {}
                meta['title'] = sTitleWatched
                resumetime, totaltime = DB.get_resume(meta)
                oOutputParameterHandler.addParameter('ResumeTime', resumetime)
                oOutputParameterHandler.addParameter('TotalTime', totaltime)
                
                if cat=='1':
                    oListItem = oGui.addMovie(site, function, title, 'films.png', '', title, oOutputParameterHandler)
                elif cat=='5':
                    oListItem = oGui.addMisc(site, function, title, 'films.png', '', title, oOutputParameterHandler)
                elif cat=='4':
                    oListItem = oGui.addSeason(site, function, title, 'series.png', '', title, oOutputParameterHandler)
                else:
                    oListItem = oGui.addTV(site, function, title, 'series.png', '', title, oOutputParameterHandler)

                oOutputParameterHandler.addParameter('sTitleWatched', sTitleWatched)
                oOutputParameterHandler.addParameter('sCat', cat)
                oListItem.addMenu(SITE_IDENTIFIER, 'delViewing', self.ADDON.VSlang(30412), oOutputParameterHandler)

            except Exception as e:
                pass
        
        # Vider toute la catégorie n'est pas accessible lors de l'utilisation en Widget
        if not xbmc.getCondVisibility('Window.IsActive(home)'):
            oOutputParameterHandler = cOutputParameterHandler()
            oGui.addDir(SITE_IDENTIFIER, 'delViewing', self.ADDON.VSlang(30211), 'trash.png', oOutputParameterHandler)

        oGui.setEndOfDirectory()

        return
示例#33
0
    def __getMediaLinkForGuest(self):

        api_call = ''
        url = self.__sUrl

        pathfile = 'special://temp/video_pstream.m3u8'
        if not isMatrix():
            video_pstream_path = VSPath(pathfile).decode('utf-8')
        else:
            video_pstream_path = VSPath(pathfile)

        oRequest = cRequestHandler(url)
        oRequest.addHeaderEntry(
            'Accept',
            'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
        oRequest.addHeaderEntry('Accept-Language',
                                'fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3')
        sHtmlContent = oRequest.request()

        oParser = cParser()
        sPattern = "playerBrand.+?var.+?\'([^\']+)"
        aResult = oParser.parse(sHtmlContent, sPattern)
        if (aResult[0] == True):
            url2 = aResult[1][0]

            oRequest = cRequestHandler(url2)
            oRequest.addHeaderEntry(
                'Accept',
                'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
            )
            oRequest.addHeaderEntry('Accept-Language',
                                    'fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3')
            sHtmlContent = oRequest.request()

            sPattern = "NAME=.([^\"']+).+?https([^#]+)"
            aResult = oParser.parse(sHtmlContent, sPattern)
            if (aResult[0] == True):
                url = []
                qua = []
                for aEntry in aResult[1]:
                    urls = 'https' + aEntry[1].strip()
                    qua.append(aEntry[0])
                    url.append(urls.strip())

                sUrlselect = dialog().VSselectqual(qua, url)

                sUrlselect = sUrlselect.strip()
                oRequest = cRequestHandler(sUrlselect)
                oRequest.addHeaderEntry(
                    'Accept',
                    'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
                )
                oRequest.addHeaderEntry('Accept-Language',
                                        'fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3')
                sHtmlContent = oRequest.request()

                if '#EXT' not in sHtmlContent:
                    return False, False

                with open(video_pstream_path, "w") as subfile:
                    subfile.write(sHtmlContent)

                api_call = video_pstream_path

        if (api_call):
            return True, api_call

        return False, False
示例#34
0
def WindowsBoxes(sTitle, sFileName, metaType, year=''):

    ADDON = addon()
    DIALOG = dialog()

    # Presence de l'addon ExtendedInfo?
    try:
        if (addon('script.extendedinfo')
                and ADDON.getSetting('extendedinfo-view') == 'true'):
            if metaType == '2':
                DIALOG.VSinfo('Lancement de ExtendInfo')
                xbmc.executebuiltin(
                    'RunScript(script.extendedinfo, info=extendedtvinfo, name=%s)'
                    % sFileName)
                return
            elif metaType == '1':
                DIALOG.VSinfo('Lancement de ExtendInfo')
                xbmc.executebuiltin(
                    'RunScript(script.extendedinfo, info=extendedinfo, name=%s)'
                    % sFileName)
                return
    except:
        pass

    # Sinon on gere par vStream via la lib TMDB
    sType = str(metaType).replace('1', 'movie').replace('2', 'tvshow').replace(
        '3', 'collection').replace('4', 'anime')

    try:
        meta = cTMDb().get_meta(
            sType,
            sFileName,
            tmdb_id=xbmc.getInfoLabel('ListItem.Property(TmdbId)'),
            year=year)
        try:
            meta['plot'] = str(meta['plot'].encode('latin-1'), 'utf-8')
        except:
            pass
    except:
        DIALOG.VSok(
            "Veuillez vider le cache des métadonnées Paramètre - outils - 'vider le cache de vStream'"
        )
        pass

    # si rien ne marche
    if (not meta['imdb_id'] and not meta['tmdb_id'] and not meta['tvdb_id']):
        # dialog par defaut
        # xbmc.executebuiltin('Action(Info)')
        # fenetre d'erreur
        DIALOG.VSinfo(ADDON.VSlang(30204))
        return

    # convertion de la date au format JJ/MM/AAAA
    if 'premiered' in meta and meta['premiered']:
        releaseDate = datetime(
            *(time.strptime(meta['premiered'], '%Y-%m-%d')[0:6]))
        meta['releaseDate'] = releaseDate.strftime('%d/%m/%Y')
    else:
        meta['releaseDate'] = '-'

    # convertion de la durée en secondes -> heure:minutes
    if 'duration' in meta and meta['duration']:
        duration = meta['duration'] / 60  # En minutes
        durationH = duration / 60  # Nombre d'heures
        meta['durationH'] = durationH
        #Le resultat doit obligatoirement etre un int sous Py3.
        meta['durationM'] = '{:02d}'.format(int(duration - 60 * durationH))
    else:
        meta['durationH'] = 0
        meta['durationM'] = 0

    # affichage du dialog perso
    class XMLDialog(xbmcgui.WindowXMLDialog):

        ADDON = addon()
        """
        Dialog class that asks user about rating of movie.
        """
        def __init__(self, *args, **kwargs):
            xbmcgui.WindowXMLDialog.__init__(self)
            pass

        # def message(self, message):
        # """
        # Shows xbmc dialog with OK and message.
        # """
        # dialog = xbmcgui.Dialog()
        # dialog.ok(' My message title', message)
        # self.close()

        def onInit(self):
            # par default le resumer#
            color = ADDON.getSetting('deco_color')
            self.setProperty('color', color)
            self.poster = 'https://image.tmdb.org/t/p/%s' % self.ADDON.getSetting(
                'poster_tmdb')
            self.none_poster = 'https://eu.ui-avatars.com/api/?background=000&size=512&name=%s&color=FFF&font-size=0.33'

            #self.getControl(50).setVisible(False)
            #self.getControl(90).setVisible(False)
            #self.getControl(5200).setVisible(False)
            #self.getControl(52100).setVisible(False)
            #self.getControl(52200).setVisible(False)
            # synopsis_first
            self.setFocusId(9000)

            #            self.getControl(50).reset()

            if 'credits' in meta and meta['credits']:
                cast = []
                crew = []

                #Decodage python 3
                try:
                    data = eval(str(meta['credits'].encode('latin-1'),
                                    'utf-8'))
                except:
                    data = eval(str(meta['credits']))

                try:
                    listitems = []
                    for i in data['cast']:
                        slabel = i['name']
                        slabel2 = i['character']
                        if i['profile_path']:
                            sicon = self.poster + str(i['profile_path'])
                        else:
                            sicon = self.none_poster % slabel
                        sid = i['id']
                        listitem_ = listitem(label=slabel, label2=slabel2)
                        listitem_.setProperty('id', str(sid))
                        listitem_.setArt({'icon': sicon})
                        listitems.append(listitem_)
                        cast.append(slabel.encode('ascii', 'ignore'))
                    self.getControl(50).addItems(listitems)
                except:
                    pass

                try:
                    listitems2 = []
                    for i in data['crew']:
                        slabel = i['name']
                        slabel2 = i['job']
                        if i['profile_path']:
                            sicon = self.poster + str(i['profile_path'])
                        else:
                            sicon = self.none_poster % slabel
                        sid = i['id']
                        listitem_ = listitem(label=slabel, label2=slabel2)
                        listitem_.setProperty('id', str(sid))
                        listitem_.setArt({'icon': sicon})
                        listitems2.append(listitem_)
                        crew.append(slabel.encode('ascii', 'ignore'))
                    self.getControl(5200).addItems(listitems2)
                except:
                    pass

            # try:
            #     for slabel, slabel2, sicon, sid in meta['cast']:
            #         listitem_ = listitem(label=slabel, label2=slabel2, iconImage=sicon)
            #         listitem_.setProperty('id', str(sid))
            #         listitems.append(listitem_)
            #         cast.append(slabel.encode('ascii', 'ignore'))
            #     self.getControl(50).addItems(listitems)
            #     #self.setProperty('ListItem.casting', str(cast))
            # except:
            #     pass

            # title
            # self.getControl(1).setLabel(meta['title'])
            meta['title'] = sTitle

            # self.getControl(49).setVisible(True)
            # self.getControl(2).setImage(meta['cover_url'])
            # self.getControl(3).setLabel(meta['rating'])

            if 'rating' not in meta or meta['rating'] == 0:
                meta['rating'] = '-'
            if 'votes' not in meta or meta['votes'] == '0':
                meta['votes'] = '-'

            for prop in meta:
                #Py3 unicode == str.
                try:
                    if isinstance(meta[prop], unicode):
                        self.setProperty(prop, meta[prop].encode('utf-8'))
                    else:
                        self.setProperty(prop, str(meta[prop]))
                except:
                    if isinstance(meta[prop], str):
                        self.setProperty(prop, meta[prop].encode('utf-8'))
                    else:
                        self.setProperty(prop, str(meta[prop]))

        def credit(self, meta='', control=''):
            #self.getControl(control).reset()
            listitems = []

            if not meta:
                meta = [{
                    u'id': 0,
                    u'title': u'Aucune information',
                    u'poster_path': u'',
                    u'vote_average': 0
                }]

            try:
                for i in meta:
                    try:
                        sTitle = unicodedata.normalize('NFKD',
                                                       i['title']).encode(
                                                           'ascii', 'ignore')
                    except:
                        sTitle = 'Aucune information'

                    if i['poster_path']:
                        sThumbnail = self.poster + str(i['poster_path'])
                    else:
                        sThumbnail = self.none_poster % sTitle

                    # sId = i['id']

                    listitem_ = listitem(label=sTitle)
                    try:
                        listitem_.setInfo(
                            'video',
                            {'rating': i['vote_average'].encode('utf-8')})
                    except:
                        listitem_.setInfo('video',
                                          {'rating': str(i['vote_average'])})

                    listitem_.setArt({'icon': sThumbnail})
                    listitems.append(listitem_)
                self.getControl(control).addItems(listitems)

            except:
                pass

            #self.getControl(52100).setVisible(False)
            #self.getControl(52200).setVisible(True)
            #self.setFocusId(5205)
            # self.setFocus(self.getControl(5200))

        def onClick(self, controlId):

            if controlId == 11:
                from resources.lib.ba import cShowBA
                cBA = cShowBA()
                cBA.SetSearch(sFileName)
                cBA.SetYear(year)
                cBA.SetTrailerUrl(self.getProperty('trailer'))
                cBA.SearchBA(True)
                return

            elif controlId == 30:
                self.close()
                return

            elif controlId == 50 or controlId == 5200:
                # print(self.getControl(50).ListItem.Property('id'))
                item = self.getControl(controlId).getSelectedItem()
                sid = item.getProperty('id')

                grab = cTMDb()
                sUrl = 'person/' + str(sid)

                try:
                    meta = grab.getUrl(
                        sUrl, '',
                        "append_to_response=movie_credits,tv_credits")
                    meta_credits = meta['movie_credits']['cast']
                    self.credit(meta_credits, 5215)

                    try:
                        sTitle = unicodedata.normalize('NFKD',
                                                       meta['name']).encode(
                                                           'ascii', 'ignore')
                    except:
                        sTitle = 'Aucune information'

                    if not meta['deathday']:
                        today = date.today()
                        try:
                            birthday = datetime(*(time.strptime(
                                meta['birthday'], '%Y-%m-%d')[0:6]))
                            age = today.year - birthday.year - (
                                (today.month, today.day) <
                                (birthday.month, birthday.day))
                            age = '%s Ans' % age
                        except:
                            age = ''
                    else:
                        age = meta['deathday']

                    self.setProperty('Person_name', sTitle)
                    self.setProperty('Person_birthday', meta['birthday'])
                    self.setProperty('Person_place_of_birth',
                                     meta['place_of_birth'])
                    self.setProperty('Person_deathday', str(age))
                    self.setProperty('Person_biography', meta['biography'])
                    self.setFocusId(9000)

                except:
                    return
                # self.getControl(50).setVisible(True)
                self.setProperty('vstream_menu', 'Person')

            # click sur similaire
            elif controlId == 9:
                # print(self.getControl(9000).ListItem.tmdb_id)
                sid = self.getProperty('tmdb_id')

                grab = cTMDb()
                sUrl_simil = 'movie/%s/similar' % str(sid)
                sUrl_recom = 'movie/%s/recommendations' % str(sid)

                try:
                    meta = grab.getUrl(sUrl_simil)
                    meta = meta['results']
                    self.credit(meta, 5205)
                except:
                    pass
                try:
                    meta = grab.getUrl(sUrl_recom)
                    meta = meta['results']
                    self.credit(meta, 5210)
                except:
                    return

            # click pour recherche
            elif controlId == 5215 or controlId == 5205 or controlId == 5210:

                import sys
                from resources.lib.util import cUtil
                item = self.getControl(controlId).getSelectedItem()
                sTitle = item.getLabel()

                try:
                    sTitle = sTitle.encode('utf-8')
                    sTitle = cUtil().CleanName(sTitle)
                except:
                    return

                self.close()

                # Si lancé depuis la page Home de Kodi, il faut d'abord en sortir pour lancer la recherche
                if xbmc.getCondVisibility('Window.IsVisible(home)'):
                    xbmc.executebuiltin('ActivateWindow(%d)' % (10028))

                sTest = '%s?site=globalSearch&searchtext=%s&sCat=1' % (
                    sys.argv[0], sTitle)
                xbmc.executebuiltin('Container.Update(%s)' % sTest)
                return
            # elif controlId == 2:
            #     print("paseeeee")
            #     xbmc.executebuiltin('Dialog.Close(all, force)')
            #     xbmc.executebuiltin('ActivateWindow(12005)')
            #     return

        def onFocus(self, controlId):
            self.controlId = controlId
            #fullscreen end return focus menu
            if controlId == 40:
                while xbmc.Player().isPlaying():
                    xbmc.sleep(500)
                    if not xbmc.Player().isPlaying():
                        self.setFocusId(9000)

            #if controlId != 5200:
            # self.getControl(5500).reset()
            #  self.getControl(5200).setVisible(False)
            # if controlId == 50:
            # item = self.getControl(50).getSelectedItem()
            # sid = item.getProperty('id')

        def _close_dialog(self):
            self.close()

        def onAction(self, action):
            if action.getId() in (104, 105, 1, 2):
                return

            if action.getId() in (9, 10, 11, 30, 92, 216, 247, 257, 275, 61467,
                                  61448):
                self.close()

    path = 'special://home/addons/plugin.video.mando'
    # self.__oPath.decode('utf-8')
    wd = XMLDialog('DialogInfo4.xml', path, 'default', '720p')
    wd.doModal()
    del wd
示例#35
0
    def checkdownload(self):

        addons = addon()
        dialogs = dialog()
        if dialogs.VSyesno("Êtes-vous sûr ?"):

            service_futur = addons.getSetting('service_futur')
            service_version = addons.getSetting('service_version')

            #result = self.resultGit()
            sUrl = 'https://api.github.com/repos/Kodi-vStream/venom-xbmc-addons/compare/%s...%s' % (
                service_version, service_futur)
            #sUrl = 'https://api.github.com/repos/Kodi-vStream/venom-xbmc-addons/compare/0.6.3...0.6.31'

            oRequestHandler = cRequestHandler(sUrl)
            sHtmlContent = oRequestHandler.request()
            result = json.loads(sHtmlContent)

            total = len(result['files'])
            progress_ = progress()
            progress_.VScreate('Update')

            addons = addon()
            site = ''
            sdown = 0
            schange = 0
            text = ''

            if result:

                #boucle download fichier
                for i in result['files']:

                    if 'plugin.video.vstream' in i['filename']:
                        progress_.VSupdate(progress_, total)

                        rootpath = self.getRootPath(i['filename'])

                        try:
                            self.__download(i['raw_url'], rootpath)
                            #site += "[COLOR green]"+i['filename'].encode("utf-8")+"[/COLOR][CR]"
                            site += "Add: [B]%s[/B] | Del: [B]%s[/B] | [COLOR green]%s[/COLOR][CR]" % (
                                i['additions'], i['deletions'],
                                i['filename'].encode("utf-8"))
                            sdown = sdown + 1
                            schange += i['changes']
                        except:
                            site += "[COLOR red]" + i['filename'].encode(
                                "utf-8") + "[/COLOR][CR]"
                            sdown = sdown + 1
                            pass

                progress_.VSclose(progress_)

                #boucle commit
                for i in result['commits']:
                    try:
                        text += "[B]%s[/B]: %s[CR]" % (
                            i['commit']['author']['name'],
                            i['commit']['message'].encode("utf-8"))
                    except:
                        text += "[B]%s[/B]: nop[CR]" % (
                            i['commit']['author']['name'])
                        pass

                sContent = "Changement (%s) | Fichier mise à jour %s / %s [CR]" % (
                    schange, sdown, total)
                sContent += "%s" % (text.encode("utf-8"))
                sContent += "%s" % (site)

                addons.setSetting('service_time', str(datetime.datetime.now()))
                addons.setSetting('service_version', str(service_futur))
                addons.setSetting('home_update', str('false'))

                #fin = dialog().VSok(sContent)
                fin = self.TextBoxes(sContent)
        return
示例#36
0
class cClear:

    DIALOG = dialog()
    ADDON = addon()

    def __init__(self):
        self.main(sys.argv[1])
        #self.__sFunctionName = ''

    def main(self, env):

        if (env == 'urlresolver'):
            addon('script.module.urlresolver').openSettings()
            return

        elif (env == 'metahandler'):
            addon('script.module.metahandler').openSettings()
            return

        elif (env == 'changelog'):
            try:
                sUrl = 'https://raw.githubusercontent.com/Kodi-vStream/venom-xbmc-addons/master/plugin.video.vstream/changelog.txt'
                oRequest = urllib2.Request(sUrl)
                oResponse = urllib2.urlopen(oRequest)
                sContent = oResponse.read()
                self.TextBoxes('vStream Changelog', sContent)
            except:
                self.DIALOG.VSerror("%s,%s" % (self.ADDON.VSlang(30205), sUrl))
            return

        elif (env == 'soutient'):
            try:
                sUrl = 'https://raw.githubusercontent.com/Kodi-vStream/venom-xbmc-addons/master/plugin.video.vstream/soutient.txt'
                oRequest = urllib2.Request(sUrl)
                oResponse = urllib2.urlopen(oRequest)
                sContent = oResponse.read()
                self.TextBoxes('vStream Soutient', sContent)
            except:
                self.DIALOG.VSerror("%s,%s" % (self.ADDON.VSlang(30205), sUrl))
            return

        elif (env == 'addon'):
            if self.DIALOG.VSyesno("Êtes-vous sûr ?"):
                #cached_Cache = cConfig().getFileCache()
                #cached_Cache = xbmc.translatePath(cached_Cache).decode("utf-8")
                cached_Cache = "special://home/userdata/addon_data/plugin.video.vstream/video_cache.db"
                #self.ClearDir2(cached_Cache,True)
                try:
                    xbmcvfs.delete(cached_Cache)
                    self.DIALOG.VSinfo(
                        'Clear Addon Cache, Successful[CR](Important relancer vStream)'
                    )
                except:
                    self.DIALOG.VSerror('Clear Addon Cache, Error')

            return

        elif (env == 'clean'):
            liste = [
                'Historiques', 'Lecture en cours', 'Marqués vues',
                'Marque-Pages', 'Téléchargements'
            ]
            ret = self.DIALOG.select('BDD à supprimer', liste)
            #cached_DB = cConfig().getFileDB()
            cached_DB = "special://home/userdata/addon_data/plugin.video.vstream/vstream.db"
            #important seul xbmcvfs peux lire le special
            cached_DB = xbmc.translatePath(cached_DB).decode("utf-8")

            sql_drop = ""

            if ret > -1:

                if ret == 0:
                    sql_drop = "DROP TABLE history"
                elif ret == 1:
                    sql_drop = "DROP TABLE resume"
                elif ret == 2:
                    sql_drop = "DROP TABLE watched"
                elif ret == 3:
                    sql_drop = "DROP TABLE favorite"
                elif ret == 4:
                    sql_drop = "DROP TABLE download"

                try:
                    db = sqlite.connect(cached_DB)
                    dbcur = db.cursor()
                    dbcur.execute(sql_drop)
                    db.commit()
                    dbcur.close()
                    db.close()
                    self.DIALOG.VSok(
                        "Suppression BDD, Successful[CR](Important relancer vStream)"
                    )
                except:
                    self.DIALOG.VSerror("Suppresion BDD, Error")

            return

        elif (env == 'xbmc'):
            if self.DIALOG.VSyesno('Êtes-vous sûr ?'):
                #temp = xbmc.translatePath('special://temp/').decode("utf-8")
                path = "special://temp/"
                #self.ClearDir(temp,True)
                try:
                    xbmcvfs.rmdir(path, True)
                    self.DIALOG.VSok(
                        'Clear Temp Cache, Successful[CR](Important relancer Kodi)'
                    )
                except:
                    self.DIALOG.VSerror('Clear Temp Cache, Error')
            return

        elif (env == 'fi'):
            if self.DIALOG.VSyesno('Êtes-vous sûr ?'):
                #path = xbmc.translatePath('special://temp/').decode("utf-8")
                path = "special://temp/archive_cache/"
                try:
                    xbmcvfs.rmdir(path, True)
                    self.DIALOG.VSok(
                        'Clear Archive_cache Cache, Successful[CR](Important relancer Kodi)'
                    )
                except:
                    self.DIALOG.VSerror('Clear Archive_cache Cache, Error')
                # filenames = next(os.walk(path))[2]
                # for i in filenames:
                #     if ".fi" in i:
                #         os.remove(os.path.join(path, i))
            return

        elif (env == 'uplog'):
            if self.DIALOG.VSyesno('Êtes-vous sûr ?'):
                #path = xbmc.translatePath('special://logpath/').decode("utf-8")
                path = "special://logpath/kodi.log"
                UA = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'
                headers = {'User-Agent': UA}
                #filenames = next(os.walk(path))[2]
                #for i in filenames:
                if xbmcvfs.exists(path):
                    post_data = {}
                    cUrl = 'http://slexy.org/index.php/submit'
                    #logop = open(path + i,'rb')
                    logop = xbmcvfs.File(path, 'rb')
                    result = logop.read()
                    logop.close()
                    post_data['raw_paste'] = result
                    post_data['author'] = 'kodi.log'
                    post_data['language'] = 'text'
                    post_data['permissions'] = 1  #private
                    post_data['expire'] = 259200  #3j
                    post_data['submit'] = 'Submit+Paste'
                    request = urllib2.Request(cUrl,
                                              urllib.urlencode(post_data),
                                              headers)
                    reponse = urllib2.urlopen(request)
                    code = reponse.geturl().replace('http://slexy.org/view/',
                                                    '')
                    reponse.close()
                    self.ADDON.setSetting('service_log', code)
                    self.DIALOG.VSok(
                        'Ce code doit être transmis lorsque vous ouvrez une issue veuillez le noter:'
                        + '  ' + code)
            return

        elif (env == 'search'):

            from resources.lib.handler.pluginHandler import cPluginHandler
            valid = '[COLOR green][x][/COLOR]'

            class XMLDialog(xbmcgui.WindowXMLDialog):

                ADDON = addon()

                def __init__(self, *args, **kwargs):
                    xbmcgui.WindowXMLDialog.__init__(self)
                    pass

                def onInit(self):

                    self.container = self.getControl(6)
                    self.button = self.getControl(5)
                    self.getControl(3).setVisible(False)
                    self.getControl(1).setLabel(self.ADDON.VSlang(30094))
                    self.button.setLabel('OK')
                    listitems = []
                    oPluginHandler = cPluginHandler()
                    aPlugins = oPluginHandler.getAllPlugins()

                    for aPlugin in aPlugins:
                        #teste si deja dans le dsip
                        sPluginSettingsName = 'plugin_' + aPlugin[1]
                        bPlugin = self.ADDON.getSetting(sPluginSettingsName)

                        #icon = os.path.join(unicode(cConfig().getRootArt(), 'utf-8'), 'sites', aPlugin[1]+'.png')
                        icon = "special://home/addons/plugin.video.vstream/resources/art/sites/%s.png" % aPlugin[
                            1]
                        stitle = aPlugin[0].replace(
                            '[COLOR violet]',
                            '').replace('[COLOR orange]',
                                        '').replace('[/COLOR]', '')
                        if (bPlugin == 'true'):
                            stitle = ('%s %s') % (stitle, valid)
                        listitem = xbmcgui.ListItem(label=stitle,
                                                    label2=aPlugin[2])
                        listitem.setArt({'icon': icon, 'thumb': icon})
                        listitem.setProperty('Addon.Summary', aPlugin[2])
                        listitem.setProperty('sitename', aPlugin[1])
                        if (bPlugin == 'true'):
                            listitem.select(True)

                        listitems.append(listitem)
                    self.container.addItems(listitems)

                    self.setFocus(self.container)

                def onClick(self, controlId):
                    if controlId == 5:
                        self.close()
                        return
                    elif controlId == 99:
                        window = xbmcgui.Window(xbmcgui.getCurrentWindowId())
                        del window
                        self.close()
                        return
                    elif controlId == 7:
                        window = xbmcgui.Window(xbmcgui.getCurrentWindowId())
                        del window
                        self.close()
                        return
                    elif controlId == 6:
                        item = self.container.getSelectedItem()
                        if item.isSelected() == True:
                            label = item.getLabel().replace(valid, '')
                            item.setLabel(label)
                            item.select(False)
                            sPluginSettingsName = ('plugin_%s') % (
                                item.getProperty('sitename'))
                            self.ADDON.setSetting(sPluginSettingsName,
                                                  str('false'))
                        else:
                            label = ('%s %s') % (item.getLabel(), valid)
                            item.setLabel(label)
                            item.select(True)
                            sPluginSettingsName = ('plugin_%s') % (
                                item.getProperty('sitename'))
                            self.ADDON.setSetting(sPluginSettingsName,
                                                  str('true'))
                        return

                def onFocus(self, controlId):
                    self.controlId = controlId

                def _close_dialog(self):
                    self.close()

                # def onAction( self, action ):
                # if action.getId() in ( 9, 10, 92, 216, 247, 257, 275, 61467, 61448, ):
                # self.close()

            #path = cConfig().getAddonPath()
            path = "special://home/addons/plugin.video.vstream"
            wd = XMLDialog('DialogSelect.xml', path, "Default")
            wd.doModal()
            del wd
            return

        elif (env == 'thumb'):

            if self.DIALOG.VSyesno(
                    'Êtes-vous sûr ? Ceci effacera toutes les thumbnails '):

                text = False
                #path = xbmc.translatePath('special://userdata/Thumbnails/').decode("utf-8")
                path = "special://userdata/Thumbnails/"
                path_DB = "special://userdata/Database"
                try:
                    xbmcvfs.rmdir(path, True)
                    text = 'Clear Thumbnail Folder, Successful[CR]'
                except:
                    text = 'Clear Thumbnail Folder, Error[CR]'
                #for i in os.listdir(path):
                # folders = os.path.join(path, i).encode('utf-8')
                # if os.path.isdir(folders):
                #     p = next(os.walk(folders))[2]
                #     for x in p:
                #         os.remove(os.path.join(folders, x).encode('utf-8'))

                #filenames = next(os.walk(path2))[2]
                folder, items = xbmcvfs.listdir(path_DB)
                items.sort()
                for sItemName in items:
                    if "extures" in sItemName:
                        cached_Cache = "/".join([path_DB, sItemName])
                        try:
                            xbmcvfs.delete(cached_Cache)
                            text += 'Clear Thumbnail DB, Successful[CR]'
                        except:
                            text += 'Clear Thumbnail DB, Error[CR]'

                if text:
                    text = "%s (Important relancer Kodi)" % text
                    self.DIALOG.VSok(text)
                # for x in filenames:
                #     if "exture" in x:
                #         con = sqlite.connect(os.path.join(path2, x).encode('utf-8'))
                #         cursor = con.cursor()
                #         cursor.execute("DELETE FROM texture")
                #         con.commit()
                #         cursor.close()
                #         con.close()
            return

        else:
            return
        return

    # def ClearDir(self, dir, clearNested = False):
    #     try:
    #         dir = dir.decode("utf8")
    #     except:
    #         pass
    #     for the_file in os.listdir(dir):
    #         file_path = os.path.join(dir, the_file).encode('utf-8')
    #         if clearNested and os.path.isdir(file_path):
    #             self.ClearDir(file_path, clearNested)
    #             try: os.rmdir(file_path)
    #             except Exception, e: print str(e)
    #         else:
    #             try:os.unlink(file_path)
    #             except Exception, e: print str(e)

    # def ClearDir2(self, dir, clearNested = False):
    #     try:
    #         dir = dir.decode("utf8")
    #     except:
    #         pass
    #     try:os.unlink(dir)
    #     except Exception, e: print str(e)

    def TextBoxes(self, heading, anounce):
        # activate the text viewer window
        xbmc.executebuiltin("ActivateWindow(%d)" % (10147, ))
        # get window
        win = window(10147)
        #win.show()
        # give window time to initialize
        xbmc.sleep(100)
        # set heading
        win.getControl(1).setLabel(heading)
        win.getControl(5).setText(anounce)
        return
示例#37
0
class cDb:

    DB = 'special://home/userdata/addon_data/plugin.video.vstream/vstream.db'
    # important seul xbmcvfs peux lire le special
    try:
        REALDB = xbmc.translatePath(DB).decode('utf-8')
    except AttributeError:
        REALDB = xbmc.translatePath(DB)

    DIALOG = dialog()
    ADDON = addon()

    def __init__(self):

        try:
            if not xbmcvfs.exists(self.DB):
                self.db = sqlite.connect(self.REALDB)
                self.db.row_factory = sqlite.Row
                self.dbcur = self.db.cursor()
                self._create_tables()
                return
        except:
            VSlog('Error: Unable to write to %s' % self.REALDB)
            pass

        try:
            self.db = sqlite.connect(self.REALDB)
            self.db.row_factory = sqlite.Row
            self.dbcur = self.db.cursor()
        except:
            VSlog('Error: Unable to access to %s' % self.REALDB)
            pass

    def __del__(self):
        ''' Cleanup db when object destroyed '''
        try:
            self.dbcur.close()
            self.db.close()
        except Exception:
            pass

    def _create_tables(self):

        # sql_create2 = 'DROP TABLE history'
        ''' Create table '''
        sql_create = "CREATE TABLE IF NOT EXISTS history ("\
                        "addon_id integer PRIMARY KEY AUTOINCREMENT, "\
                        "title TEXT, "\
                        "disp TEXT, "\
                        "icone TEXT, "\
                        "isfolder TEXT, "\
                        "level TEXT, "\
                        "lastwatched TIMESTAMP "", "\
                        "UNIQUE(title)"\
                        ");"
        self.dbcur.execute(sql_create)

        sql_create = "CREATE TABLE IF NOT EXISTS resume ("\
                        "addon_id integer PRIMARY KEY AUTOINCREMENT, "\
                        "title TEXT, "\
                        "hoster TEXT, "\
                        "point TEXT, "\
                        "UNIQUE(title, hoster)"\
                        ");"
        self.dbcur.execute(sql_create)

        sql_create = "CREATE TABLE IF NOT EXISTS watched ("\
                        "addon_id integer PRIMARY KEY AUTOINCREMENT, "\
                        "title TEXT, "\
                        "site TEXT, "\
                        "UNIQUE(title, site)"\
                        ");"
        self.dbcur.execute(sql_create)

        sql_create = "CREATE TABLE IF NOT EXISTS favorite ("\
                        "addon_id integer PRIMARY KEY AUTOINCREMENT, "\
                        "title TEXT, "\
                        "siteurl TEXT, "\
                        "site TEXT, "\
                        "fav TEXT, "\
                        "cat TEXT, "\
                        "icon TEXT, "\
                        "fanart TEXT, "\
                        "UNIQUE(title, site)"\
                        ");"
        self.dbcur.execute(sql_create)

        sql_create = "CREATE TABLE IF NOT EXISTS download ("\
                        "addon_id integer PRIMARY KEY AUTOINCREMENT, "\
                        "title TEXT, "\
                        "url TEXT, "\
                        "path TEXT, "\
                        "cat TEXT, "\
                        "icon TEXT, "\
                        "size TEXT,"\
                        "totalsize TEXT, "\
                        "status TEXT, "\
                        "UNIQUE(title, path)"\
                        ");"
        self.dbcur.execute(sql_create)

        VSlog('Table initialized')

    # Ne pas utiliser cette fonction pour les chemins
    def str_conv(self, data):
        if isinstance(data, str):
            # Must be encoded in UTF-8
            try:
                data = data.decode('utf8')
            except AttributeError:
                pass
        import unicodedata
        data = unicodedata.normalize('NFKD', data).encode('ascii', 'ignore')
        data = data.decode(
            'string-escape'
        )  # ATTENTION: provoque des bugs pour les chemins a cause du caractere '/'

        return data

    # ***********************************
    #   History fonctions
    # ***********************************

    def insert_history(self, meta):

        # title = Unquote(meta['title']).decode('ascii', 'ignore')
        title = self.str_conv(Unquote(meta['title']))
        disp = meta['disp']
        icon = 'icon.png'

        try:
            ex = 'INSERT INTO history (title, disp, icone) VALUES (?, ?, ?)'
            self.dbcur.execute(ex, (title, disp, icon))
            self.db.commit()
            VSlog('SQL INSERT history Successfully')
        except Exception as e:
            if 'UNIQUE constraint failed' in e.message:
                ex = "UPDATE history set title = '%s', disp = '%s', icone= '%s' WHERE title = '%s'" % (
                    title, disp, icon, title)
                self.dbcur.execute(ex)
                self.db.commit()
                VSlog('SQL UPDATE history Successfully')
            VSlog('SQL ERROR INSERT')
            pass

    def get_history(self):
        sql_select = 'SELECT * FROM history'

        try:
            self.dbcur.execute(sql_select)
            # matchedrow = self.dbcur.fetchone()
            matchedrow = self.dbcur.fetchall()
            return matchedrow
        except Exception:
            VSlog('SQL ERROR EXECUTE')
            return None

    def del_history(self):
        from resources.lib.gui.gui import cGui
        oGui = cGui()
        oInputParameterHandler = cInputParameterHandler()
        if oInputParameterHandler.exist('searchtext'):
            sql_delete = "DELETE FROM history WHERE title = '%s'" % (
                oInputParameterHandler.getValue('searchtext'))
        else:
            sql_delete = 'DELETE FROM history;'

        try:
            self.dbcur.execute(sql_delete)
            self.db.commit()
            self.DIALOG.VSinfo(self.ADDON.VSlang(30041))
            oGui.updateDirectory()
            return False, False
        except Exception:
            VSlog('SQL ERROR DELETE')
            return False, False

    # ***********************************
    #   Watched fonctions
    # ***********************************

    def insert_watched(self, meta):
        title = meta['title']
        if not title:
            return

        site = QuotePlus(meta['site'])
        ex = 'INSERT INTO watched (title, site) VALUES (?, ?)'
        self.dbcur.execute(ex, (title, site))
        try:
            self.db.commit()
            VSlog('SQL INSERT watched Successfully')
        except Exception:
            VSlog('SQL ERROR INSERT')
            pass

    def get_watched(self, meta):
        title = meta['title']
        if not title:
            return None

        sql_select = "SELECT * FROM watched WHERE title = '%s'" % title

        try:
            self.dbcur.execute(sql_select)
            # matchedrow = self.dbcur.fetchone()
            matchedrow = self.dbcur.fetchall()

            if matchedrow:
                return 1
            return 0
        except Exception:
            VSlog('SQL ERROR EXECUTE')
            return None

    def del_watched(self, meta):
        title = meta['title']
        if not title:
            return

        sql_select = "DELETE FROM watched WHERE title = '%s'" % title
        try:
            self.dbcur.execute(sql_select)
            self.db.commit()
            return False, False
        except Exception:
            VSlog('SQL ERROR EXECUTE')
            return False, False

    # ***********************************
    #   Resume fonctions
    # ***********************************

    def insert_resume(self, meta):
        title = self.str_conv(meta['title'])
        site = QuotePlus(meta['site'])
        # hoster = meta['hoster']
        point = meta['point']
        ex = "DELETE FROM resume WHERE hoster = '%s'" % site
        self.dbcur.execute(ex)
        ex = 'INSERT INTO resume (title, hoster, point) VALUES (?, ?, ?)'
        self.dbcur.execute(ex, (title, site, point))

        try:
            self.db.commit()
            VSlog('SQL INSERT resume Successfully')
        except Exception:
            VSlog('SQL ERROR INSERT')
            pass

    def get_resume(self, meta):
        # title = self.str_conv(meta['title'])
        site = QuotePlus(meta['site'])

        sql_select = "SELECT * FROM resume WHERE hoster = '%s'" % site

        try:
            self.dbcur.execute(sql_select)
            # matchedrow = self.dbcur.fetchone()
            matchedrow = self.dbcur.fetchall()
            return matchedrow
        except Exception:
            VSlog('SQL ERROR EXECUTE')
            return None

    def del_resume(self, meta):
        site = QuotePlus(meta['site'])

        sql_select = "DELETE FROM resume WHERE hoster = '%s'" % site

        try:
            self.dbcur.execute(sql_select)
            self.db.commit()
            return False, False
        except Exception:
            VSlog('SQL ERROR EXECUTE')
            return False, False

    # ***********************************
    #   Bookmark fonctions
    # ***********************************

    def insert_bookmark(self, meta):

        title = self.str_conv(meta['title'])
        siteurl = QuotePlus(meta['siteurl'])

        try:
            sIcon = meta['icon'].decode('UTF-8')
        except:
            sIcon = meta['icon']

        try:
            ex = 'INSERT INTO favorite (title, siteurl, site, fav, cat, icon, fanart) VALUES (?, ?, ?, ?, ?, ?, ?)'
            self.dbcur.execute(ex, (title, siteurl, meta['site'], meta['fav'],
                                    meta['cat'], sIcon, meta['fanart']))

            self.db.commit()

            self.DIALOG.VSinfo(self.ADDON.VSlang(30042), meta['title'])
            VSlog('SQL INSERT favorite Successfully')
        except Exception as e:
            if 'UNIQUE constraint failed' in e.message:
                self.DIALOG.VSinfo(self.ADDON.VSlang(30043), meta['title'])
            VSlog('SQL ERROR INSERT')
            pass

    def get_bookmark(self):

        sql_select = 'SELECT * FROM favorite'

        try:
            self.dbcur.execute(sql_select)
            # matchedrow = self.dbcur.fetchone()
            matchedrow = self.dbcur.fetchall()
            return matchedrow
        except Exception:
            VSlog('SQL ERROR EXECUTE')
            return None

    def del_bookmark(self):
        from resources.lib.gui.gui import cGui
        oGui = cGui()
        oInputParameterHandler = cInputParameterHandler()

        if oInputParameterHandler.exist('sCat'):
            sql_delete = "DELETE FROM favorite WHERE cat = '%s'" % (
                oInputParameterHandler.getValue('sCat'))

        if oInputParameterHandler.exist('sMovieTitle'):

            siteUrl = oInputParameterHandler.getValue('siteUrl')
            sMovieTitle = oInputParameterHandler.getValue('sMovieTitle')
            siteUrl = QuotePlus(siteUrl)
            title = self.str_conv(sMovieTitle)
            title = title.replace("'", r"''")
            sql_delete = "DELETE FROM favorite WHERE siteurl = '%s' AND title = '%s'" % (
                siteUrl, title)

        if oInputParameterHandler.exist('sAll'):
            sql_delete = 'DELETE FROM favorite;'

        try:
            self.dbcur.execute(sql_delete)
            self.db.commit()
            self.DIALOG.VSinfo(self.ADDON.VSlang(30044))
            oGui.updateDirectory()
            return False, False
        except Exception:
            VSlog('SQL ERROR EXECUTE')
            return False, False

    # ***********************************
    #   Download fonctions
    # ***********************************

    def insert_download(self, meta):

        title = self.str_conv(meta['title'])
        url = QuotePlus(meta['url'])
        sIcon = QuotePlus(meta['icon'])
        sPath = meta['path']

        ex = 'INSERT INTO download (title, url, path, cat, icon, size, totalsize, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
        self.dbcur.execute(ex,
                           (title, url, sPath, meta['cat'], sIcon, '', '', 0))

        try:
            self.db.commit()
            VSlog('SQL INSERT download Successfully')
            self.DIALOG.VSinfo(self.ADDON.VSlang(30042), meta['title'])
        except Exception:
            VSlog('SQL ERROR INSERT')
            pass

    def get_download(self, meta=''):

        if meta == '':
            sql_select = 'SELECT * FROM download'
        else:
            url = QuotePlus(meta['url'])
            sql_select = "SELECT * FROM download WHERE url = '%s' AND status = '0'" % url

        try:
            self.dbcur.execute(sql_select)
            matchedrow = self.dbcur.fetchall()
            return matchedrow
        except Exception:
            VSlog('SQL ERROR EXECUTE')
            return None

    def clean_download(self):

        sql_select = "DELETE FROM download WHERE status = '2'"

        try:
            self.dbcur.execute(sql_select)
            self.db.commit()
            return False, False
        except Exception:
            VSlog('SQL ERROR EXECUTE')
            return False, False

    def reset_download(self, meta):

        url = QuotePlus(meta['url'])
        sql_select = "UPDATE download SET status = '0' WHERE status = '2' AND url = '%s'" % url

        try:
            self.dbcur.execute(sql_select)
            self.db.commit()
            return False, False
        except Exception:
            VSlog('SQL ERROR EXECUTE')
            return False, False

    def del_download(self, meta):

        if len(meta['url']) > 1:
            url = QuotePlus(meta['url'])
            sql_select = "DELETE FROM download WHERE url = '%s'" % url
        elif len(meta['path']) > 1:
            path = meta['path']
            sql_select = "DELETE FROM download WHERE path = '%s'" % path
        else:
            return

        try:
            self.dbcur.execute(sql_select)
            self.db.commit()
            return False, False
        except Exception:
            VSlog('SQL ERROR EXECUTE')
            return False, False

    def cancel_download(self):
        sql_select = "UPDATE download SET status = '0' WHERE status = '1'"
        try:
            self.dbcur.execute(sql_select)
            self.db.commit()
            return False, False
        except Exception:
            VSlog('SQL ERROR EXECUTE')
            return False, False

    def update_download(self, meta):

        path = meta['path']
        size = meta['size']
        totalsize = meta['totalsize']
        status = meta['status']

        sql_select = "UPDATE download set size = '%s', totalsize = '%s', status= '%s' WHERE path = '%s'" % (
            size, totalsize, status, path)

        try:
            self.dbcur.execute(sql_select)
            self.db.commit()
            return False, False
        except Exception:
            VSlog('SQL ERROR EXECUTE')
            return False, False
示例#38
0
    def checkdownload(self):

        addons = addon()
        dialogs = dialog()
        if dialogs.VSyesno(addons.VSlang(30456)):

            service_futur = addons.getSetting('service_futur')
            service_version = addons.getSetting('service_version')
            if not service_futur:
                return self.getUpdate()
            if not service_version:
                return self.getUpdate()

            #result = self.resultGit()
            sUrl = 'https://api.github.com/repos/zombiB/zombi-addons/compare/%s...%s' % (service_version, service_futur)
            #pour test
            #sUrl = 'https://api.github.com/repos/zombiB/zombi-addons/compare/0.6.3...0.6.31'

            oRequestHandler = cRequestHandler(sUrl)
            sHtmlContent = oRequestHandler.request()
            result = json.loads(sHtmlContent)

            progress_ = progress()
            progress_.VScreate(addons.VSlang(30015))

            #site = ''
            sdown = 0
            add = 0
            dell = 0
            schange = 0
            text = ''
            listitems = []

            if result:

                #boucle download fichier
                total = len(result['files'])
                for i in result['files']:

                    if 'plugin.video.matrix' in i['filename']:
                        progress_.VSupdate(progress_, total)

                        rootpath = self.getRootPath(i['filename'])

                        try:
                            self.__download(i['raw_url'], rootpath)
                            #site += 'Add: [B]%s[/B] | Del: [B]%s[/B] | [COLOR green]%s[/COLOR][CR]' % (i['additions'], i['deletions'], i['filename'].encode('utf-8'))
                            add += i['additions']
                            dell += i['deletions']
                            sdown = sdown + 1
                            schange += i['changes']
                        except:
                            #site += "[COLOR red]" + i['filename'].encode("utf-8") + "[/COLOR][CR]"
                            sdown = sdown + 1
                            pass

                progress_.VSclose(progress_)

                #données fichiers
                sContent = 'Ajouter (%s) | Supprimer (%s) | Changement (%s) [CR]Fichiers mise à jour %s / %s' % (add, dell, schange, sdown, total)
                listitem = xbmcgui.ListItem(label = 'matrix', label2 = sContent)
                icon = 'special://home/addons/plugin.video.matrix/resources/art/update.png'
                listitem.setArt({'icon': icon, 'thumb': icon})
                listitems.append(listitem)

                #boucle commit
                for i in result['commits']:
                    try:
                        #text += '[B]%s[/B]: %s[CR]' % (i['commit']['author']['name'], i['commit']['message'].encode('utf-8'))
                        icon = i['author']['avatar_url']
                        login = i['author']['login']
                        desc = i['commit']['message'].encode('utf-8')
                        listitem = xbmcgui.ListItem(label = login, label2 = desc)
                        listitem.setArt({'icon': icon, 'thumb': icon})
                    except:
                        #text += '[B]%s[/B]: nop[CR]' % (i['commit']['author']['name'])
                        listitem = xbmcgui.ListItem(label = 'None', label2 = 'none')
                        pass
                    listitems.append(listitem)

                #sContent = 'Changement (%s) | Fichiers mise à jour %s / %s [CR]' % (schange, sdown, total)
                #sContent += '%s' %  (text.encode('utf-8'))
                #sContent += '%s' %  (site)

                addons.setSetting('service_time', str(datetime.datetime.now()))
                addons.setSetting('service_version', str(service_futur))
                addons.setSetting('home_update', str('false'))

                #fin = dialog().VSok(sContent)
                #fin = self.TextBoxes(sContent)
                fin = self.Box(listitems)
        return
示例#39
0
def showCensure():

    content = "Pour activer le contenu (+18) mettre: \n[COLOR coral]SPION_CENSURE = False[/COLOR]\ndans le fichier:\n[COLOR coral]plugin.video.vstream/resources/sites/spion_com.py[/COLOR]"
    dialog().VSok(content)
def showAllPlaylist():  #On recupere les differentes playlist si il y en a
    oGui = cGui()

    oInputParameterHandler = cInputParameterHandler()
    sUrl = oInputParameterHandler.getValue('siteUrl')
    sTitle = oInputParameterHandler.getValue('sMovieTitle')
    sThumb = oInputParameterHandler.getValue('sThumbnail')
    sDesc = oInputParameterHandler.getValue('sDescription')
    #VSlog(str(sUrl))
    if 'firstonetv' and 'Register-Login' in sUrl:

        session = requests.Session()
        url = 'https://www.firstonetv.net/Register-Login'
        data = {
            'usrmail': ADDON.getSetting('hoster_firstonetv_username'),
            'password': ADDON.getSetting('hoster_firstonetv_password'),
            'login': '******'
        }

        headers = {
            'user-agent': UA,
            'Content-Type': 'application/x-www-form-urlencoded',
            'Referer': 'https://www.firstonetv.net/Index',
            'Content-Length': str(len(data))
        }

        session.post(url, data=data, headers=headers)
        cookiesDict = requests.utils.dict_from_cookiejar(session.cookies)
        getUser = re.match("{'(.+?)': '(.+?)',", str(cookiesDict))
        VSlog(cookiesDict)
        cookies = str(getUser.group(1)) + '=' + str(getUser.group(2))
        GestionCookie().SaveCookie('firstonetv', cookies)
        dialog().VSinfo('Authentification reussie merci de recharger la page',
                        "FirstOneTv", 15)
        return

    sHtmlContent = getHtml(sUrl)

    if 'myfree-tivi' in sUrl:
        aResult = re.findall('<meta name="csrf-token" content="(.+?)">',
                             sHtmlContent)
        if aResult:
            token = aResult[0]
            VSlog(token)
            sHtmlContent = getHtml(sUrl, token)

    if 'firstonetv' in sUrl:
        sPattern = '(?:"surl":"{\".+?|,.+?)"([^"]+)\".+?"http([^"]+).m3u8'
    elif 'myfree-tivi' in sUrl:
        sPattern = "thumb'.+?'(.+?)'.+?title.+?'(.+?)'.+?url'.+?'(.+?)'"
    elif 'iptvgratuit.com' in sUrl:
        sPattern = '<strong>2. Cliquez sur le lien pour télécharger la liste des chaînes .+?</strong></p><h4><a class="more-link" title="(.+?)" href="(.+?)" target="_blank"'
    elif 'dailyiptvlist.com' in sUrl:
        sPattern = '<p></br><br /><strong>2. Click on link to download .+? iptv channels list</strong></p>\s*.+?<a href="(.+?)">Download (.+?)</a>'
    elif 'iptvsource.com':
        sPattern = '<a href="([^"]+)">Download as([^"]+)</a>'

    oParser = cParser()
    aResult = oParser.parse(sHtmlContent, sPattern)

    if (aResult[0] == True):
        total = len(aResult[1])
        progress_ = progress().VScreate(SITE_NAME)

        for aEntry in aResult[1]:
            progress_.VSupdate(progress_, total)
            if progress_.iscanceled():
                break

            if 'firstonetv' in sUrl:
                sTitle = sTitle + aEntry[0]
                sDesc = sDesc
                sThumb = sThumb
                sUrl2 = 'http' + aEntry[1].replace('\\\/', '/').replace(
                    "\/", "/"
                ) + '.m3u8|Referer=' + sUrl + '&User-Agent=' + UA + '&X-Requested-With=ShockwaveFlash/28.0.0.137&Origin=https://www.firstonetv.net'
            elif 'myfree-tivi' in sUrl:
                sTitle = str(aEntry[1])
                sUrl2 = str(aEntry[2])
                sThumb = 'https:' + str(aEntry[0])
                sDesc = ''
            elif 'iptvgratuit.com' in sUrl:
                sTitle = aEntry[0]
                sUrl2 = aEntry[1]
                sThumb = ''
                sDesc = ''
            else:
                sTitle = aEntry[1]
                sUrl2 = aEntry[0]
                sThumb = ''
                sDesc = ''

            oOutputParameterHandler = cOutputParameterHandler()
            oOutputParameterHandler.addParameter('siteUrl', sUrl2)
            oOutputParameterHandler.addParameter('sMovieTitle', sTitle)
            if 'myfree-tivi' or 'firstonetv' in sUrl:
                oOutputParameterHandler.addParameter('sThumbnail', sThumb)

            if 'iptvgratuit' and 'world-iptv-links' in sUrl:
                oGui.addDir(SITE_IDENTIFIER, 'showWorldIptvGratuit', sTitle,
                            '', oOutputParameterHandler)
            elif 'firstonetv' in sUrl:
                oGui.addMovie(SITE_IDENTIFIER, 'play__', sTitle, '', sThumb,
                              sDesc, oOutputParameterHandler)
            elif not 'firstonetv' or not 'myfree-tivi' in sUrl:
                oGui.addDir(SITE_IDENTIFIER, 'parseWebM3U', sTitle, '',
                            oOutputParameterHandler)
            else:
                oGui.addMovie(SITE_IDENTIFIER, 'play__', sTitle, '', sThumb,
                              sDesc, oOutputParameterHandler)

        progress_.VSclose(progress_)

    oGui.setEndOfDirectory()
示例#41
0
class cFav:

    DIALOG = dialog()
    ADDON = addon()

    # Suppression d'un bookmark, d'une catégorie, ou tous les bookmarks
    def delBookmark(self):
        oInputParameterHandler = cInputParameterHandler()
        if not self.DIALOG.VSyesno(self.ADDON.VSlang(30456)):
            return False

        sAll = oInputParameterHandler.exist('sAll')
        sCat = oInputParameterHandler.getValue('sCat')
        siteUrl = oInputParameterHandler.getValue('siteUrl')
        sTitle = oInputParameterHandler.getValue('sCleanTitle')
        #         sTitle = cUtil().CleanName(sTitle)

        cDb().del_bookmark(siteUrl, sTitle, sCat, sAll)
        return True

    # Suppression d'un bookmark depuis un Widget
    def delBookmarkMenu(self):
        if not self.DIALOG.VSyesno(self.ADDON.VSlang(30456)):
            return False

        sTitle = xbmc.getInfoLabel('ListItem.Property(sCleanTitle)')
        siteUrl = xbmc.getInfoLabel('ListItem.Property(siteUrl)')

        cDb().del_bookmark(siteUrl, sTitle)

        return True

    def getBookmarks(self):
        oGui = cGui()

        # Comptages des marque-pages
        row = cDb().get_bookmark()

        compt = [0, 0, 0, 0, 0, 0, 0, 0]
        for i in row:
            compt[int(i[5])] = compt[int(i[5])] + 1

        oOutputParameterHandler = cOutputParameterHandler()
        oOutputParameterHandler.addParameter('sCat', '1')
        oGui.addDir(SITE_IDENTIFIER, 'getFav',
                    ('%s (%s)') % (self.ADDON.VSlang(30120), str(compt[1])),
                    'mark.png', oOutputParameterHandler)

        oOutputParameterHandler = cOutputParameterHandler()
        oOutputParameterHandler.addParameter('sCat', '2')
        oGui.addDir(SITE_IDENTIFIER, 'getFav',
                    ('%s/%s (%s)') % (self.ADDON.VSlang(30121),
                                      self.ADDON.VSlang(30122), str(compt[2])),
                    'mark.png', oOutputParameterHandler)

        # oOutputParameterHandler = cOutputParameterHandler()
        # oOutputParameterHandler.addParameter('sCat', '3')
        # oGui.addDir(SITE_IDENTIFIER, 'getFav()', 'Pages', 'news.png', oOutputParameterHandler)

        oOutputParameterHandler = cOutputParameterHandler()
        oOutputParameterHandler.addParameter('sCat', '6')
        oGui.addDir(SITE_IDENTIFIER, 'getFav',
                    ('%s (%s)') % (self.ADDON.VSlang(30332), str(compt[6])),
                    'mark.png', oOutputParameterHandler)

        # oOutputParameterHandler = cOutputParameterHandler()
        # oOutputParameterHandler.addParameter('sCat', '7')
        # oGui.addDir(SITE_IDENTIFIER, 'getFav', ('%s (%s)') % (self.ADDON.VSlang(30088), str(compt[7])), 'mark.png', oOutputParameterHandler)

        oOutputParameterHandler = cOutputParameterHandler()
        total = compt[3] + compt[4] + compt[5]
        oGui.addDir(SITE_IDENTIFIER, 'getFav',
                    ('%s (%s)') % (self.ADDON.VSlang(30410), str(total)),
                    'mark.png', oOutputParameterHandler)

        oOutputParameterHandler = cOutputParameterHandler()
        oOutputParameterHandler.addParameter('sAll', 'true')
        oGui.addDir(SITE_IDENTIFIER, 'delBookmark', self.ADDON.VSlang(30209),
                    'trash.png', oOutputParameterHandler)

        # A virer dans les versions future, pour le moment c'est juste pr supprimer les liens bugges
        if compt[0] > 0:
            oOutputParameterHandler = cOutputParameterHandler()
            oOutputParameterHandler.addParameter('sCat', '0')
            oGui.addDir(
                SITE_IDENTIFIER, 'getFav',
                '[COLOR red]Erreur /!\ lien à supprimer!!! (' + str(compt[0]) +
                ')[/COLOR]', 'mark.png', oOutputParameterHandler)

        oGui.setEndOfDirectory()

    def getFav(self):
        oGui = cGui()

        oInputParameterHandler = cInputParameterHandler()

        row = cDb().get_bookmark()

        if (oInputParameterHandler.exist('sCat')):
            sCat = oInputParameterHandler.getValue('sCat')
            gen = (x for x in row if x[5] in sCat)
        else:
            sCat = '5'
            gen = (x for x in row if x[5] not in ('1', '2', '6'))

        for data in gen:

            try:
                title = data[1].encode('utf-8')
            except:
                title = data[1]

            try:
                thumbnail = data[6].encode('utf-8')
            except:
                thumbnail = data[6]

            try:

                try:
                    siteurl = data[2].encode('utf-8')
                except:
                    siteurl = data[2]

                if xbmc.getInfoLabel('system.buildversion')[0:2] >= '19':
                    siteurl = UnquotePlus(siteurl.decode('utf-8'))
                else:
                    siteurl = UnquotePlus(siteurl)

                site = data[3]
                function = data[4]
                cat = data[5]
                fanart = data[7]

                if thumbnail == '':
                    thumbnail = 'False'

                oOutputParameterHandler = cOutputParameterHandler()
                oOutputParameterHandler.addParameter('siteUrl', siteurl)
                oOutputParameterHandler.addParameter('sMovieTitle', title)
                oOutputParameterHandler.addParameter('searchtext', title)
                oOutputParameterHandler.addParameter('sThumbnail', thumbnail)
                # Dans ajouter source c'est bien sThumb donc...
                oOutputParameterHandler.addParameter('sThumb', thumbnail)

                if (function == 'play'):
                    oHoster = cHosterGui().checkHoster(siteurl)
                    oOutputParameterHandler.addParameter(
                        'sHosterIdentifier', oHoster.getPluginIdentifier())
                    oOutputParameterHandler.addParameter(
                        'sFileName', oHoster.getFileName())
                    oOutputParameterHandler.addParameter('sMediaUrl', siteurl)

                oGuiElement = cGuiElement()
                oGuiElement.setSiteName(site)
                oGuiElement.setFunction(function)
                oGuiElement.setTitle(title)
                oGuiElement.setFileName(title)
                oGuiElement.setIcon("mark.png")
                if (cat == '1'):
                    cGui.CONTENT = 'movies'
                    oGuiElement.setMeta(cat)
                    oGuiElement.setCat(1)
                elif (cat == '2'):
                    cGui.CONTENT = 'tvshows'
                    oGuiElement.setMeta(cat)
                    oGuiElement.setCat(2)
                else:
                    oGuiElement.setMeta(0)
                    oGuiElement.setCat(cat)
                oGuiElement.setThumbnail(thumbnail)
                oGuiElement.setFanart(fanart)
                oGuiElement.addItemProperties('isBookmark', True)

                oGui.CreateSimpleMenu(oGuiElement, oOutputParameterHandler,
                                      'cFav', 'cFav', 'delBookmark',
                                      self.ADDON.VSlang(30412))

                if (function == 'play'):
                    oGui.addHost(oGuiElement, oOutputParameterHandler)
                else:
                    oGui.addFolder(oGuiElement, oOutputParameterHandler)

            except:
                oGui.addDir(SITE_IDENTIFIER, 'DoNothing',
                            '[COLOR red]ERROR[/COLOR]', 'films.png',
                            oOutputParameterHandler)

        # La suppression n'est pas accessible lors de l'utilisation en Widget
        if not xbmc.getCondVisibility('Window.IsActive(home)'):
            oOutputParameterHandler = cOutputParameterHandler()
            oOutputParameterHandler.addParameter('sCat', sCat)
            oGui.addDir(SITE_IDENTIFIER, 'delBookmark',
                        self.ADDON.VSlang(30211), 'trash.png',
                        oOutputParameterHandler)

        oGui.setEndOfDirectory()

        return

    def setBookmark(self):
        oInputParameterHandler = cInputParameterHandler()

        sCat = oInputParameterHandler.getValue(
            'sCat') if oInputParameterHandler.exist(
                'sCat') else xbmc.getInfoLabel('ListItem.Property(sCat)')
        if int(sCat) not in (1, 2, 5):
            self.DIALOG.VSinfo('Error', self.ADDON.VSlang(30038))
            return

        meta = {}

        sSiteUrl = oInputParameterHandler.getValue(
            'siteUrl') if oInputParameterHandler.exist(
                'siteUrl') else xbmc.getInfoLabel('ListItem.Property(siteUrl)')
        sTitle = oInputParameterHandler.getValue(
            'sMovieTitle') if oInputParameterHandler.exist(
                'sMovieTitle') else xbmc.getInfoLabel(
                    'ListItem.Property(sCleanTitle)')
        sSite = oInputParameterHandler.getValue(
            'sId') if oInputParameterHandler.exist(
                'sId') else xbmc.getInfoLabel('ListItem.Property(sId)')
        sFav = oInputParameterHandler.getValue(
            'sFav') if oInputParameterHandler.exist(
                'sFav') else xbmc.getInfoLabel('ListItem.Property(sFav)')

        meta['siteurl'] = sSiteUrl
        meta['title'] = sTitle
        meta['site'] = sSite
        meta['fav'] = sFav
        meta['cat'] = sCat

        meta['icon'] = xbmc.getInfoLabel('ListItem.Art(thumb)')
        meta['fanart'] = xbmc.getInfoLabel('ListItem.Art(fanart)')
        try:
            cDb().insert_bookmark(meta)
        except:
            pass
示例#42
0
def showHosters():
    oGui = cGui()
    oInputParameterHandler = cInputParameterHandler()
    sUrl = oInputParameterHandler.getValue('siteUrl')
    sMovieTitle = oInputParameterHandler.getValue('sMovieTitle')
    sThumb = oInputParameterHandler.getValue('sThumb')

    if 'mon-tele' in sUrl:
        dialog().VSinfo('Décodage en cours', "Patientez", 5)
        s = requests.Session()

        response = s.get(sUrl, headers={'User-Agent': UA})
        sHtmlContent = str(response.content)
        cookie_string = "; ".join(
            [str(x) + "=" + str(y) for x, y in s.cookies.items()])

        oParser = cParser()
        sPattern = '<input type="hidden".+?value="([^"]+)"'
        aResult = oParser.parse(sHtmlContent, sPattern)

        from resources.lib import librecaptcha
        test = librecaptcha.get_token(
            api_key="6LezIsIZAAAAABMSqc7opxGc3xyCuXtAtV4VlTtN",
            site_url="https://mon-tele.com/",
            user_agent=UA,
            gui=False,
            debug=False,
        )

        if (aResult[0] == True):
            data = "_method=" + aResult[1][0] + "&_csrfToken=" + aResult[1][
                1] + "&ref=&f_n=" + aResult[1][
                    2] + "&g-recaptcha-response=" + test + "&_Token%5Bfields%5D=" + Quote(
                        aResult[1][3]) + "&_Token%5Bunlocked%5D=" + Quote(
                            aResult[1][4])

            oRequestHandler = cRequestHandler(sUrl)
            oRequestHandler.setRequestType(1)
            oRequestHandler.addHeaderEntry('Referer', sUrl)
            oRequestHandler.addHeaderEntry(
                'Accept',
                ' text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
            )
            oRequestHandler.addHeaderEntry('User-Agent', UA)
            oRequestHandler.addHeaderEntry('Content-Length', len(data))
            oRequestHandler.addHeaderEntry(
                'Content-Type', "application/x-www-form-urlencoded")
            oRequestHandler.addHeaderEntry('Cookie', cookie_string)
            oRequestHandler.addParametersLine(data)
            sHtmlContent = oRequestHandler.request()

        oParser = cParser()
        sPattern = '<input type="hidden".+?value="([^"]+)"'
        aResult = oParser.parse(sHtmlContent, sPattern)

        if (aResult[0] == True):
            data = "_method=" + aResult[1][0] + "&_csrfToken=" + aResult[1][
                1] + "&ad_form_data=" + Quote(
                    aResult[1][2]) + "&_Token%5Bfields%5D=" + Quote(
                        aResult[1][3]) + "&_Token%5Bunlocked%5D=" + Quote(
                            aResult[1][4])

            #Obligatoire pour validé les cookies.
            xbmc.sleep(15000)
            oRequestHandler = cRequestHandler(
                "https://mon-tele.com/obtenirliens/links/go")
            oRequestHandler.setRequestType(1)
            oRequestHandler.addHeaderEntry('Referer', sUrl)
            oRequestHandler.addHeaderEntry(
                'Accept', 'application/json, text/javascript, */*; q=0.01')
            oRequestHandler.addHeaderEntry('User-Agent', UA)
            oRequestHandler.addHeaderEntry('Content-Length', len(data))
            oRequestHandler.addHeaderEntry(
                'Content-Type',
                "application/x-www-form-urlencoded; charset=UTF-8")
            oRequestHandler.addHeaderEntry('X-Requested-With',
                                           'XMLHttpRequest')
            oRequestHandler.addHeaderEntry('Cookie', cookie_string)
            oRequestHandler.addParametersLine(data)
            sHtmlContent = oRequestHandler.request()

            sPattern = 'url":"([^"]+)"'
            aResult = oParser.parse(sHtmlContent, sPattern)
            if (aResult[0] == True):
                sHosterUrl = aResult[1][0]
                oHoster = cHosterGui().checkHoster(sHosterUrl)
                if (oHoster != False):
                    oHoster.setDisplayName(sMovieTitle)
                    oHoster.setFileName(sMovieTitle)
                    cHosterGui().showHoster(oGui, oHoster, sHosterUrl, sThumb)
    else:
        sHosterUrl = sUrl
        oHoster = cHosterGui().checkHoster(sHosterUrl)
        if (oHoster != False):
            oHoster.setDisplayName(sMovieTitle)
            oHoster.setFileName(sMovieTitle)
            cHosterGui().showHoster(oGui, oHoster, sHosterUrl, sThumb)

    oGui.setEndOfDirectory()
示例#43
0
class cDownload:

    DIALOG = dialog()
    ADDON = addon()


    def __init__(self):
        pass

    def __createDownloadFilename(self, sTitle):
        sTitle = re.sub(' +',' ',sTitle) #Vire double espace
        valid_chars = "-_.() abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        filename = ''.join(c for c in sTitle if c in valid_chars)
        filename = filename.replace(' .','.')
        if filename.startswith(' '):
            filename = filename[1:]
        #filename = filename.replace(' ','_') #pas besoin de ca, enfin pr moi en tout cas
        return filename

    def __formatFileSize(self, iBytes):
        iBytes = int(iBytes)
        if (iBytes == 0):
            return '%.*f %s' % (2, 0, 'MB')

        return '%.*f %s' % (2, iBytes/(1024*1024.0) , 'MB')

    def isDownloading_old(self):

        if not Memorise.get('VstreamDownloaderLock'):
            return False
        return True

    def isDownloading(self):

        if not xbmc.getCondVisibility("Window.IsVisible(10151)"):
            return False
        return True


    def download(self, sDBUrl, sTitle,sDownloadPath,FastMode = False):

        if self.isDownloading():
            self.DIALOG.VSinfo('Telechargements deja demarrés', 'Erreur')
            return False

        self.__sTitle = sTitle

        #resolve url
        from resources.lib.gui.hoster import cHosterGui
        oHoster = cHosterGui().checkHoster(sDBUrl)
        oHoster.setUrl(sDBUrl)
        aLink = oHoster.getMediaLink()
        #aLink = (True,'https://github.com/LordVenom/venom-xbmc-addons-beta/blob/master/plugin.video.vstream/Thumbs.db?raw=true')

        if (aLink[0] == True):
            sUrl = aLink[1]
        else:
            print 'Lien non resolvable'
            self.DIALOG.VSinfo('Lien non resolvable', sTitle)
            return False

        if (not sUrl.startswith('http')) or sUrl.split('|')[0].endswith('.m3u8') :
            self.DIALOG.VSinfo('Format non supporte', sTitle)
            return False

        try:
            VSlog("Telechargement " + str(sUrl))

            #background download task
            if FastMode:
                cDownloadProgressBar(title = self.__sTitle , url = sUrl , Dpath = sDownloadPath , FastMode = True ).start()
            else:
                cDownloadProgressBar(title = self.__sTitle , url = sUrl , Dpath = sDownloadPath ).start()

            VSlog("Telechargement ok")
            VSlog(sDownloadPath)


        except:
            #print_exc()
            self.DIALOG.VSinfo('Telechargement impossible', sTitle)
            VSlog("Telechargement impossible")
            return False

        return True


    def __createTitle(self, sUrl, sTitle):

        #sTitle = re.sub('[\(\[].+?[\)\]]',' ', sTitle)
        sTitle = cUtil().FormatSerie(sTitle)
        sTitle = cUtil().CleanName(sTitle)

        aTitle = sTitle.rsplit('.')
        #Si deja extension
        if (len(aTitle) > 1):
            return sTitle

        #recherche d'une extension
        sUrl = sUrl.lower()
        m = re.search('(flv|avi|mp4|mpg|mpeg|mkv)', sUrl)
        if m:
            sTitle = sTitle + '.' + m.group(0)
        else:
            sTitle = sTitle + '.flv' #Si quedale on en prend une au pif


        return sTitle


    def getDownload(self):

        oGui = cGui()
        sPluginHandle = cPluginHandler().getPluginHandle()
        sPluginPath = cPluginHandler().getPluginPath()
        sItemUrl = '%s?site=%s&function=%s&title=%s' % (sPluginPath, SITE_IDENTIFIER, 'StartDownloadList', 'tittle')
        meta = {'title': 'Demarrer la liste'}
        item = xbmcgui.ListItem('Demarrer la liste', iconImage='special://home/addons/plugin.video.vstream/resources/art/download.png')

        #item.setInfo(type="Video", infoLabels = meta)

        #item.setProperty("Video", "false")
        #item.setProperty("IsPlayable", "false")

        xbmcplugin.addDirectoryItem(sPluginHandle,sItemUrl,item,isFolder=False)

        oOutputParameterHandler = cOutputParameterHandler()
        oGui.addDir(SITE_IDENTIFIER, 'StopDownloadList', 'Arreter les Téléchargements', 'download.png', oOutputParameterHandler)

        oOutputParameterHandler = cOutputParameterHandler()
        oGui.addDir(SITE_IDENTIFIER, 'getDownloadList', 'Liste de Téléchargement', 'download.png', oOutputParameterHandler)

        oOutputParameterHandler = cOutputParameterHandler()
        oGui.addDir(SITE_IDENTIFIER, 'CleanDownloadList', 'Nettoyer la liste (Fichiers finis)', 'download.png', oOutputParameterHandler)

        oGui.setEndOfDirectory()

    def CleanDownloadList(self):

        try:
            cDb().clean_download()
            self.DIALOG.VSinfo('Liste mise a jour')
            #VSupdate()
        except:
            pass

        return

    def dummy(self):
        return

    def StartDownloadOneFile(self,meta = []):
        if not meta:
            meta = self.GetOnefile()

        xbmcgui.Window(10101).setProperty('SimpleDownloaderQueue', '0')
        self.StartDownload(meta)


    def ResetDownload(self):
        oInputParameterHandler = cInputParameterHandler()
        url = oInputParameterHandler.getValue('sUrl')
        meta = {}
        meta['url'] = url

        try:
            cDb().reset_download(meta)
            self.DIALOG.VSinfo('Liste mise a jour')
            VSupdate()
        except:
            pass

        return

    def ReadDownload(self):
        oInputParameterHandler = cInputParameterHandler()
        path = oInputParameterHandler.getValue('sPath')
        sTitle = oInputParameterHandler.getValue('sMovieTitle')

        oGuiElement = cGuiElement()
        oGuiElement.setSiteName(SITE_IDENTIFIER)
        oGuiElement.setMediaUrl(path)
        oGuiElement.setTitle(sTitle)
        #oGuiElement.getInfoLabel()

        oPlayer = cPlayer()
        #oPlayer.clearPlayList()
        #oPlayer.addItemToPlaylist(oGuiElement)
        if not (sys.argv[ 1 ] == '-1'):
            oPlayer.run(oGuiElement, sTitle, path)
        else:
            oPlayer.clearPlayList()
            oPlayer.addItemToPlaylist(oGuiElement)
            oPlayer.startPlayer()

    def DelFile(self):
        oInputParameterHandler = cInputParameterHandler()
        path = oInputParameterHandler.getValue('sPath')

        oDialog = self.DIALOG.VSyesno('Voulez vous vraiment supprimer ce fichier ? Operation non reversible.')
        if (oDialog == 1):
            meta = {}
            meta['url'] = ''
            meta['path'] = path

            try:
                cDb().del_download(meta)
                xbmcvfs.delete(path)
                self.DIALOG.VSinfo('Fichier supprimé')
                VSupdate()
            except:
                self.DIALOG.VSinfo('Erreur, fichier non supprimable')

    def GetNextFile(self):
        row = cDb().get_Download()

        for data in row:
            status = data[8]

            if status == '0':
                return data

        return None

    def GetOnefile(self):
        oInputParameterHandler = cInputParameterHandler()
        url = oInputParameterHandler.getValue('sUrl')

        meta = {}
        meta['url'] = url

        row = cDb().get_Download(meta)

        if not (row):
            return None

        return row[0]


    def StartDownload(self,data):
        if not (data):
            return

        title = data[1]
        url = urllib.unquote_plus(data[2])
        path = data[3]
        #thumbnail = urllib.unquote_plus(data[4])
        #status = data[8]

        self.download(url,title,path)

    def StartDownloadList(self):
        self.DIALOG.VSinfo('Demarrage de la liste complete')
        #Memorise.set('SimpleDownloaderQueue', '1')
        xbmcgui.Window(10101).setProperty('SimpleDownloaderQueue', '1')
        data = self.GetNextFile()
        self.StartDownload(data)

    def StopDownloadList(self):

        #oInputParameterHandler = cInputParameterHandler()
        #path = oInputParameterHandler.getValue('sPath')
        #status = oInputParameterHandler.getValue('sStatus')


        #WINDOW_PROGRESS = xbmcgui.Window( 10101 )
        #WINDOW_PROGRESS.close()
        #xbmcgui.Window(10101).setProperty('arret', '1')
        #xbmc.executebuiltin("Dialog.Close(%s, true)" % 10101)
        #xbmc.getCondVisibility('Window.IsActive(10101)'))

        #thread actif
        if xbmcgui.Window(10101).getProperty('arret') == '0':
            xbmcgui.Window(10101).setProperty('arret', '1')
        #si bug
        else:
            cDownloadProgressBar().StopAll()

        #On remet tout les status a 0 ou 2
        cDb().Cancel_download()

        VSupdate()

        return

    def getDownloadList(self):

        #from resources.lib.downloadplay import download_and_play
        ##download_and_play('https://a-2.1fichier.com/c2290838997?inline','test.avi','D:\Temporaire')
        #download_and_play('https://1fichier.com/?56eplh6nth','test.avi','D:\Temporaire')
        #return

        oGui = cGui()
        oInputParameterHandler = cInputParameterHandler()

        row = cDb().get_Download()

        for data in row:

            title = data[1]
            url = urllib.unquote_plus(data[2])
            cat = data[4]
            thumbnail = urllib.unquote_plus(data[5])
            #The url is unicode format ? Not managed yet
            try:
                #thumbnail = urllib.quote(thumbnail.encode('utf-8'), safe=':/.+?&')
                thumbnail = str(thumbnail)
            except:
                thumbnail = ''

            size = data[6]
            totalsize = data[7]
            status = data[8]
            path = data[3]

            oOutputParameterHandler = cOutputParameterHandler()
            oOutputParameterHandler.addParameter('sUrl', url)
            oOutputParameterHandler.addParameter('sMovieTitle', title)
            oOutputParameterHandler.addParameter('sThumbnail', thumbnail)
            oOutputParameterHandler.addParameter('sPath', path)
            oOutputParameterHandler.addParameter('sStatus', status)

            if status == '0':
                sStatus = ''
            elif status == '1':
                sStatus='[COLOR=red][En cours] [/COLOR]'
            elif status == '2':
                sStatus='[COLOR=green][Fini] [/COLOR]'

            if size:
                sTitle = sStatus + title + ' (' + self.__formatFileSize(size)+'/'+self.__formatFileSize(totalsize)+')'
            else:
                sTitle = sStatus + title

            oGuiElement = cGuiElement()

            if not thumbnail or thumbnail == 'False':
                thumbnail = "mark.png"

            oGuiElement.setSiteName(SITE_IDENTIFIER)
            if status == '2':
                oGuiElement.setFunction('ReadDownload')
            else:
                #oGuiElement.setFunction('StartDownloadOneFile') #marche pas a cause de fenetre xbmc
                oGuiElement.setFunction('ReadDownload')
            oGuiElement.setTitle(sTitle)
            oGuiElement.setIcon('download.png')
            oGuiElement.setMeta(0)
            oGuiElement.setThumbnail(thumbnail)

            oGui.createContexMenuDownload(oGuiElement, oOutputParameterHandler,status)

            oGui.addFolder(oGuiElement, oOutputParameterHandler)


        oGui.setEndOfDirectory()

        return

    def delDownload(self):

        oInputParameterHandler = cInputParameterHandler()
        url = oInputParameterHandler.getValue('sUrl')
        meta = {}
        meta['url'] = url
        meta['path'] = ''

        try:
            cDb().del_download(meta)
            self.DIALOG.VSinfo('Liste mise a jour')
            VSupdate()
        except:
            pass

        return

    def AddDownload(self,meta):

        sTitle = meta['title']
        sUrl = meta['url']

        #titre fichier
        sTitle = self.__createTitle(sUrl, sTitle)
        sTitle = self.__createDownloadFilename(sTitle)
        sTitle =  cGui().showKeyBoard(sTitle)

        if (sTitle != False and len(sTitle) > 0):

            #chemin de sauvegarde
            sPath2 = xbmc.translatePath(self.ADDON.getSetting('download_folder'))

            dialog = xbmcgui.Dialog()
            sPath = dialog.browse(3, 'Downloadfolder', 'files', '', False, False , sPath2)

            if (sPath != ''):
                self.ADDON.setSetting('download_folder',sPath)
                sDownloadPath = xbmc.translatePath(sPath +  '%s' % (sTitle, ))

                if xbmcvfs.exists(sDownloadPath):
                    self.DIALOG.VSinfo('Nom deja utilise', sTitle)
                    return self.AddDownload(meta)
                else:
                    xbmcvfs.File(sDownloadPath, 'w')

                try:
                    VSlog("Rajout en liste de telechargement " + str(sUrl))
                    meta['title'] = sTitle
                    meta['path'] = sDownloadPath

                    cDb().insert_download(meta)

                    return True

                except:
                    #print_exc()
                    self.DIALOG.VSinfo('Telechargement impossible', sTitle)
                    VSlog("Telechargement impossible")

        return False


    def AddtoDownloadList(self):

        oInputParameterHandler = cInputParameterHandler()

        sHosterIdentifier = oInputParameterHandler.getValue('sHosterIdentifier')
        sMediaUrl = oInputParameterHandler.getValue('sMediaUrl')
        #bGetRedirectUrl = oInputParameterHandler.getValue('bGetRedirectUrl')
        sFileName = oInputParameterHandler.getValue('sFileName')

        #if (bGetRedirectUrl == 'True'):
        #    sMediaUrl = self.__getRedirectUrl(sMediaUrl)

        VSlog("Telechargement " + sMediaUrl)

        meta = {}
        meta['url'] = sMediaUrl
        meta['cat'] = oInputParameterHandler.getValue('sCat')
        meta['title'] = sFileName
        meta['icon'] = xbmc.getInfoLabel('ListItem.Art(thumb)')

        if (self.AddDownload(meta)):
            #telechargement direct ou pas ?
            if not self.isDownloading():
                row = cDb().get_Download(meta)
                if row:
                    self.StartDownloadOneFile(row[0])

        return

    def AddtoDownloadListandview(self):

        oInputParameterHandler = cInputParameterHandler()

        sHosterIdentifier = oInputParameterHandler.getValue('sHosterIdentifier')
        sMediaUrl = oInputParameterHandler.getValue('sMediaUrl')
        sFileName = oInputParameterHandler.getValue('sFileName')

        VSlog("Telechargement " + sMediaUrl)

        meta = {}
        meta['url'] = sMediaUrl
        meta['cat'] = oInputParameterHandler.getValue('sCat')
        meta['title'] = sFileName
        meta['icon'] = xbmc.getInfoLabel('ListItem.Art(thumb)')

        if (self.AddDownload(meta)):
            #Si pas de telechargement en cours on lance le notre
            if not self.isDownloading():
                row = cDb().get_Download(meta)
                if row:

                    title = row[0][1]
                    url = urllib.unquote_plus(row[0][2])
                    path = row[0][3]
                    #thumbnail = urllib.unquote_plus(row[0][4])
                    #status = row[0][8]
                    if (self.download(url,title,path,True) == True): #Download in fastmode

                        #ok on attend un peu, et on lance le stream
                        tempo = 100
                        progress_ = progress().VScreate('Creation buffer')

                        while (tempo > 0):
                            #if canceled do nothing
                            if progress_.iscanceled():
                                break
                            progress_.VSupdate(progress_, 100)
                            tempo = tempo - 1
                            xbmc.sleep(500)

                        progress_.VSclose(progress_)

                        oGuiElement = cGuiElement()
                        oGuiElement.setSiteName(SITE_IDENTIFIER)
                        oGuiElement.setMediaUrl(path)
                        oGuiElement.setTitle(title)
                        #oGuiElement.getInfoLabel()

                        oPlayer = cPlayer()

                        if not (sys.argv[ 1 ] == '-1'):
                            oPlayer.run(oGuiElement, title, path)
                        else:
                            oPlayer.clearPlayList()
                            oPlayer.addItemToPlaylist(oGuiElement)
                            oPlayer.startPlayer()

                    else:
                        self.DIALOG.VSinfo('Echec du telechargement', 'Erreur')
        return
示例#44
0
def DecryptDlProtecte(url):

    VSlog('DecryptDlProtecte : ' + url)
    dialogs = dialog()

    if not (url):
        return ''

    #url2 = 'https://www.dl-protecte.org/php/Qaptcha.jquery.php'
    #url2 = 'https://www.protect-zt.com/php/Qaptcha.jquery.php'
    url2 = 'https://' + url.split('/')[2] + '/php/Qaptcha.jquery.php'

    #VSlog(url2)

    #Make random key
    s = "azertyupqsdfghjkmwxcvbn23456789AZERTYUPQSDFGHJKMWXCVBN_-#@"
    RandomKey = ''.join(random.choice(s) for i in range(32))

    oRequestHandler = cRequestHandler(url2)
    oRequestHandler.setRequestType(1)
    oRequestHandler.addHeaderEntry('Host', 'www.dl-protect.ru')
    oRequestHandler.addHeaderEntry('Referer', url)
    oRequestHandler.addHeaderEntry(
        'Accept', 'application/json, text/javascript, */*; q=0.01')
    oRequestHandler.addHeaderEntry('User-Agent', UA)
    oRequestHandler.addHeaderEntry('Accept-Language',
                                   'fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4')
    oRequestHandler.addHeaderEntry(
        'Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
    oRequestHandler.addHeaderEntry('X-Requested-With', 'XMLHttpRequest')
    oRequestHandler.addParameters('action', 'qaptcha')
    oRequestHandler.addParameters('qaptcha_key', RandomKey)

    sHtmlContent = oRequestHandler.request()

    cookies = oRequestHandler.GetCookies()
    GestionCookie().SaveCookie('dl_protect.ru', cookies)
    #VSlog( 'result'  + sHtmlContent)

    if not '"error":false' in sHtmlContent:
        VSlog('Captcha rate')
        VSlog(sHtmlContent)
        return

    #tempo pas necessaire
    #cGui().showInfo("Patientez", 'Décodage en cours', 2)
    #xbmc.sleep(1000)

    #Ancienne methode avec POST
    #query_args = ( ( 'YnJYHKk4xYUUu4uWQdxxuH@JEJ2yrmJS', '' ) , ('submit', 'Valider' ) )
    #data = urllib.urlencode(query_args)

    #Nouvelle methode avec multipart
    #multipart_form_data = { RandomKey : '', 'submit' : 'Valider' }

    import string
    _BOUNDARY_CHARS = string.digits + string.ascii_letters
    boundary = ''.join(random.choice(_BOUNDARY_CHARS) for i in range(30))

    multipart_form_data = {RandomKey: '', 'submit': 'Valider'}
    data, headersMulti = encode_multipart(multipart_form_data, {}, boundary)
    #VSlog( 'header 2'  + str(headersMulti))
    #VSlog( 'data 2'  + str(data))

    #2 eme requete pour avoir le lien
    cookies = GestionCookie().Readcookie('dl_protect.ru')
    oRequestHandler = cRequestHandler(url)
    oRequestHandler.setRequestType(1)
    oRequestHandler.addHeaderEntry('Host', 'www.dl-protect.ru')
    oRequestHandler.addHeaderEntry('Referer', url)
    oRequestHandler.addHeaderEntry(
        'Accept',
        'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
    oRequestHandler.addHeaderEntry('User-Agent', UA)
    oRequestHandler.addHeaderEntry('Accept-Language',
                                   'fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3')
    oRequestHandler.addHeaderEntry('Content-Length',
                                   headersMulti['Content-Length'])
    oRequestHandler.addHeaderEntry('Content-Type',
                                   headersMulti['Content-Type'])
    oRequestHandler.addHeaderEntry('Cookie', cookies)
    oRequestHandler.addHeaderEntry('Accept-Encoding', 'gzip, deflate')

    oRequestHandler.addParametersLine(data)

    sHtmlContent = oRequestHandler.request()

    #fh = open('d:\\test.txt', "w")
    #fh.write(sHtmlContent)
    #fh.close()

    return sHtmlContent
示例#45
0
def Display_protected_link():
    oGui = cGui()
    oParser = cParser()
    oInputParameterHandler = cInputParameterHandler()
    sMovieTitle = oInputParameterHandler.getValue('sMovieTitle')
    sUrl = oInputParameterHandler.getValue('siteUrl')
    sThumb = oInputParameterHandler.getValue('sThumb')

    if 'ouo' in sUrl:
        sHosterUrl = DecryptOuo(sUrl)
        if (sHosterUrl):
            sTitle = sMovieTitle

            oHoster = cHosterGui().checkHoster(sHosterUrl)
            if (oHoster != False):
                oHoster.setDisplayName(sTitle)
                oHoster.setFileName(sTitle)
                cHosterGui().showHoster(oGui, oHoster, sHosterUrl, sThumb)

        oGui.setEndOfDirectory()

    #Est ce un lien dl-protect ?
    if '/l.k.s/' in sUrl:
        sHtmlContent = DecryptddlProtect(sUrl)

        if sHtmlContent:
            #Si redirection
            if sHtmlContent.startswith('http'):
                aResult_dlprotect = (True, [sHtmlContent])
            else:
                sPattern_dlprotect = '<p><a href="(.+?)">.+?</a></p>'
                aResult_dlprotect = oParser.parse(sHtmlContent,
                                                  sPattern_dlprotect)

        else:
            oDialog = dialog().VSok(
                'Désolé, problème de captcha.\n Veuillez en rentrer un directement sur le site, le temps de réparer'
            )
            aResult_dlprotect = (False, False)

    elif 'keeplinks' in sUrl:
        sHosterUrl = DecryptKeeplinks(sUrl)
        if (sHosterUrl):
            sTitle = sMovieTitle

            oHoster = cHosterGui().checkHoster(sHosterUrl)
            if (oHoster != False):
                oHoster.setDisplayName(sTitle)
                oHoster.setFileName(sTitle)
                cHosterGui().showHoster(oGui, oHoster, sHosterUrl, sThumb)

        oGui.setEndOfDirectory()
    #Si lien normal
    else:
        if not sUrl.startswith('http'):
            sUrl = 'http://' + sUrl
        aResult_dlprotect = (True, [sUrl])

    if (aResult_dlprotect[0]):
        for aEntry in aResult_dlprotect[1]:
            sHosterUrl = aEntry

            sTitle = sMovieTitle

            oHoster = cHosterGui().checkHoster(sHosterUrl)
            if (oHoster != False):
                oHoster.setDisplayName(sTitle)
                oHoster.setFileName(sTitle)
                cHosterGui().showHoster(oGui, oHoster, sHosterUrl, sThumb)

    oGui.setEndOfDirectory()
示例#46
0
def DecryptddlProtect(url):
    #print 'entering DecryptddlProtect'
    if not (url): return ''

    #Get host
    tmp = url.split('/')
    host = tmp[0] + '//' + tmp[2] + '/' + tmp[3] + '/'
    host1 = tmp[2]

    cookies = ''
    dialogs = dialog()
    #try to get previous cookie
    cookies = GestionCookie().Readcookie('cinemegatoil_org')

    oRequestHandler = cRequestHandler(url)
    if cookies:
        oRequestHandler.addHeaderEntry('Cookie', cookies)
    sHtmlContent = oRequestHandler.request()

    #A partir de la on a les bon cookies pr la protection cloudflare

    #Si ca demande le captcha
    if 'Vérification Captcha:' in sHtmlContent:
        if cookies:
            GestionCookie().DeleteCookie('cinemegatoil_org')
            oRequestHandler = cRequestHandler(url)
            sHtmlContent = oRequestHandler.request()

        s = re.findall('<img src="([^<>"]+?)" /><br />', sHtmlContent)
        if host in s[0]:
            image = s[0]
        else:
            image = host + s[0]

        captcha,cookies2 = get_response(image, cookies)
        cookies = cookies2.replace(';', '')

        oRequestHandler = cRequestHandler(url)
        oRequestHandler.setRequestType(1)
        oRequestHandler.addHeaderEntry('Host',host1)
        oRequestHandler.addHeaderEntry('User-Agent', UA)
        oRequestHandler.addHeaderEntry('Accept-Language', 'fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4')
        oRequestHandler.addHeaderEntry('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8')
        oRequestHandler.addHeaderEntry('Cookie', cookies)
        oRequestHandler.addHeaderEntry('Referer', url)

        oRequestHandler.addParameters('submit1', 'Submit')
        oRequestHandler.addParameters('security_code', captcha)

        sHtmlContent = oRequestHandler.request()

        if 'Code de securite incorrect' in sHtmlContent:
            dialogs.VSinfo("Mauvais Captcha")
            return 'rate'

        if 'Veuillez recopier le captcha ci-dessus' in sHtmlContent:
            dialogs.VSinfo("Rattage")
            return 'rate'

        #si captcha reussi
        #save cookies
        GestionCookie().SaveCookie('cinemegatoil_org', cookies)

    return sHtmlContent
示例#47
0
class cFav:

    DIALOG = dialog()
    ADDON = addon()

    #effacement direct par menu
    def delFavouritesMenu(self):
        if self.DIALOG.VSyesno(self.ADDON.VSlang(30456)):
            cDb().del_favorite()
        return True

    #avec confirmation pour les autres
    def delFavourites(self):
        if self.DIALOG.VSyesno(self.ADDON.VSlang(30456)):
            cDb().del_favorite()
        return True

    def getFavourites(self):
        oGui = cGui()

        #Comptages des favoris
        row = cDb().get_favorite()

        compt = [0, 0, 0, 0, 0, 0, 0, 0]
        for i in row:
            compt[int(i[5])] = compt[int(i[5])] + 1

        # sTitle = '[COLOR khaki]Vous avez %s marque page[/COLOR]' % (len(row))
        # oOutputParameterHandler = cOutputParameterHandler()
        # oOutputParameterHandler.addParameter('siteUrl', 'http://')
        # oGui.addText(SITE_IDENTIFIER, sTitle)

        oOutputParameterHandler = cOutputParameterHandler()
        oOutputParameterHandler.addParameter('sCat', '1')
        oGui.addDir(SITE_IDENTIFIER, 'getFav',
                    ('%s (%s)') % (self.ADDON.VSlang(30120), str(compt[1])),
                    'mark.png', oOutputParameterHandler)

        oOutputParameterHandler = cOutputParameterHandler()
        oOutputParameterHandler.addParameter('sCat', '2')
        oGui.addDir(SITE_IDENTIFIER, 'getFav',
                    ('%s/%s (%s)') % (self.ADDON.VSlang(30121),
                                      self.ADDON.VSlang(30122), str(compt[2])),
                    'mark.png', oOutputParameterHandler)

        # oOutputParameterHandler = cOutputParameterHandler()
        # oOutputParameterHandler.addParameter('sCat', '3')
        # oGui.addDir(SITE_IDENTIFIER, 'getFav()', 'Pages', 'news.png', oOutputParameterHandler)

        oOutputParameterHandler = cOutputParameterHandler()
        oOutputParameterHandler.addParameter('sCat', '6')
        oGui.addDir(SITE_IDENTIFIER, 'getFav',
                    ('%s (%s)') % (self.ADDON.VSlang(30332), str(compt[6])),
                    'mark.png', oOutputParameterHandler)

        # oOutputParameterHandler = cOutputParameterHandler()
        # oOutputParameterHandler.addParameter('sCat', '7')
        # oGui.addDir(SITE_IDENTIFIER, 'getFav', 'Recherche Visuelle (' + str(compt[7]) + ')', 'mark.png', oOutputParameterHandler)

        oOutputParameterHandler = cOutputParameterHandler()
        total = compt[3] + compt[4] + compt[5]
        oGui.addDir(SITE_IDENTIFIER, 'getFav',
                    ('%s (%s)') % (self.ADDON.VSlang(30410), str(total)),
                    'mark.png', oOutputParameterHandler)

        oOutputParameterHandler = cOutputParameterHandler()
        oOutputParameterHandler.addParameter('sAll', 'true')
        oGui.addDir(SITE_IDENTIFIER, 'delFavourites', self.ADDON.VSlang(30209),
                    'trash.png', oOutputParameterHandler)

        #A virer dans les versions future, pour le moment c'est juste pr supprimer les liens bugges
        if compt[0] > 0:
            oOutputParameterHandler = cOutputParameterHandler()
            oOutputParameterHandler.addParameter('sCat', '0')
            oGui.addDir(
                SITE_IDENTIFIER, 'getFav',
                '[COLOR red]Erreur /!\ lien a supprimer !!! (' +
                str(compt[0]) + ')[/COLOR]', 'mark.png',
                oOutputParameterHandler)

        oGui.setEndOfDirectory()

    def getFav(self):
        oGui = cGui()

        oInputParameterHandler = cInputParameterHandler()

        #aParams = oInputParameterHandler.getAllParameter()

        row = cDb().get_favorite()

        if (oInputParameterHandler.exist('sCat')):
            sCat = oInputParameterHandler.getValue('sCat')
            gen = (x for x in row if x[5] in sCat)
        else:
            sCat = '5'
            gen = (x for x in row if x[5] not in ('1', '2', '6'))

        for data in gen:

            try:
                title = data[1].encode('utf-8')
            except:
                title = data[1]

            try:
                thumbnail = data[6].encode('utf-8')
            except:
                thumbnail = data[6]

            try:

                siteurl = urllib.unquote_plus(data[2])
                site = data[3]
                function = data[4]
                cat = data[5]
                fanart = data[7]

                if thumbnail == '':
                    thumbnail = 'False'

                oOutputParameterHandler = cOutputParameterHandler()
                oOutputParameterHandler.addParameter('siteUrl', siteurl)
                oOutputParameterHandler.addParameter('sMovieTitle', title)
                oOutputParameterHandler.addParameter('searchtext', title)
                oOutputParameterHandler.addParameter('sThumbnail', thumbnail)
                #Dans ajouter source c'est bien sThumb donc...
                oOutputParameterHandler.addParameter('sThumb', thumbnail)

                if (function == 'play'):
                    oHoster = cHosterGui().checkHoster(siteurl)
                    oOutputParameterHandler.addParameter(
                        'sHosterIdentifier', oHoster.getPluginIdentifier())
                    oOutputParameterHandler.addParameter(
                        'sFileName', oHoster.getFileName())
                    oOutputParameterHandler.addParameter('sMediaUrl', siteurl)

                oGuiElement = cGuiElement()

                oGuiElement.setSiteName(site)
                oGuiElement.setFunction(function)
                oGuiElement.setTitle(title)
                oGuiElement.setFileName(title)
                oGuiElement.setIcon("mark.png")
                if (cat == '1'):
                    cGui.CONTENT = 'movies'
                    oGuiElement.setMeta(cat)
                    oGuiElement.setCat(1)
                elif (cat == '2'):
                    cGui.CONTENT = 'tvshows'
                    oGuiElement.setMeta(cat)
                    oGuiElement.setCat(2)
                else:
                    oGuiElement.setMeta(0)
                    oGuiElement.setCat(cat)
                oGuiElement.setThumbnail(thumbnail)
                oGuiElement.setFanart(fanart)

                #self.createContexMenuDelFav(oGuiElement, oOutputParameterHandler)
                oGui.CreateSimpleMenu(oGuiElement, oOutputParameterHandler,
                                      'cFav', 'cFav', 'delFavouritesMenu',
                                      self.ADDON.VSlang(30412))

                if (function == 'play'):
                    oGui.addHost(oGuiElement, oOutputParameterHandler)
                else:
                    oGui.addFolder(oGuiElement, oOutputParameterHandler)

                    #oGui.addFav(site, function, title, "mark.png", thumbnail, fanart, oOutputParameterHandler)

            except:
                oGui.addDir(SITE_IDENTIFIER, 'DoNothing',
                            '[COLOR red]ERROR[/COLOR]', 'films.png',
                            oOutputParameterHandler)

        oOutputParameterHandler = cOutputParameterHandler()
        oOutputParameterHandler.addParameter('sCat', sCat)
        oGui.addDir(SITE_IDENTIFIER, 'delFavourites', self.ADDON.VSlang(30211),
                    'trash.png', oOutputParameterHandler)

        oGui.setEndOfDirectory()

        return

    def setFavorite(self):
        oInputParameterHandler = cInputParameterHandler()

        if oInputParameterHandler.getValue('sId') == 'kepliz_com':
            self.DIALOG.VSinfo('Error', 'Non possible pour ce site')
            return

        if int(oInputParameterHandler.getValue('sCat')) < 1:
            self.DIALOG.VSinfo('Error',
                               'Mise en Favoris non possible pour ce lien')
            return

        meta = {}
        meta['siteurl'] = oInputParameterHandler.getValue('siteUrl')
        meta['site'] = oInputParameterHandler.getValue('sId')
        meta['fav'] = oInputParameterHandler.getValue('sFav')
        meta['cat'] = oInputParameterHandler.getValue('sCat')

        #ListItem.title contient des code de couleurs, sMovieTitle le titre en plus "propre"
        #Inutile a la prochaine version, car plus de couleurs a la base.
        if oInputParameterHandler.getValue('sMovieTitle'):
            meta['title'] = oInputParameterHandler.getValue('sMovieTitle')
        else:
            meta['title'] = xbmc.getInfoLabel('ListItem.title')

        meta['icon'] = xbmc.getInfoLabel('ListItem.Art(thumb)')
        meta['fanart'] = xbmc.getInfoLabel('ListItem.Art(fanart)')
        try:
            cDb().insert_favorite(meta)
        except:
            pass
示例#48
0
def get_response(img,cookie):
    #on telecharge l'image
    import xbmcvfs

    dialogs = dialog()

    filename = "special://home/userdata/addon_data/plugin.video.vstream/Captcha.raw"
    #PathCache = xbmc.translatePath(xbmcaddon.Addon('plugin.video.vstream').getAddonInfo("profile"))
    #filename  = os.path.join(PathCache, 'Captcha.raw')

    hostComplet = re.sub(r'(https*:\/\/[^/]+)(\/*.*)', '\\1', img)
    host = re.sub(r'https*:\/\/', '', hostComplet)
    url = img

    oRequestHandler = cRequestHandler(url)
    oRequestHandler.addHeaderEntry('User-Agent' , UA)
    #oRequestHandler.addHeaderEntry('Referer', url)
    oRequestHandler.addHeaderEntry('Cookie', cookie)

    htmlcontent = oRequestHandler.request()

    NewCookie = oRequestHandler.GetCookies()

    downloaded_image = xbmcvfs.File(filename, 'wb')
    #downloaded_image = file(filename, "wb")
    downloaded_image.write(htmlcontent)
    downloaded_image.close()

#on affiche le dialogue
    solution = ''

    if (True):
        ####nouveau captcha
        try:
            ##affichage du dialog perso
            class XMLDialog(xbmcgui.WindowXMLDialog):
                #"""
                #Dialog class for captcha
                #"""
                def __init__(self, *args, **kwargs):
                    xbmcgui.WindowXMLDialog.__init__(self)
                    pass

                def onInit(self):
                    #image background captcha
                    self.getControl(1).setImage(filename.encode("utf-8"), False)
                    #image petit captcha memory fail
                    self.getControl(2).setImage(filename.encode("utf-8"), False)
                    self.getControl(2).setVisible(False)
                    ##Focus clavier
                    self.setFocus(self.getControl(21))

                def onClick(self, controlId):
                    if controlId == 20:
                        #button Valider
                        solution = self.getControl(5000).getLabel()
                        xbmcgui.Window(10101).setProperty('captcha', solution)
                        self.close()
                        return

                    elif controlId == 30:
                        #button fermer
                        self.close()
                        return

                    elif controlId == 21:
                        #button clavier
                        self.getControl(2).setVisible(True)
                        kb = xbmc.Keyboard(self.getControl(5000).getLabel(), '', False)
                        kb.doModal()

                        if (kb.isConfirmed()):
                            self.getControl(5000).setLabel(kb.getText())
                            self.getControl(2).setVisible(False)
                        else:
                            self.getControl(2).setVisible(False)

                def onFocus(self, controlId):
                    self.controlId = controlId

                def _close_dialog(self):
                    self.close()

                def onAction(self, action):
                    #touche return 61448
                    if action.getId() in (9, 10, 11, 30, 92, 216, 247, 257, 275, 61467, 61448):
                        self.close()

            path = "special://home/addons/plugin.video.vstream"
            #path = cConfig().getAddonPath().decode("utf-8")
            wd = XMLDialog('DialogCaptcha.xml', path, 'default', '720p')
            wd.doModal()
            del wd
        finally:

            solution = xbmcgui.Window(10101).getProperty('captcha')
            if solution == '':
                dialogs.VSinfo("Vous devez taper le captcha")

    else:
        #ancien Captcha
        try:
            img = xbmcgui.ControlImage(450, 0, 400, 130, filename.encode("utf-8"))
            wdlg = xbmcgui.WindowDialog()
            wdlg.addControl(img)
            wdlg.show()
            #xbmc.sleep(3000)
            kb = xbmc.Keyboard('', 'Tapez les Lettres/chiffres de l\'image', False)
            kb.doModal()
            if (kb.isConfirmed()):
                solution = kb.getText()
                if solution == '':
                    dialogs.VSinfo("Vous devez taper le captcha")
            else:
                dialogs.VSinfo("Vous devez taper le captcha")
        finally:
            wdlg.removeControl(img)
            wdlg.close()

    return solution, NewCookie
示例#49
0
class cLibrary:
    ADDON = addon()
    DIALOG = dialog()

    def __init__(self):
        self.__sMovieFolder = self.ADDON.getSetting('Library_folder_Movies')
        self.__sTVFolder = self.ADDON.getSetting('Library_folder_TVs')

        if not self.__sMovieFolder:
            #PathCache = cConfig().getSettingCache()
            #self.__sMovieFolder = os.path.join(PathCache, 'Movies\\').decode('utf-8')
            self.__sMovieFolder = 'special://userdata/addon_data/plugin.video.vstream/Films'
            self.ADDON.setSetting('Library_folder_Movies', self.__sMovieFolder)
        if not xbmcvfs.exists(self.__sMovieFolder):
                xbmcvfs.mkdir(self.__sMovieFolder)

        if not self.__sTVFolder:
            #PathCache = cConfig().getSettingCache()
            #self.__sTVFolder = os.path.join(PathCache, 'TVs\\').decode('utf-8')
            self.__sTVFolder = 'special://userdata/addon_data/plugin.video.vstream/Series'
            Self.ADDON.setSetting('Library_folder_TVs', self.__sTVFolder)
        if not xbmcvfs.exists(self.__sTVFolder):
                xbmcvfs.mkdir(self.__sTVFolder)

        self.__sTitle = ''

    def setLibrary(self):
        oInputParameterHandler = cInputParameterHandler()
        # sUrl = oInputParameterHandler.getValue('siteUrl')
        sHosterIdentifier = oInputParameterHandler.getValue('sHosterIdentifier')
        sFileName = oInputParameterHandler.getValue('sFileName')
        sMediaUrl = oInputParameterHandler.getValue('sMediaUrl')

        ret = self.DIALOG.select('Sélectionner une catégorie', ['Film', 'Série'])
        if ret == 0:
            sCat = '1'
        elif ret == -1:
            return
        else:
            sCat = '2'

        #cConfig().log(oInputParameterHandler.getAllParameter())

        sMediaUrl = urllib.quote_plus(sMediaUrl)
        sFileName = urllib.quote_plus(sFileName)

        sLink = 'plugin://plugin.video.vstream/?function=play&site=cHosterGui&sFileName=' + sFileName + '&sMediaUrl=' + sMediaUrl + '&sHosterIdentifier=' + sHosterIdentifier

        sTitle = sFileName

        #folder = self.__sMovieFolder

        if sCat == '1':#film
            #folder = self.__sMovieFolder

            sTitle = cUtil().CleanName(sTitle)
            sTitle =  self.showKeyBoard(sTitle, 'Nom du dossier et du fichier')

            try:
                #folder = '%s%s/' % (folder, sTitle)
                sPath = '/'.join([self.__sMovieFolder, sTitle])

                # if not os.path.exists(folder):
                    # os.mkdir(folder)
                if not xbmcvfs.exists(sPath):
                    xbmcvfs.mkdir(sPath)

                self.MakeFile(sPath,sTitle,sLink)
                #xbmc.executebuiltin('UpdateLibrary(video, '+ folder + ')')
            except:
                self.DIALOG.VSinfo('Rajout impossible')

        elif sCat == '2':#serie

            #sTitle = cUtil().FormatSerie(sTitle)
            sTitle = cUtil().CleanName(sTitle)
            sFTitle =  self.showKeyBoard(sTitle, 'Recommandé Nomdeserie/Saison00')
            
            #sTitleGlobal = re.sub('((?:[s|e][0-9]+){1,2})', '', sTitle)
            
            # if sTitleGlobal.endswith(' '):
            #     sTitleGlobal = sTitleGlobal[:-1]
            # if sTitleGlobal.endswith('FINAL'):
            #      sTitleGlobal = sTitleGlobal[:-5]

            try:
                #print folder

                #folder2 = folder + '/' + sTitleGlobal + '/'
                #folder2 = '%s%s/' % (self.__sTVFolder, sTitleGlobal)
                sPath = '/'.join([self.__sTVFolder, sFTitle])

                #if not os.path.exists(folder2):
                    #os.mkdir(folder2)
                if not xbmcvfs.exists(sPath):
                    xbmcvfs.mkdir(sPath)

                sTitle =  self.showKeyBoard(sTitle, 'Recommandé NomdeserieS00E00')

                self.MakeFile(sPath,sTitle,sLink)
                #xbmc.executebuiltin('UpdateLibrary(video, '+ folder + ')')
            except:
                self.DIALOG.VSinfo('Rajout impossible')


    def MakeFile(self,folder,name,content):
        #stream = os.path.join(folder, str(name) + '.strm')
        #stream = '%s%s.strm' % (folder, str(name))
        stream = '/'.join([folder, str(name)]) + '.strm'
        #f = open(stream, 'w')
        f = xbmcvfs.File(stream, 'w')
        result = f.write(str(content))
        f.close()
        if result:
            self.DIALOG.VSinfo('Elément rajouté à la librairie')
        else:
            self.DIALOG.VSinfo('Rajout impossible')


    def getLibrary(self):
        xbmc.executebuiltin('Container.Update(special://userdata/addon_data/plugin.video.vstream/)', True)
        #xbmc.executebuiltin('ActivateWindow(Videos, 'special://userdata/addon_data/plugin.video.vstream/')', True)
        return True


    def Delfile(self):
        oInputParameterHandler = cInputParameterHandler()
        sFile = oInputParameterHandler.getValue('sFile')

        #os.remove(sFile)
        xbmcvfs.delete(sFile)

        runClean = self.DIALOG.VSyesno('Voulez vous mettre à jour la librairie maintenant (non conseillé)', 'Fichier supprimé')
        if(not runClean):
            return

        xbmc.executebuiltin('CleanLibrary(video)')

    def ShowContent(self):
        oInputParameterHandler = cInputParameterHandler()
        sFolder = oInputParameterHandler.getValue('folder')
        xbmc.executebuiltin('Container.Update(' + sFolder + ')')

    def showKeyBoard(self, sDefaultText='', Heading=''):
        keyboard = xbmc.Keyboard(sDefaultText)
        keyboard.setHeading(Heading) #optional
        keyboard.doModal()
        if (keyboard.isConfirmed()):
            sSearchText = keyboard.getText()
            if (len(sSearchText)) > 0:
                return sSearchText

        return False
示例#50
0
    def run(self, oGuiElement, sTitle, sUrl):

        self.totalTime = 0
        self.currentTime = 0

        sPluginHandle = cPluginHandler().getPluginHandle()

        oGui = cGui()
        item = oGui.createListItem(oGuiElement)
        item.setPath(oGuiElement.getMediaUrl())

        #meta = {'label': oGuiElement.getTitle(), 'title': oGuiElement.getTitle()}
        #item = xbmcgui.ListItem(path=sUrl, iconImage='DefaultVideo.png', thumbnailImage=self.sThumbnail)
        #item.setInfo(type='Video', infoLabels=meta)

        #Sous titres
        if (self.Subtitles_file):
            try:
                item.setSubtitles(self.Subtitles_file)
                VSlog('Load SubTitle :' + str(self.Subtitles_file))
                self.SubtitleActive = True
            except:
                VSlog("Can't load subtitle:" + str(self.Subtitles_file))

        player_conf = self.ADDON.getSetting('playerPlay')

        #Si lien dash, methode prioritaire
        if sUrl.endswith('.mpd') or sUrl.split('?')[0][-4:] in '.mpd':
            if isKrypton() == True:
                self.enable_addon('inputstream.adaptive')
                item.setProperty('inputstreamaddon', 'inputstream.adaptive')
                item.setProperty('inputstream.adaptive.manifest_type', 'mpd')
                xbmcplugin.setResolvedUrl(sPluginHandle, True, listitem=item)
                VSlog('Player use inputstream addon')
            else:
                dialog().VSerror('Nécessite kodi 17 minimum')
                return
        #1 er mode de lecture
        elif (player_conf == '0'):
            self.play(sUrl, item)
            VSlog('Player use Play() method')
        #2 eme mode non utilise
        elif (player_conf == 'neverused'):
            xbmc.executebuiltin('PlayMedia(' + sUrl + ')')
            VSlog('Player use PlayMedia() method')
        #3 eme mode (defaut)
        else:
            xbmcplugin.setResolvedUrl(sPluginHandle, True, item)
            VSlog('Player use setResolvedUrl() method')

        #Attend que le lecteur demarre, avec un max de 20s
        if xbmc.getInfoLabel('system.buildversion')[0:2] >= '19':
            for _ in range(20):
                if self.playBackEventReceived:
                    break
                xbmc.sleep(1000)
        else:
            for _ in xrange(20):
                if self.playBackEventReceived:
                    break
                xbmc.sleep(1000)

        #active/desactive les sous titres suivant l'option choisie dans la config
        if (self.SubtitleActive):
            if (self.ADDON.getSetting('srt-view') == 'true'):
                self.showSubtitles(True)
                dialog().VSinfo('Sous-titres chargés', 'Sous-Titres', 5)
            else:
                self.showSubtitles(False)
                dialog().VSinfo('Sous-titres chargés, vous pouvez les activer',
                                'Sous-Titres', 15)

        while self.isPlaying() and not self.forcestop:
            #while not xbmc.abortRequested:
            try:
                self.currentTime = self.getTime()
                self.totalTime = self.getTotalTime()

                #xbmc.log(str(self.currentTime))

            except:
                pass
                #break
            xbmc.sleep(1000)

        if not self.playBackStoppedEventReceived:
            self.onPlayBackStopped()

        #Uniquement avec la lecture avec play()
        if (player_conf == '0'):
            r = xbmcplugin.addDirectoryItem(handle=sPluginHandle,
                                            url=sUrl,
                                            listitem=item,
                                            isFolder=False)
            #xbmcplugin.endOfDirectory(sPluginHandle, True, False, False)
            return r

        VSlog('Closing player')
示例#51
0
    def __getMediaLinkForGuest(self):

        oParser = cParser()

        #recuperation de la page
        #xbmc.log('url teste : ' + self.__sUrl)
        oRequest = cRequestHandler(self.__sUrl)
        oRequest.addHeaderEntry('User-Agent', UA)
        sHtmlContent1 = oRequest.request()

        #fh = open('c:\\test.txt', "w")
        #fh.write(sHtmlContent1)
        #fh.close()

        #Recuperation url cachee
        TabUrl = []
        #sPattern = '<span style="".+?id="([^"]+)">([^<]+)<\/span>'
        sPattern = '<p style=""[^"]+id="([^"]+)">([^<]+)<\/p>'
        aResult = re.findall(sPattern, sHtmlContent1)
        if (aResult):
            TabUrl = aResult
        else:
            VSlog('OPL er 1')
            return False, False

        #xbmc.log("Nbre d'url : " + str(len(TabUrl)))

        #on essait de situer le code
        sPattern = '<script src="\/assets\/js\/video-js\/video\.js.+?.js"(.+)*'

        aResult = re.findall(sPattern, sHtmlContent1, re.DOTALL)
        if (aResult):
            sHtmlContent3 = aResult[0]
        else:
            VSlog('OPL er 2')
            return False, False

        #Deobfuscation, a otimiser pour accelerer le traitement
        code = ''
        maxboucle = 4
        while (maxboucle > 0):
            sHtmlContent3 = CheckCpacker(sHtmlContent3)
            sHtmlContent3 = CheckJJDecoder(sHtmlContent3)
            sHtmlContent3 = CheckAADecoder(sHtmlContent3)

            maxboucle = maxboucle - 1

        code = sHtmlContent3

        #fh = open('c:\\html.txt', "w")
        #fh.write(code)
        #fh.close()

        id_final = ""
        sPattern = 'var srclink.*?\/stream\/.*?(#[^\'"]+).*?mime=true'
        aResult = re.findall(sPattern, code)
        if (aResult):
            id_final = aResult[0]
        else:
            VSlog('OPL er 9')
            return False, False

        if not (code):
            VSlog('OPL er 3')
            return False, False

        #Search the coded url
        Coded_url = ''
        for i in TabUrl:
            if len(i[1]) > 30:
                Coded_url = i[1]
                Item_url = '#' + i[0]
                VSlog(Item_url + ' : ' + Coded_url)

        if not (Coded_url):
            VSlog('Url codee non trouvee')
            return False, False

        #Nettoyage du code pr traitement
        code = CleanCode(code, Coded_url)

        #fh = open('c:\\JS.txt', "w")
        #fh.write(code)
        #fh.close()

        VSlog('Code JS extrait')

        dialog().VSinfo('Decodage : Peut durer plus d une minute.',
                        self.__sDisplayName, 15)

        #interpreteur JS
        JP = JsParser()
        Liste_var = []
        JP.AddHackVar(Item_url, Coded_url)

        JP.ProcessJS(code, Liste_var)

        url = None
        #for name in [ '#streamurl', '#streamuri', '#streamurj']:
        #    if JP.IsVar( JP.HackVars, name ):
        #        url = JP.GetVarHack( name )
        #        VSlog( 'Decoded url ' + name + ' : ' + url )
        #        break
        url = JP.GetVarHack(id_final)

        if not (url):
            VSlog('Rate, debug: ' + str(Liste_var))
            return False, False

        dialog().VSinfo('Ok, lien decode.', self.__sDisplayName, 15)

        api_call = self.__getHost() + "/stream/" + url + "?mime=true"

        if '::' in api_call:
            dialog().VSinfo('Possibles problemes d\'ip V6',
                            self.__sDisplayName, 5)
            xbmc.sleep(5 * 1000)

        VSlog(api_call)

        if (api_call):
            return True, api_call

        return False, False
示例#52
0
def ProtectstreamBypass(url):
    if url.startswith('/'):
        url = URL_MAIN[:-1] + url

    UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0'

    session = requests.Session()
    session.headers.update({
        'User-Agent':
        UA,
        'Referer':
        URL_MAIN,
        'Accept':
        'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    })

    try:
        response = session.get(url, timeout=5)
        response.raise_for_status()
    except requests.exceptions.RequestException as e:
        print('erreur ' + str(e))
        return ''

    sHtmlContent = response.text

    oParser = cParser()
    sPattern = 'var k=\"([^<>\"]*?)\";'
    aResult = oParser.parse(sHtmlContent, sPattern)

    if (aResult[0] == True):

        dialog().VSinfo('Décodage en cours', 'Patientez', 5)
        xbmc.sleep(5000)

        postdata = aResult[1][0]
        headers = {
            'User-Agent': UA,
            'Accept': '*/*',
            'Referer': url,
            'Content-Type': 'application/x-www-form-urlencoded',
        }
        session.headers.update(headers)
        data = {'k': postdata}

        try:
            response = session.post(URL_MAIN + 'embed_secur.php', data=data)
        except requests.exceptions.RequestException as e:
            print('erreur' + str(e))
            return ''

        data = response.text
        data = data.encode('utf-8', 'ignore')

        # VSlog(type(data))
        # VSlog(repr(data))

        # fh = open('c:\\test.txt', 'w')
        # fh.write(data)
        # fh.close()

        # Test de fonctionnement
        aResult = oParser.parse(data, sPattern)
        if aResult[0]:
            dialog().VSinfo('Lien encore protegé', 'Erreur', 5)
            return ''

        # recherche du lien embed
        sPattern = '<iframe src=["\']([^<>"\']+?)["\']'
        aResult = oParser.parse(data, sPattern)
        if (aResult[0] == True):
            return aResult[1][0]

        # recherche d'un lien redirigee
        sPattern = '<a class=.button. href=["\']([^<>"\']+?)["\'] target=._blank.>'
        aResult = oParser.parse(data, sPattern)
        if (aResult[0] == True):
            return aResult[1][0]

    return ''
示例#53
0
class cPlayer(xbmc.Player):

    ADDON = addon()
    DIALOG = dialog()

    def __init__(self, *args):

        sPlayerType = self.__getPlayerType()
        xbmc.Player.__init__(self, sPlayerType)

        self.Subtitles_file = []
        self.SubtitleActive = False

        oInputParameterHandler = cInputParameterHandler()
        #aParams = oInputParameterHandler.getAllParameter()
        #xbmc.log(str(aParams))

        self.sHosterIdentifier = oInputParameterHandler.getValue(
            'sHosterIdentifier')
        self.sTitle = oInputParameterHandler.getValue('sTitle')
        #self.sSite = oInputParameterHandler.getValue('site')
        self.sSite = oInputParameterHandler.getValue('siteUrl')
        self.sThumbnail = xbmc.getInfoLabel('ListItem.Art(thumb)')

        self.playBackEventReceived = False
        self.playBackStoppedEventReceived = False
        self.forcestop = False

        VSlog('player initialized')

    def clearPlayList(self):
        oPlaylist = self.__getPlayList()
        oPlaylist.clear()

    def __getPlayList(self):
        return xbmc.PlayList(xbmc.PLAYLIST_VIDEO)

    def addItemToPlaylist(self, oGuiElement):
        oGui = cGui()
        oListItem = oGui.createListItem(oGuiElement)
        self.__addItemToPlaylist(oGuiElement, oListItem)

    def __addItemToPlaylist(self, oGuiElement, oListItem):
        oPlaylist = self.__getPlayList()
        oPlaylist.add(oGuiElement.getMediaUrl(), oListItem)

    def AddSubtitles(self, files):
        if isinstance(files, basestring):
            self.Subtitles_file.append(files)
        else:
            self.Subtitles_file = files

    def run(self, oGuiElement, sTitle, sUrl):

        self.totalTime = 0
        self.currentTime = 0

        sPluginHandle = cPluginHandler().getPluginHandle()

        oGui = cGui()
        item = oGui.createListItem(oGuiElement)
        item.setPath(oGuiElement.getMediaUrl())

        #meta = {'label': oGuiElement.getTitle(), 'title': oGuiElement.getTitle()}
        #item = xbmcgui.ListItem(path=sUrl, iconImage='DefaultVideo.png', thumbnailImage=self.sThumbnail)
        #item.setInfo(type='Video', infoLabels=meta)

        #Sous titres
        if (self.Subtitles_file):
            try:
                item.setSubtitles(self.Subtitles_file)
                VSlog('Load SubTitle :' + str(self.Subtitles_file))
                self.SubtitleActive = True
            except:
                VSlog("Can't load subtitle:" + str(self.Subtitles_file))

        player_conf = self.ADDON.getSetting('playerPlay')

        #Si lien dash, methode prioritaire
        if sUrl.endswith('.mpd'):
            if isKrypton() == True:
                self.enable_addon('inputstream.adaptive')
                item.setProperty('inputstreamaddon', 'inputstream.adaptive')
                item.setProperty('inputstream.adaptive.manifest_type', 'mpd')
                xbmcplugin.setResolvedUrl(sPluginHandle, True, listitem=item)
                VSlog('Player use inputstream addon')
            else:
                dialog().VSerror('Nécessite kodi 17 minimum')
                return
        #1 er mode de lecture
        elif (player_conf == '0'):
            self.play(sUrl, item)
            VSlog('Player use Play() method')
        #2 eme mode non utilise
        elif (player_conf == 'neverused'):
            xbmc.executebuiltin('PlayMedia(' + sUrl + ')')
            VSlog('Player use PlayMedia() method')
        #3 eme mode (defaut)
        else:
            xbmcplugin.setResolvedUrl(sPluginHandle, True, item)
            VSlog('Player use setResolvedUrl() method')

        #Attend que le lecteur demarre, avec un max de 20s
        for _ in xrange(20):
            if self.playBackEventReceived:
                break
            xbmc.sleep(1000)

        #active/desactive les sous titres suivant l'option choisie dans la config
        if (self.SubtitleActive):
            if (self.ADDON.getSetting('srt-view') == 'true'):
                self.showSubtitles(True)
                self.DIALOG.VSinfo('Sous-titres chargés', 'Sous-Titres', 5)
            else:
                self.showSubtitles(False)
                self.DIALOG.VSinfo(
                    'Sous-titres chargés, vous pouvez les activer',
                    'Sous-Titres', 15)

        while self.isPlaying() and not self.forcestop:
            #while not xbmc.abortRequested:
            try:
                self.currentTime = self.getTime()
                self.totalTime = self.getTotalTime()

                #xbmc.log(str(self.currentTime))

            except:
                pass
                #break
            xbmc.sleep(1000)

        if not self.playBackStoppedEventReceived:
            self.onPlayBackStopped()

        #Uniquement avec la lecture avec play()
        if (player_conf == '0'):
            r = xbmcplugin.addDirectoryItem(handle=sPluginHandle,
                                            url=sUrl,
                                            listitem=item,
                                            isFolder=False)
            #xbmcplugin.endOfDirectory(sPluginHandle, True, False, False)
            return r

        VSlog('Closing player')

    #fonction light servant par exmple pour visualiser les DL ou les chaines de TV
    def startPlayer(self):
        oPlayList = self.__getPlayList()
        self.play(oPlayList)

    def onPlayBackEnded(self):
        self.onPlayBackStopped()

    #Attention pas de stop, si on lance une seconde video sans fermer la premiere
    def onPlayBackStopped(self):
        VSlog('player stoped')
        self.playBackStoppedEventReceived = True

        #calcul le temp de lecture
        pourcent = 0
        if self.totalTime > 0:
            pourcent = float('%.2f' % (self.currentTime / self.totalTime))
        if (pourcent > 0.90):

            # Marqué VU dans la BDD matrix
            cGui().setWatched()

            # Marqué VU dans les comptes perso
            try:
                tmdb_session = self.ADDON.getSetting('tmdb_session')
                if tmdb_session:
                    self.__getWatchlist('tmdb')
                bstoken = self.ADDON.getSetting('bstoken')
                if bstoken:
                    self.__getWatchlist('trakt')
            except:
                pass

        #xbmc.executebuiltin('Container.Refresh')

    def onPlayBackStarted(self):
        VSlog('player started')

        #Si on recoit une nouvelle fois l'event, c'est que ca buggue, on stope tout
        if self.playBackEventReceived:
            self.forcestop = True
            return

        self.playBackEventReceived = True

    def __getWatchlist(self, sAction):

        if sAction == 'tmdb':
            plugins = __import__('resources.sites.themoviedb_org',
                                 fromlist=['themoviedb_org'])
            function = getattr(plugins, 'getWatchlist')
            function()
        elif sAction == 'trakt':
            #plugins = __import__('resources.lib.trakt', fromlist=['cTrakt'])
            plugins = __import__('resources.lib.trakt',
                                 fromlist=['trakt']).cTrakt()
            function = getattr(plugins, 'getWatchlist')
            function()

        return

    def __getPlayerType(self):
        sPlayerType = self.ADDON.getSetting('playerType')

        try:
            if (sPlayerType == '0'):
                VSlog('playertype from config: auto')
                return xbmc.PLAYER_CORE_AUTO

            if (sPlayerType == '1'):
                VSlog('playertype from config: mplayer')
                return xbmc.PLAYER_CORE_MPLAYER

            if (sPlayerType == '2'):
                VSlog('playertype from config: dvdplayer')
                return xbmc.PLAYER_CORE_DVDPLAYER
        except:
            return False

    def enable_addon(self, addon):
        #import json
        #sCheck = {'jsonrpc': '2.0','id': 1,'method': 'Addons.GetAddonDetails','params': {'addonid':'inputstream.adaptive','properties': ['enabled']}}
        #response = xbmc.executeJSONRPC(json.dumps(sCheck))
        #data = json.loads(response)
        #if not 'error' in data.keys():
        #if data['result']['addon']['enabled'] == False:

        if xbmc.getCondVisibility(
                'System.HasAddon(inputstream.adaptive)') == 0:
            do_json = '{"jsonrpc":"2.0","id":1,"method":"Addons.SetAddonEnabled","params":{"addonid":"inputstream.adaptive","enabled":true}}'
            query = xbmc.executeJSONRPC(do_json)
            VSlog("Activation d'inputstream.adaptive")
        else:
            VSlog('inputstream.adaptive déjà activé')
示例#54
0
def Display_protected_link():
    # VSlog('Display_protected_link')
    oGui = cGui()
    oParser = cParser()
    oInputParameterHandler = cInputParameterHandler()
    sMovieTitle = oInputParameterHandler.getValue('sMovieTitle')
    # baseUrl = oInputParameterHandler.getValue('baseUrl')
    sUrl = oInputParameterHandler.getValue('siteUrl')
    sThumb = oInputParameterHandler.getValue('sThumb')

    # Ne marche pas
    if (False):
        code = {
            '123455600123455602123455610123455615': 'http://uptobox.com/',
            '1234556001234556071234556111234556153': 'http://turbobit.net/',
            '123455600123455605123455615': 'http://ul.to/',
            '123455600123455608123455610123455615': 'http://nitroflare.com/',
            '123455601123455603123455610123455615123455617':
            'https://1fichier.com/?',
            '123455600123455606123455611123455615': 'http://rapidgator.net/'
        }

        for k in code:
            match = re.search(k + '(.+)$', sUrl)
            if match:
                sHosterUrl = code[k] + match.group(1)
                sHosterUrl = sHosterUrl.replace('123455615', '/')
                oHoster = cHosterGui().checkHoster(sHosterUrl)
                if (oHoster != False):
                    oHoster.setDisplayName(sMovieTitle)
                    oHoster.setFileName(sMovieTitle)
                    cHosterGui().showHoster(oGui, oHoster, sHosterUrl, sThumb)
                oGui.setEndOfDirectory()
                return

    # Est ce un lien dl-protect ?
    if sUrl:

        sHtmlContent = DecryptDlProtecte(sUrl)

        if sHtmlContent:
            # Si redirection
            if sHtmlContent.startswith('http'):
                aResult_dlprotecte = (True, [sHtmlContent])
            else:
                sPattern_dlprotecte = '<div class="alert alert-primary".+?href="(.+?)"'
                aResult_dlprotecte = oParser.parse(sHtmlContent,
                                                   sPattern_dlprotecte)

        else:
            dialog().VSok('Erreur décryptage du lien')
            aResult_dlprotecte = (False, False)

    # Si lien normal
    else:
        if not sUrl.startswith('http'):
            sUrl = 'http://' + sUrl
        aResult_dlprotecte = (True, [sUrl])

    if (aResult_dlprotecte[0]):

        episode = 1

        for aEntry in aResult_dlprotecte[1]:
            sHosterUrl = aEntry

            sTitle = sMovieTitle
            if len(aResult_dlprotecte[1]) > 1:
                sTitle = sMovieTitle + ' episode ' + episode

            episode += 1

            oHoster = cHosterGui().checkHoster(sHosterUrl)
            if (oHoster != False):
                oHoster.setDisplayName(sTitle)
                oHoster.setFileName(sTitle)
                cHosterGui().showHoster(oGui, oHoster, sHosterUrl, sThumb)

    oGui.setEndOfDirectory()
示例#55
0
class cRequestHandler:
    REQUEST_TYPE_GET = 0
    REQUEST_TYPE_POST = 1
    DIALOG = dialog()
    ADDON = addon()

    def __init__(self, sUrl):
        self.__sUrl = sUrl
        self.__sRealUrl = ''
        self.__cType = 0
        self.__aParamaters = {}
        self.__aParamatersLine = ''
        self.__aHeaderEntries = []
        self.removeBreakLines(True)
        self.removeNewLines(True)
        self.__setDefaultHeader()
        self.__timeout = 30
        self.__bRemoveNewLines = False
        self.__bRemoveBreakLines = False
        self.__sResponseHeader = ''
        self.BUG_SSL = False

    def removeNewLines(self, bRemoveNewLines):
        self.__bRemoveNewLines = bRemoveNewLines

    def removeBreakLines(self, bRemoveBreakLines):
        self.__bRemoveBreakLines = bRemoveBreakLines

    def setRequestType(self, cType):
        self.__cType = cType

    def setTimeout(self, valeur):
        self.__timeout = valeur

    def addHeaderEntry(self, sHeaderKey, sHeaderValue):
        for sublist in self.__aHeaderEntries:
            if sHeaderKey in sublist:
                self.__aHeaderEntries.remove(sublist)
        aHeader = {sHeaderKey: sHeaderValue}
        self.__aHeaderEntries.append(aHeader)

    def addParameters(self, sParameterKey, mParameterValue):
        self.__aParamaters[sParameterKey] = mParameterValue

    def addParametersLine(self, mParameterValue):
        self.__aParamatersLine = mParameterValue

    #egg addMultipartFiled({'sess_id':sId,'upload_type':'url','srv_tmp_url':sTmp})
    def addMultipartFiled(self, fields):
        mpartdata = MPencode(fields)
        self.__aParamatersLine = mpartdata[1]
        self.addHeaderEntry('Content-Type', mpartdata[0])
        self.addHeaderEntry('Content-Length', len(mpartdata[1]))

    #Je sais plus si elle gere les doublons
    def getResponseHeader(self):
        return self.__sResponseHeader

    # url after redirects
    def getRealUrl(self):
        return self.__sRealUrl

    def GetCookies(self):
        if 'Set-Cookie' in self.__sResponseHeader:
            import re

            #cookie_string = self.__sResponseHeader.getheaders('set-cookie')
            #c = ''
            #for i in cookie_string:
            #    c = c + i + ', '
            c = self.__sResponseHeader.getheader('set-cookie')

            c2 = re.findall('(?:^|,) *([^;,]+?)=([^;,\/]+?);', c)
            if c2:
                cookies = ''
                for cook in c2:
                    cookies = cookies + cook[0] + '=' + cook[1] + ';'
                cookies = cookies[:-1]
                return cookies
        return ''

    def request(self):
        #Supprimee car deconne si url contient ' ' et '+' en meme temps
        #self.__sUrl = self.__sUrl.replace(' ', '+')
        return self.__callRequest()

    def getRequestUri(self):
        return self.__sUrl + '?' + urllib.urlencode(self.__aParamaters)

    def __setDefaultHeader(self):
        self.addHeaderEntry(
            'User-Agent',
            'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'
        )
        self.addHeaderEntry('Accept-Language',
                            'fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3')
        self.addHeaderEntry('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7')

    def __callRequest(self):
        if self.__aParamatersLine:
            sParameters = self.__aParamatersLine
        else:
            sParameters = urllib.urlencode(self.__aParamaters)

        if (self.__cType == cRequestHandler.REQUEST_TYPE_GET):
            if (len(sParameters) > 0):
                if (self.__sUrl.find('?') == -1):
                    self.__sUrl = self.__sUrl + '?' + str(sParameters)
                    sParameters = ''
                else:
                    self.__sUrl = self.__sUrl + '&' + str(sParameters)
                    sParameters = ''

        if (len(sParameters) > 0):
            oRequest = urllib2.Request(self.__sUrl, sParameters)
        else:
            oRequest = urllib2.Request(self.__sUrl)

        for aHeader in self.__aHeaderEntries:
            for sHeaderKey, sHeaderValue in aHeader.items():
                oRequest.add_header(sHeaderKey, sHeaderValue)

        sContent = ''
        try:

            if self.BUG_SSL:
                VSlog('Retrying with SSL bug')
                import ssl
                gcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
                oResponse = urllib2.urlopen(oRequest,
                                            timeout=self.__timeout,
                                            context=gcontext)
            else:
                oResponse = urllib2.urlopen(oRequest, timeout=self.__timeout)

            sContent = oResponse.read()

            self.__sResponseHeader = oResponse.info()

            #compressed page ?
            if self.__sResponseHeader.get('Content-Encoding') == 'gzip':
                import zlib
                sContent = zlib.decompress(sContent, zlib.MAX_WBITS | 16)

            #https://bugs.python.org/issue4773
            self.__sRealUrl = oResponse.geturl()
            self.__sResponseHeader = oResponse.info()

            oResponse.close()

        except urllib2.HTTPError, e:
            if e.code == 503:

                #Protected by cloudFlare ?
                from resources.lib import cloudflare
                if cloudflare.CheckIfActive(e.read()):

                    cookies = self.GetCookies()
                    VSlog('Page protegee par cloudflare')
                    CF = cloudflare.CloudflareBypass()
                    sContent = CF.GetHtml(self.__sUrl, e.read(), cookies,
                                          sParameters, oRequest.headers)
                    self.__sRealUrl, self.__sResponseHeader = CF.GetReponseInfo(
                    )
                else:
                    sContent = e.read()
                    self.__sRealUrl = e.geturl()
                    self.__sResponseHeader = e.headers()

            else:
                try:
                    VSlog("%s (%d),%s" %
                          (self.ADDON.VSlang(30205), e.code, self.__sUrl))
                    self.__sRealUrl = e.geturl()
                    self.__sResponseHeader = e.headers
                    sContent = e.read()
                except:
                    sContent = ''

            if not sContent:
                self.DIALOG.VSerror(
                    "%s (%d),%s" %
                    (self.ADDON.VSlang(30205), e.code, self.__sUrl))
                return ''

        except urllib2.URLError, e:
            if 'CERTIFICATE_VERIFY_FAILED' in str(
                    e.reason) and self.BUG_SSL == False:
                self.BUG_SSL = True
                return self.__callRequest()

            self.DIALOG.VSerror(
                "%s (%s),%s" %
                (self.ADDON.VSlang(30205), e.reason, self.__sUrl))
            return ''
示例#56
0
class cHoster(iHoster):

    def __init__(self):
        self.__sDisplayName = 'DailyMotion'
        self.__sFileName = self.__sDisplayName
        self.__sHD = ''

    def getDisplayName(self):
        return  self.__sDisplayName

    def setDisplayName(self, sDisplayName):
        self.__sDisplayName = sDisplayName + ' [COLOR skyblue]' + self.__sDisplayName + '[/COLOR] [COLOR khaki]' + self.__sHD + '[/COLOR]'

    def setFileName(self, sFileName):
        self.__sFileName = sFileName

    def getFileName(self):
        return self.__sFileName

    def setHD(self, sHD):
        if 'hd' in sHD:
            self.__sHD = 'HD'
        else:
            self.__sHD = ''

    def getHD(self):
        return self.__sHD

    def getPluginIdentifier(self):
        return 'dailymotion'

    def isDownloadable(self):
        return True

    def isJDownloaderable(self):
        return True

    def getPattern(self):
        return ''
        
    def __getIdFromUrl(self):
        sPattern = "?([^<]+)"
        oParser = cParser()
        aResult = oParser.parse(self.__sUrl, sPattern)
        if (aResult[0] == True):
            return aResult[1][0]

        return ''
        
    def __modifyUrl(self, sUrl):
        if (sUrl.startswith('http://')):
            oRequestHandler = cRequestHandler(sUrl)
            oRequestHandler.request()
            sRealUrl = oRequestHandler.getRealUrl()
            self.__sUrl = sRealUrl
            return self.__getIdFromUrl()

        return sUrl
        
    def __getKey(self):
        oRequestHandler = cRequestHandler(self.__sUrl)
        sHtmlContent = oRequestHandler.request()
        sPattern = 'fkzd="(.+?)";'
        oParser = cParser()
        aResult = oParser.parse(sHtmlContent, sPattern)
        if (aResult[0] == True):
            aResult = aResult[1][0].replace('.', '%2E')
            return aResult

        return ''

    def setUrl(self, sUrl):
        self.__sUrl = str(sUrl)
        self.__sUrl = self.__sUrl.replace('http://dai.ly/', '')
        self.__sUrl = self.__sUrl.replace('http://www.dailymotion.com/', '')
        self.__sUrl = self.__sUrl.replace('https://www.dailymotion.com/', '')
        self.__sUrl = self.__sUrl.replace('embed/', '')
        self.__sUrl = self.__sUrl.replace('video/', '')
        self.__sUrl = self.__sUrl.replace('sequence/', '')
        self.__sUrl = self.__sUrl.replace('swf/', '')
        self.__sUrl = 'http://www.dailymotion.com/embed/video/' + str(self.__sUrl)

    def checkUrl(self, sUrl):
        return True

    def getUrl(self):
        return self.__sUrl

    def getMediaLink(self):
        return self.__getMediaLinkForGuest()

    def __getMediaLinkForGuest(self):
        api_call = False
        url=[]
        qua=[]
        
        #oRequest = cRequestHandler(self.__sUrl)
        #sHtmlContent = oRequest.request()
        
        request = urllib2.Request(self.__sUrl)
        request.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20100101 Firefox/22.0')
        request.add_header('Accept-Language', 'fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3')
        request.add_header('Cookie', "ff=off") #supprime le filtre parental
        
        try: 
            reponse = urllib2.urlopen(request)
        except urllib2.HTTPError, e:
            print e.read()
            print e.reason
            
        sHtmlContent = reponse.read()
        reponse.close()

        sHtmlContent=sHtmlContent.replace("\/", "\\")
        
        #fh = open('c:\\test.txt', "w")
        #fh.write(sHtmlContent)
        #fh.close()
        
        #print self.__sUrl
        
        oParser = cParser()

        sPattern =  '"live_rtsp_url":"(.+?)"'
        aResult = oParser.parse(sHtmlContent, sPattern)
        if (aResult[0] == True):
            url.append(aResult[1][0])
            qua.append('live')

        sPattern =  '"stream_h264_hd1080_url":"(.+?)"'
        aResult = oParser.parse(sHtmlContent, sPattern)
        if (aResult[0] == True):
            url.append(aResult[1][0])
            qua.append('1080p')

        sPattern =  '"stream_h264_hd_url":"(.+?)"'
        aResult = oParser.parse(sHtmlContent, sPattern)
        if (aResult[0] == True):
            url.append(aResult[1][0])
            qua.append('720p')

        sPattern =  '"stream_h264_hq_url":"(.+?)"'
        aResult = oParser.parse(sHtmlContent, sPattern)
        if (aResult[0] == True):
            url.append(aResult[1][0])
            qua.append('high')

        sPattern =  '"stream_h264_url":"(.+?)"'
        aResult = oParser.parse(sHtmlContent, sPattern)
        if (aResult[0] == True):
            url.append(aResult[1][0])
            qua.append('low')

        sPattern =  '"stream_h264_ld_url":"(.+?)"'
        aResult = oParser.parse(sHtmlContent, sPattern)
        if (aResult[0] == True):
            url.append(aResult[1][0])
            qua.append('low 2')

        aResult = re.findall(r'{"source":"type":"application\\x-mpegURL","url":"(.+?)"}', sHtmlContent)
        if (aResult):
            url.append(aResult[0])
            qua.append('Live')

        #pattern plus generaliste
        aResult = re.findall(r'"([0-9]+)":\[{"type":"application.+?","url":".+?"}.+?"url":"(.+?)"}]', sHtmlContent)
        #aResult = re.findall(r'{"type":"video.+?","url":"(.+?)"}],"(\d+)"', sHtmlContent)
        if (aResult):
            for aEntry in aResult:
                url.append(aEntry[1])
                qua.append(str(aEntry[0]) + 'p')

            api_call = dialog().VSselectqual(qua, url)

        if (api_call):
            return True, api_call
        
        return False, False
示例#57
0
    def __getMediaLinkForGuest(self):
        api_call = False

        oParser = cParser()

        #on recupere le host atuel
        HOST = self.GetHost(self.__sUrl)

        #on recupere l'ID
        sId = self.__getIdFromUrl(self.__sUrl)
        if sId == '':
            VSlog("Id prb")
            return False, False

        #on ne garde que les chiffres
        #sId = re.sub(r'-.+', '', sId)

        #on cherche la vraie url
        sHtmlContent = self.GetRedirectHtml(self.__sUrl, sId)

        #fh = open('c:\\test.txt', "w")
        #fh.write(sHtmlContent)
        #fh.close()

        sPattern = 'href=["\'](https*:\/\/www\.flashx[^"\']+)'
        AllUrl = re.findall(sPattern, sHtmlContent, re.DOTALL)
        #VSlog(str(AllUrl))

        #Disabled for the moment
        if (False):
            if AllUrl:
                # Need to find which one is the good link
                # Use the len don't work
                for i in AllUrl:
                    if i[0] == '':
                        web_url = i[1]
            else:
                return False, False
        else:
            web_url = AllUrl[0]

        web_url = AllUrl[0]

        #Requests to unlock video
        #unlock fake video
        LoadLinks(sHtmlContent)
        #unlock bubble
        unlock = False
        url2 = re.findall('["\']([^"\']+?\.js\?cache.+?)["\']', sHtmlContent,
                          re.DOTALL)
        if not url2:
            VSlog('No special unlock url find')
        for i in url2:
            unlock = UnlockUrl(i)
            if unlock:
                break

        if not unlock:
            VSlog('No special unlock url working')
            return False, False

        #get the page
        sHtmlContent = self.GetRedirectHtml(web_url, sId, True)

        if sHtmlContent == False:
            VSlog('Passage en mode barbare')
            #ok ca a rate on passe toutes les url de AllUrl
            for i in AllUrl:
                if not i == web_url:
                    sHtmlContent = self.GetRedirectHtml(i, sId, True)
                    if sHtmlContent:
                        break

        if not sHtmlContent:
            return False, False

        if 'reload the page!' in sHtmlContent:
            #VSlog("page bloquée")

            #On recupere la bonne url
            sGoodUrl = web_url

            #on recupere la page de refresh
            sPattern = 'reload the page! <a href="([^"]+)">!! <b>'
            aResult = re.findall(sPattern, sHtmlContent)
            if not aResult:
                return False, False
            sRefresh = aResult[0]

            #on recupere le script de debloquage
            sPattern = "<script type='text/javascript' src='([^']+)'><\/script>"
            aResult = re.findall(sPattern, sHtmlContent)
            if not aResult:
                return False, False

            deblockurl = aResult[0]
            if deblockurl.startswith('//'):
                deblockurl = 'http:' + deblockurl

            #on debloque la page
            sHtmlContent = self.GetRedirectHtml(deblockurl, sId)

            #lien speciaux ?
            if sRefresh.startswith('./'):
                sRefresh = 'http://' + self.GetHost(sGoodUrl) + sRefresh[1:]

            #on rafraichit la page
            sHtmlContent = self.GetRedirectHtml(sRefresh, sId)

            #et on re-recupere la page
            sHtmlContent = self.GetRedirectHtml(sGoodUrl, sId)

        if (False):

            #A t on le lien code directement?
            sPattern = "(\s*eval\s*\(\s*function(?:.|\s)+?)<\/script>"
            aResult = re.findall(sPattern, sHtmlContent)

            if (aResult):
                #VSlog( "lien code")

                AllPacked = re.findall(
                    '(eval\(function\(p,a,c,k.*?)\s+<\/script>', sHtmlContent,
                    re.DOTALL)
                if AllPacked:
                    for i in AllPacked:
                        sUnpacked = cPacker().unpack(i)
                        sHtmlContent = sUnpacked
                        if "file" in sHtmlContent:
                            break
                else:
                    return False, False

        #decodage classique
        sPattern = '{file:"([^",]+)",label:"([^"<>,]+)"}'
        sPattern = '{src: *\'([^"\',]+)\'.+?label: *\'([^"<>,\']+)\''
        aResult = oParser.parse(sHtmlContent, sPattern)

        #VSlog(str(aResult))

        if (aResult[0] == True):
            #initialisation des tableaux
            url = []
            qua = []

            #Remplissage des tableaux
            for i in aResult[1]:
                url.append(str(i[0]))
                qua.append(str(i[1]))

            #Affichage du tableau
            api_call = dialog().VSselectqual(qua, url)

        if (api_call):
            return True, api_call

        return False, False
示例#58
0
    def __callRequest(self, jsonDecode=False, xmlDecode=False):
        if self.__enableDNS:
            self.save_getaddrinfo = socket.getaddrinfo
            socket.getaddrinfo = self.new_getaddrinfo

        if self.__aParamatersLine:
            sParameters = self.__aParamatersLine
        else:
            sParameters = self.__aParamaters

        if (self.__cType == cRequestHandler.REQUEST_TYPE_GET):
            if (len(sParameters) > 0):
                if (self.__sUrl.find('?') == -1):
                    self.__sUrl = self.__sUrl + '?' + str(sParameters)
                    sParameters = ''
                else:
                    self.__sUrl = self.__sUrl + '&' + str(sParameters)
                    sParameters = ''

        sContent = ''

        if self.BUG_SSL == True:
            self.verify = False

        if self.__cType == cRequestHandler.REQUEST_TYPE_GET:
            method = "GET"
        else:
            method = "POST"

        if self.forceIPV4:
            urllib3_cn.allowed_gai_family = self.allowed_gai_family

        oResponse = None
        try:
            _request = Request(method,
                               self.__sUrl,
                               headers=self.__aHeaderEntries)
            if method in ['POST']:
                _request.data = sParameters

            if self.__Cookie:
                _request.cookies = self.__Cookie

            if self.json:
                _request.json = self.json

            prepped = _request.prepare()
            self.s.headers.update(self.__aHeaderEntries)

            oResponse = self.s.send(prepped,
                                    timeout=self.__timeout,
                                    allow_redirects=self.redirects,
                                    verify=self.verify)
            self.__sResponseHeader = oResponse.headers
            self.__sRealUrl = oResponse.url

            if jsonDecode == True:
                sContent = oResponse.json()
            elif xmlDecode == True:
                sContent = oResponse.content
            else:
                sContent = oResponse.content
                #Necessaire pour Python 3
                if isMatrix() and not 'youtube' in oResponse.url:
                    try:
                        sContent = sContent.decode()
                    except:
                        #Decodage minimum obligatoire.
                        try:
                            sContent = sContent.decode('unicode-escape')
                        except:
                            pass

        except ConnectionError as e:
            # Retry with DNS only if addon is present
            if 'getaddrinfo failed' in str(
                    e) or 'Failed to establish a new connection' in str(
                        e) and self.__enableDNS == False:
                # Retry with DNS only if addon is present
                import xbmcvfs
                if xbmcvfs.exists(
                        'special://home/addons/script.module.dnspython/'):
                    self.__enableDNS = True
                    return self.__callRequest()
                else:
                    error_msg = addon().VSlang(30470)
                    dialog().VSerror(error_msg)
                    sContent = ''
            else:
                sContent = ''
                return False

        except RequestException as e:
            if 'CERTIFICATE_VERIFY_FAILED' in str(e) and self.BUG_SSL == False:
                self.BUG_SSL = True
                return self.__callRequest()
            elif 'getaddrinfo failed' in str(e) and self.__enableDNS == False:
                # Retry with DNS only if addon is present
                import xbmcvfs
                if xbmcvfs.exists(
                        'special://home/addons/script.module.dnspython/'):
                    self.__enableDNS = True
                    return self.__callRequest()
                else:
                    error_msg = addon().VSlang(30470)
            else:
                error_msg = "%s (%s),%s" % (addon().VSlang(30205), e,
                                            self.__sUrl)

            dialog().VSerror(error_msg)
            sContent = ''

        if oResponse != None:
            if oResponse.status_code in [503, 403]:
                if not "Forbidden" in sContent:
                    #Default
                    CLOUDPROXY_ENDPOINT = 'http://' + addon().getSetting(
                        'ipaddress') + ':8191/v1'

                    json_session = False

                    try:
                        json_session = post(CLOUDPROXY_ENDPOINT,
                                            headers=self.__aHeaderEntries,
                                            json={'cmd': 'sessions.list'})
                    except:
                        dialog().VSerror("%s" % (
                            "Page protege par Cloudflare, veuillez executer  FlareSolverr."
                        ))

                    if json_session:
                        #On regarde si une session existe deja.
                        if json_session.json()['sessions']:
                            cloudproxy_session = json_session.json(
                            )['sessions'][0]
                        else:
                            json_session = post(CLOUDPROXY_ENDPOINT,
                                                headers=self.__aHeaderEntries,
                                                json={
                                                    'cmd': 'sessions.create'
                                                }).json()
                            cloudproxy_session = json_session['session']

                        self.__aHeaderEntries[
                            'Content-Type'] = 'application/x-www-form-urlencoded' if (
                                method == 'post') else 'application/json'

                        #Ont fait une requete.
                        json_response = post(
                            CLOUDPROXY_ENDPOINT,
                            headers=self.__aHeaderEntries,
                            json={
                                'cmd':
                                'request.%s' % method.lower(),
                                'url':
                                self.__sUrl,
                                'session':
                                cloudproxy_session,
                                'postData':
                                '%s' % urlEncode(sParameters) if
                                (method.lower() == 'post') else ''
                            })

                        http_code = json_response.status_code
                        response = json_response.json()
                        if 'solution' in response:
                            if self.__sUrl != response['solution']['url']:
                                self.__sRealUrl = response['solution']['url']

                            sContent = response['solution']['response']

            if oResponse and not sContent:
                #Ignorer ces deux codes erreurs.
                ignoreStatus = [200, 302]
                if oResponse.status_code not in ignoreStatus:
                    dialog().VSerror("%s (%d),%s" %
                                     (addon().VSlang(30205),
                                      oResponse.status_code, self.__sUrl))

        if sContent:
            if (self.__bRemoveNewLines == True):
                sContent = sContent.replace("\n", "")
                sContent = sContent.replace("\r\t", "")

            if (self.__bRemoveBreakLines == True):
                sContent = sContent.replace("&nbsp;", "")

        if self.__enableDNS:
            socket.getaddrinfo = self.save_getaddrinfo
            self.__enableDNS = False

        return sContent
class cHosterGui:

    SITE_NAME = 'cHosterGui'
    ADDON = addon()
    DIALOG = dialog()

    # step 1 - bGetRedirectUrl in ein extra optionsObject verpacken
    def showHoster(self,
                   oGui,
                   oHoster,
                   sMediaUrl,
                   sThumbnail,
                   bGetRedirectUrl=False):

        oInputParameterHandler = cInputParameterHandler()

        oGuiElement = cGuiElement()
        oGuiElement.setSiteName(self.SITE_NAME)
        # oGuiElement.setFunction('showHosterMenu')
        oGuiElement.setFunction('play')
        oGuiElement.setTitle(oHoster.getDisplayName())
        # oGuiElement.setThumbnail(sThumbnail)
        # if (oInputParameterHandler.exist('sMeta')):
        # sMeta = oInputParameterHandler.getValue('sMeta')
        # oGuiElement.setMeta(int(sMeta))

        oGuiElement.setFileName(oHoster.getFileName())
        oGuiElement.getInfoLabel()
        if sThumbnail:
            oGuiElement.setThumbnail(sThumbnail)

        # oGuiElement.setMeta(1)
        oGuiElement.setIcon('host.png')

        oOutputParameterHandler = cOutputParameterHandler()
        oOutputParameterHandler.addParameter('sMediaUrl', sMediaUrl)
        oOutputParameterHandler.addParameter('sHosterIdentifier',
                                             oHoster.getPluginIdentifier())
        oOutputParameterHandler.addParameter('bGetRedirectUrl',
                                             bGetRedirectUrl)
        oOutputParameterHandler.addParameter('sFileName',
                                             oHoster.getFileName())
        oOutputParameterHandler.addParameter('sTitleWatched',
                                             oGuiElement.getTitleWatched())
        oOutputParameterHandler.addParameter('sTitle',
                                             oHoster.getDisplayName())
        oOutputParameterHandler.addParameter('sId', 'cHosterGui')
        oOutputParameterHandler.addParameter('siteUrl', sMediaUrl)
        # oOutputParameterHandler.addParameter('sFav', 'play')
        # oOutputParameterHandler.addParameter('sCat', '4')

        # nouveaux pour la lecture.
        if oInputParameterHandler.exist('sCat'):
            sCat = oInputParameterHandler.getValue('sCat')
            oGuiElement.setCat(sCat)
            oOutputParameterHandler.addParameter('sCat', sCat)
        else:
            oGuiElement.setCat('4')

        # context playlit menu
        oContext = cContextElement()
        oContext.setFile('cHosterGui')
        oContext.setSiteName(self.SITE_NAME)
        oContext.setFunction('addToPlaylist')
        oContext.setTitle(self.ADDON.VSlang(30201))
        oContext.setOutputParameterHandler(oOutputParameterHandler)
        oGuiElement.addContextItem(oContext)

        # Download menu
        if oHoster.isDownloadable():
            oContext = cContextElement()
            oContext.setFile('cDownload')
            oContext.setSiteName('cDownload')
            oContext.setFunction('AddtoDownloadList')
            oContext.setTitle(self.ADDON.VSlang(30202))
            oContext.setOutputParameterHandler(oOutputParameterHandler)
            oGuiElement.addContextItem(oContext)

        if oHoster.isDownloadable():
            # Beta context download and view menu
            oContext = cContextElement()
            oContext.setFile('cDownload')
            oContext.setSiteName('cDownload')
            oContext.setFunction('AddtoDownloadListandview')
            oContext.setTitle(self.ADDON.VSlang(30326))
            oContext.setOutputParameterHandler(oOutputParameterHandler)
            oGuiElement.addContextItem(oContext)

        # Upload menu uptobox
        if cInputParameterHandler().getValue(
                'site') != 'siteuptobox' and self.ADDON.getSetting(
                    'hoster_uptobox_premium') == 'true':
            host = oHoster.getPluginIdentifier()
            accept = [
                'uptobox', 'uptostream', 'onefichier', 'uploaded', 'uplea'
            ]
            for i in accept:
                if host == i:
                    oGui.CreateSimpleMenu(oGuiElement, oOutputParameterHandler,
                                          'siteuptobox', 'siteuptobox',
                                          'UptomyAccount',
                                          self.ADDON.VSlang(30325))

        # onefichier
        if cInputParameterHandler().getValue(
                'site') != 'siteonefichier' and self.ADDON.getSetting(
                    'hoster_onefichier_premium') == 'true':
            host = oHoster.getPluginIdentifier()
            accept = 'onefichier'  # les autres ne fonctionnent pas
            if host == accept:
                oGui.CreateSimpleMenu(oGuiElement, oOutputParameterHandler,
                                      'siteonefichier', 'siteonefichier',
                                      'UptomyAccount', '1fichier')

        # context FAV menu
        oGui.createContexMenuFav(oGuiElement, oOutputParameterHandler)

        # context Library menu
        oGui.CreateSimpleMenu(oGuiElement, oOutputParameterHandler,
                              'cLibrary', 'cLibrary', 'setLibrary',
                              self.ADDON.VSlang(30324))

        # bug
        oGui.addHost(oGuiElement, oOutputParameterHandler)

    def checkHoster(self, sHosterUrl):
        # securite
        if not sHosterUrl:
            return False

        # Petit nettoyage
        sHosterUrl = sHosterUrl.split('|')[0]
        sHosterUrl = sHosterUrl.lower()

        # Recuperation du host
        try:
            sHostName = sHosterUrl.split('/')[2]
        except:
            sHostName = sHosterUrl

        # L'user a active l'url resolver ?
        if self.ADDON.getSetting('UserUrlResolver') == 'true':
            import urlresolver
            hmf = urlresolver.HostedMediaFile(url=sHosterUrl)
            if hmf.valid_url():
                tmp = self.getHoster('resolver')
                RH = sHosterUrl.split('/')[2]
                RH = RH.replace('www.', '')
                tmp.setRealHost(RH.split('.')[0].upper())
                return tmp

        # L'user a active alldebrid ?

        if self.ADDON.getSetting('hoster_alldebrid_premium') == 'true':
            return self.getHoster('alldebrid')

        # Gestion classique
        if ('viki' in sHostName):
            return self.getHoster('viki')
        if ('streamz' in sHostName):
            return self.getHoster('streamz')
        if ('streamax' in sHostName):
            return self.getHoster('streamax')
        if ('gounlimited' in sHostName):
            return self.getHoster('gounlimited')
        if ('xdrive' in sHostName):
            return self.getHoster('xdrive')
        if ('facebook' in sHostName):
            return self.getHoster('facebook')
        if ('mixdrop' in sHostName):
            return self.getHoster('mixdrop')
        if ('mixloads' in sHostName):
            return self.getHoster('mixloads')
        if ('vidoza' in sHostName):
            return self.getHoster('vidoza')
        if ('youtube' in sHostName) or ('youtu.be' in sHostName):
            return self.getHoster('youtube')
        if ('rutube' in sHostName):
            return self.getHoster('rutube')
        if ('vk.com' in sHostName):
            return self.getHoster('vk')
        if ('vkontakte' in sHostName):
            return self.getHoster('vk')
        if ('vkcom' in sHostName):
            return self.getHoster('vk')
        if ('megawatch' in sHostName):
            return self.getHoster('megawatch')
        if ('playvidto' in sHostName):
            return self.getHoster('vidto')
        # vidtodo et clone
        if ('vidtodo' in sHostName) or ('vixtodo' in sHostName):
            return self.getHoster('vidtodo')
        if ('viddoto' in sHostName):
            return self.getHoster('vidtodo')
        if ('vidstodo' in sHostName):
            return self.getHoster('vidtodo')

        if ('vidzi' in sHostName):
            return self.getHoster('vidzi')
        if ('vcstream' in sHostName):
            return self.getHoster('vidcloud')
        if ('filetrip' in sHostName):
            return self.getHoster('filetrip')
        if ('uptostream' in sHostName):
            return self.getHoster('uptostream')
        if ('dailymotion' in sHostName) or ('dai.ly' in sHostName):
            try:
                if 'stream' in sHosterUrl:
                    return self.getHoster('lien_direct')
            except:
                return self.getHoster('dailymotion')
        if ('livestream' in sHostName):
            return self.getHoster('lien_direct')
        if ('flashx' in sHostName):
            return self.getHoster('flashx')
        if ('filez' in sHostName):
            return self.getHoster('flashx')
        if ('mystream' in sHostName) or ('mstream' in sHostName):
            return self.getHoster('mystream')
        if ('streamingentiercom/videophp?type=speed' in sHosterUrl):
            return self.getHoster('speedvideo')
        if ('speedvideo' in sHostName):
            return self.getHoster('speedvideo')
        if ('speedvid' in sHostName):
            return self.getHoster('speedvid')
        if ('netu' in sHostName) or ('hqq' in sHostName) or (
                'waaw' in sHostName) or ('vizplay' in sHostName):
            return self.getHoster('netu')
        if ('upstream' in sHostName):
            return self.getHoster('upstream')
        if ('mail.ru' in sHostName):
            return self.getHoster('mailru')
        if ('onevideo' in sHostName):
            return self.getHoster('onevideo')
        if ('googlevideo' in sHostName):
            return self.getHoster('googlevideo')
        if ('picasaweb' in sHostName):
            return self.getHoster('googlevideo')
        if ('googleusercontent' in sHostName):
            return self.getHoster('googlevideo')
        if ('playreplay' in sHostName):
            return self.getHoster('playreplay')
        if ('ok.ru' in sHostName) or ('odnoklassniki' in sHostName):
            return self.getHoster('ok_ru')
        if ('vimeo' in sHostName):
            return self.getHoster('vimeo')
        if ('prostream' in sHostName):
            return self.getHoster('prostream')
        if ('vidfast' in sHostName):
            return self.getHoster('vidfast')
        if ('thevideo' in sHostName) or ('video.tt'
                                         in sHostName) or ('vev.io'
                                                           in sHostName):
            return self.getHoster('thevideo_me')
        if ('uqload' in sHostName):
            return self.getHoster('uqload')
        if ('letwatch' in sHostName):
            return self.getHoster('letwatch')
        if ('letsupload' in sHostName):
            return self.getHoster('letsupload')
        if ('filepup' in sHostName):
            return self.getHoster('filepup')
        if ('vimple.ru' in sHostName):
            return self.getHoster('vimple')
        if ('wstream' in sHostName):
            return self.getHoster('wstream')
        if ('watchvideo' in sHostName):
            return self.getHoster('watchvideo')
        if ('drive.google.com' in sHostName):
            return self.getHoster('googledrive')
        if ('docs.google.com' in sHostName):
            return self.getHoster('googledrive')
        if ('vidwatch' in sHostName):
            return self.getHoster('vidwatch')
        if ('up2stream' in sHostName):
            return self.getHoster('up2stream')
        if ('vidbm' in sHostName):
            return self.getHoster('vidbm')
        if ('tune' in sHostName):
            return self.getHoster('tune')
        if ('vidup' in sHostName):
            return self.getHoster('vidup')
        if ('vidbull' in sHostName):
            return self.getHoster('vidbull')
        # vidlox et clone
        if ('vidlox' in sHostName):
            return self.getHoster('vidlox')
        if ('videobin' in sHostName):
            return self.getHoster('videobin')

        if ('stagevu' in sHostName):
            return self.getHoster('stagevu')
        if ('movshare' in sHostName) or ('wholecloud' in sHostName):
            return self.getHoster('wholecloud')
        if ('gorillavid' in sHostName):
            return self.getHoster('gorillavid')
        if ('daclips' in sHostName):
            return self.getHoster('daclips')
        if ('estream' in sHostName) and not ('widestream' in sHostName):
            return self.getHoster('estream')
        if ('hdvid' in sHostName):
            return self.getHoster('hdvid')
        if ('vshare' in sHostName):
            return self.getHoster('vshare')
        if ('giga' in sHostName):
            return self.getHoster('giga')
        if ('vidbom' in sHostName):
            return self.getHoster('vidbom')
        if ('upvid' in sHostName):
            return self.getHoster('upvid')
        if ('cloudvid' in sHostName):
            return self.getHoster('cloudvid')
        if ('clipwatching' in sHostName):
            return self.getHoster('clipwatching')
        if ('megadrive' in sHostName):
            return self.getHoster('megadrive')
        if ('downace' in sHostName):
            return self.getHoster('downace')
        if ('clickopen' in sHostName):
            return self.getHoster('clickopen')
        if ('iframe-secured' in sHostName):
            return self.getHoster('iframe_secured')
        if ('iframe-secure' in sHostName):
            return self.getHoster('iframe_secure')
        if ('goo.gl' in sHostName) or ('bit.ly' in sHostName) or (
                'streamcrypt' in sHostName) or ('opsktp' in sHosterUrl):
            return self.getHoster('allow_redirects')
        if ('jawcloud' in sHostName):
            return self.getHoster('jawcloud')
        if ('kvid' in sHostName):
            return self.getHoster('kvid')
        if ('soundcloud' in sHostName):
            return self.getHoster('soundcloud')
        if ('mixcloud' in sHostName):
            return self.getHoster('mixcloud')
        if ('ddlfr' in sHostName):
            return self.getHoster('ddlfr')
        if ('pdj' in sHostName):
            return self.getHoster('pdj')
        if ('vidzstore' in sHostName):
            return self.getHoster('vidzstore')
        if ('hd-stream' in sHostName):
            return self.getHoster('hd_stream')
        if ('rapidstream' in sHostName):
            return self.getHoster('rapidstream')
        if ('archive' in sHostName):
            return self.getHoster('archive')
        if ('jetload' in sHostName):
            return self.getHoster('jetload')
        if ('dustreaming' in sHostName):
            return self.getHoster('dustreaming')
        # frenchvid et clone
        if ('french-vid' in sHostName) or ('yggseries' in sHostName):
            return self.getHoster('frenchvid')
        if ('fembed' in sHostName) or ('fem.tohds' in sHostName):
            return self.getHoster('frenchvid')
        if ('feurl' in sHostName) or ('fsimg' in sHostName):
            return self.getHoster('frenchvid')
        if ('core1player' in sHostName) or ('vfsplayer' in sHostName):
            return self.getHoster('frenchvid')

        if ('flix555' in sHostName):
            return self.getHoster('flix555')
        if ('onlystream' in sHostName) or ('gotochus' in sHostName):
            return self.getHoster('onlystream')
        if ('pstream' in sHostName):
            return self.getHoster('pstream')
        if ('vudeo' in sHostName):
            return self.getHoster('vudeo')
        if ('sendvid' in sHostName):
            return self.getHoster('sendvid')
        if ('supervideo' in sHostName):
            return self.getHoster('supervideo')
        if ('dood' in sHostName):
            return self.getHoster('dood')
        if ('vidia' in sHostName):
            return self.getHoster('vidia')
        if ('streamtape' in sHostName):
            return self.getHoster('streamtape')

        # Lien telechargeable a convertir en stream
        if ('1fichier' in sHostName):
            return self.getHoster('onefichier')
        if ('uptobox' in sHostName):
            return self.getHoster('uptobox')
        if ('uplea' in sHostName):
            return self.getHoster('uplea')
        if ('uploaded' in sHostName) or ('ul.to' in sHostName):
            if ('/file/forbidden' in sHosterUrl):
                return False
            return self.getHoster('uploaded')
        if ('vidload' in sHostName):
            return self.getHoster('vidload')
        if ('kaydo' in sHostName):
            return self.getHoster('lien_direct')
        if ('cloudhost' in sHostName):
            return self.getHoster('cloudhost')
        if ('rapidgator' in sHostName):
            return False
        if ('turbobit' in sHostName):
            return False
        if ('mega.nz' in sHostName) or ('mega.co.nz' in sHostName):
            return False
        if ('hitfile' in sHostName):
            return False
        if ('myfiles.alldebrid.com' in sHostName):
            return self.getHoster('lien_direct')
        if ('dl.free.fr' in sHostName):
            return False

        # Si aucun hebergeur connu on teste les liens directs
        if (sHosterUrl[-4:] in '.mp4.avi.flv.m3u8.webm'):
            return self.getHoster('lien_direct')
        # Cas special si parametre apres le lien_direct
        if (sHosterUrl.split('?')[0][-4:] in '.mp4.avi.flv.m3u8.webm'):
            return self.getHoster('lien_direct')

        return False

    def getHoster(self, sHosterFileName):
        exec("from resources.hosters." + sHosterFileName + " import cHoster",
             globals())
        return cHoster()

    def play(self):
        oGui = cGui()
        oInputParameterHandler = cInputParameterHandler()
        sHosterIdentifier = oInputParameterHandler.getValue(
            'sHosterIdentifier')
        sMediaUrl = oInputParameterHandler.getValue('sMediaUrl')
        bGetRedirectUrl = oInputParameterHandler.getValue('bGetRedirectUrl')
        sFileName = oInputParameterHandler.getValue('sFileName')
        sTitle = oInputParameterHandler.getValue('title')

        if not sTitle:
            sTitle = sFileName

        if bGetRedirectUrl == 'True':
            sMediaUrl = self.__getRedirectUrl(sMediaUrl)

        VSlog('Hoster - play ' + sMediaUrl)

        oHoster = self.getHoster(sHosterIdentifier)
        oHoster.setFileName(sFileName)

        sHosterName = oHoster.getDisplayName()
        self.DIALOG.VSinfo(sHosterName, 'Resolve')

        try:

            oHoster.setUrl(sMediaUrl)
            aLink = oHoster.getMediaLink()

            if aLink[0]:
                oGuiElement = cGuiElement()
                oGuiElement.setSiteName(self.SITE_NAME)
                oGuiElement.setMediaUrl(aLink[1])
                oGuiElement.setTitle(sTitle)
                oGuiElement.getInfoLabel()

                oPlayer = cPlayer()

                # sous titres ?
                if len(aLink) > 2:
                    oPlayer.AddSubtitles(aLink[2])

                oPlayer.run(oGuiElement, oHoster.getFileName(), aLink[1])
                return
            else:
                self.DIALOG.VSerror(self.ADDON.VSlang(30020))
                return

        except:
            self.DIALOG.VSerror(self.ADDON.VSlang(30020))
            return

        oGui.setEndOfDirectory()

    def addToPlaylist(self):
        oGui = cGui()
        oInputParameterHandler = cInputParameterHandler()
        sHosterIdentifier = oInputParameterHandler.getValue(
            'sHosterIdentifier')
        sMediaUrl = oInputParameterHandler.getValue('sMediaUrl')
        bGetRedirectUrl = oInputParameterHandler.getValue('bGetRedirectUrl')
        sFileName = oInputParameterHandler.getValue('sFileName')

        if bGetRedirectUrl == 'True':
            sMediaUrl = self.__getRedirectUrl(sMediaUrl)

        VSlog('Hoster - playlist ' + sMediaUrl)
        oHoster = self.getHoster(sHosterIdentifier)
        oHoster.setFileName(sFileName)

        oHoster.setUrl(sMediaUrl)
        aLink = oHoster.getMediaLink()

        if aLink[0]:
            oGuiElement = cGuiElement()
            oGuiElement.setSiteName(self.SITE_NAME)
            oGuiElement.setMediaUrl(aLink[1])
            oGuiElement.setTitle(oHoster.getFileName())

            oPlayer = cPlayer()
            oPlayer.addItemToPlaylist(oGuiElement)
            self.DIALOG.VSinfo(str(oHoster.getFileName()), 'Playlist')
            return

        oGui.setEndOfDirectory()

    def __getRedirectUrl(self, sUrl):
        oRequest = cRequestHandler(sUrl)
        oRequest.request()
        return oRequest.getRealUrl()
示例#60
0
class cDownloadProgressBar(threading.Thread):

    DIALOG = dialog()


    def __init__(self, *args, **kwargs):

        self.__sTitle = ''
        self.__sUrl = ''
        self.__fPath = ''
        self.__bFastMode = False

        if (kwargs):
            self.__sTitle = kwargs['title']
            self.__sUrl = kwargs['url']
            self.__fPath = kwargs['Dpath']
            if'FastMode' in kwargs:
                print 'Telechargement en mode Turbo'
                self.__bFastMode = True

        threading.Thread.__init__(self)

        self.processIsCanceled = False
        self.oUrlHandler = None
        self.file = None
        self.__oDialog = None

        #self.currentThread = threading.Thread(target=self.run)
        #self.currentThread.start()

    def createProcessDialog(self):
        self.__oDialog = xbmcgui.DialogProgressBG()
        self.__oDialog.create('Download')
        #xbmc.sleep(1000)
        return self.__oDialog

    def _StartDownload(self):

        #print 'Thread actuel'
        #print threading.current_thread().getName()

        diag = self.createProcessDialog()
        #diag.isFinished()

        xbmcgui.Window(10101).setProperty('arret', '0')
        #self.Memorise.set("VstreamDownloaderWorking", "1")

        headers = self.oUrlHandler.info()

        #print headers

        iTotalSize = -1
        if "content-length" in headers:
            iTotalSize = int(headers["Content-Length"])

        chunk = 16 * 1024
        TotDown = 0

        #mise a jour pour info taille
        self.__updatedb(TotDown,iTotalSize)
        self.DIALOG.VSinfo('Téléchargement Démarré')

        while not (self.processIsCanceled or diag.isFinished()):

            data = self.oUrlHandler.read(chunk)
            if not data:
                print 'DL err'
                break

            self.file.write(data)
            TotDown = TotDown + data.__len__()
            self.__updatedb(TotDown,iTotalSize)

            self.__stateCallBackFunction(TotDown, iTotalSize)
            #if self.Memorise.get("VstreamDownloaderWorking") == "0":
            #    self.processIsCanceled = True
            if xbmcgui.Window(10101).getProperty('arret') == '1':
                self.processIsCanceled = True

            #petite pause, ca ralentit le download mais evite de bouffer 100/100 ressources
            if not (self.__bFastMode):
                xbmc.sleep(300)

        self.oUrlHandler.close()
        self.file.close()
        self.__oDialog.close()

        #On autorise le prochain DL
        #????????????????
        #Memorise.unlock("VstreamDownloaderLock")

        #fait une pause pour fermer le Dialog
        xbmc.sleep(900)

        #if download finish
        meta = {}
        meta['path'] = self.__fPath
        meta['size'] = TotDown
        meta['totalsize'] = iTotalSize

        if (TotDown == iTotalSize) and (iTotalSize > 10000):
            meta['status'] = 2
            try:
                cDb().update_download(meta)
                self.DIALOG.VSinfo('Téléchargements Termine', self.__sTitle)
                #print 'Téléchargements Termine : %s' % self.__sTitle
                self.RefreshDownloadList()
            except:
                pass
        else:
            meta['status'] = 0
            try:
                cDb().update_download(meta)
                self.DIALOG.VSinfo('Téléchargements Arrete', self.__sTitle)
                #print 'Téléchargements Arrete : %s' % self.__sTitle
                self.RefreshDownloadList()
            except:
                pass
            return

        #ok tout est bon on contiinu ou pas ?
        #if Memorise.get('SimpleDownloaderQueue') == '1':
        if xbmcgui.Window(10101).getProperty('SimpleDownloaderQueue') == '1':
            print 'Download suivant'
            tmp = cDownload()
            data = tmp.GetNextFile()
            tmp.StartDownload(data)


    def __updatedb(self, TotDown, iTotalSize):
        #percent 3 chiffre
        percent = '{0:.2f}'.format(min(100 * float(TotDown) / float(iTotalSize), 100))
        if percent in ['0.00','10.00','20.00','30.00','40.00','50.00','60.00','70.00','80.00','90.00']:
            meta = {}
            meta['path'] = self.__fPath
            meta['size'] = TotDown
            meta['totalsize'] = iTotalSize
            meta['status'] = 1

            try:
                cDb().update_download(meta)
                self.RefreshDownloadList()
            except:
                pass


    def __stateCallBackFunction(self, iDownsize, iTotalSize):

        if self.__oDialog.isFinished():
            self.createProcessDialog()

        iPercent = int(float(iDownsize * 100) / iTotalSize)
        self.__oDialog.update(iPercent, self.__sTitle, self.__formatFileSize(float(iDownsize))+'/'+self.__formatFileSize(iTotalSize))

        if (self.__oDialog.isFinished()) and not (self.__processIsCanceled):
            self.__processIsCanceled = True
            self.__oDialog.close()

    def run(self):

        try:
            #Recuperation url simple
            url = self.__sUrl.split('|')[0]
            #Recuperation des headers du lien
            headers = {}
            if len (self.__sUrl.split('|')) > 1:
                u = self.__sUrl.split('|')[1].split('&')
                for i in u:
                    headers[i.split('=')[0]] = i.replace(i.split('=')[0] + '=','')

            #Rajout du user-agent si abscent
            if not ('User-Agent' in headers):
                headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'

            req = urllib2.Request(url, None, headers)

            self.oUrlHandler = urllib2.urlopen(req,timeout=30)
            #self.__instance = repr(self)
            self.file = xbmcvfs.File(self.__fPath, 'w')
        except:
            VSlog('download error')
            VSlog(self.__sUrl)
            self.DIALOG.VSinfo('Erreur initialisation', 'Download error')
            return

        # if not Memorise.lock("VstreamDownloaderLock"):
        #     self.DIALOG.VSinfo('Telechargements deja demarrés', 'Download error')
        #     return

        if xbmc.getCondVisibility("Window.IsVisible(10151)"):
            self.DIALOG.VSinfo('Telechargements deja demarrés', 'Erreur')
            return

        self._StartDownload()

    def __formatFileSize(self, iBytes):
        iBytes = int(iBytes)
        if (iBytes == 0):
            return '%.*f %s' % (2, 0, 'MB')

        return '%.*f %s' % (2, iBytes/(1024*1024.0) , 'MB')

    def StopAll(self):

        self.processIsCanceled = True
        #Memorise.unlock("VstreamDownloaderLock")
        #Memorise.set('SimpleDownloaderQueue', '0')
        xbmcgui.Window(10101).setProperty('SimpleDownloaderQueue', '0')

        xbmcgui.Window(10101).setProperty('arret', '1')
        try:
            self.__oDialog.close()
        except:
            pass

        return

    def RefreshDownloadList(self):
        #print xbmc.getInfoLabel('Container.FolderPath')
        if 'function=getDownload' in xbmc.getInfoLabel('Container.FolderPath'):
            VSupdate()