コード例 #1
0
def _pbhook(dest, numblocks, blocksize, filesize, dp, start_time):
    try:
        if filesize <= 0:
            kodi.notify(msg='Invalid downloadable file', sound=True)
            log_utils.log('Error downloading video.', xbmc.LOGERROR)
            quit()
        percent = min(numblocks * blocksize * 100 / filesize, 100)
        currently_downloaded = float(numblocks) * blocksize / (1024 * 1024)
        kbps_speed = numblocks * blocksize / (time.time() - start_time)
        if kbps_speed > 0:
            eta = (filesize - numblocks * blocksize) / kbps_speed
        else:
            eta = 0
        kbps_speed = kbps_speed / 1024
        mbps_speed = kbps_speed / 1024
        total = float(filesize) / (1024 * 1024)
        mbs = '[COLOR dodgerblue]%.02f MB[/COLOR] of [B]%.02f MB[/B]' % (
            currently_downloaded, total)
        e = '[COLOR white][B]Speed: [/B][/COLOR][COLOR dodgerblue]%.02f Mb/s ' % mbps_speed + '[/COLOR]'
        e += '[COLOR white][B]ETA: [/B][/COLOR][COLOR dodgerblue]%02d:%02d' % divmod(
            eta, 60) + '[/COLOR]'
        dp.update(percent, '', mbs, e)
    except:
        dp.close()
        kodi.notify(msg='Error Downloading. Exiting...')
        quit()
    if dp.iscanceled():
        dp.close()
        kodi.notify(msg='Download Cancelled')
        quit()
コード例 #2
0
def find(url, name=None, iconimage=None, pattern=None):

    kodi.busy()

    try:
        url, site = url.split('|SPLIT|')
    except:
        site = 'Unknown'
        log_utils.log('Error getting site information from :: %s' % (url),
                      xbmc.LOGERROR)

    try:
        if 'streamingporn.xyz' in url:
            c = client.request(url)
            r = dom_parser2.parse_dom(c,
                                      'a',
                                      req=['href', 'class', 'rel', 'target'])
            r = [i for i in r if i.attrs['class'] == 'external']
            r = [client.request(i.attrs['href'], output='geturl') for i in r]
            r = [i for i in r if hmf.HostedMediaFile(i).valid_url()]
            url = multi(r)
        elif 'spreadporn.org' in url:
            c = client.request(url)
            r = dom_parser2.parse_dom(c, 'li', req=['data-show', 'data-link'])
            r = [(i.attrs['data-link']) for i in r]
            url = multi(r)
        elif 'pandamovie.eu' in url:
            c = client.request(url)
            r = dom_parser2.parse_dom(c, 'a', req='id')
            r = [(i.attrs['href']) for i in r]
            url = multi(r)
        elif 'xtheatre.net' in url:
            c = client.request(url)
            pattern = '''<iframe\s*src=['"](?:[^'"]+)['"]\s*data-lazy-src=['"]([^'"]+)'''
            r = re.findall(pattern, c)
            url = multi(r)
        elif 'sexkino.to' in url:
            c = client.request(url)
            u = dom_parser2.parse_dom(c, 'iframe',
                                      {'class': ['metaframe', 'rptss']})
            r = dom_parser2.parse_dom(c, 'tr')
            r = [dom_parser2.parse_dom(i, 'a', req='href') for i in r]
            r = [client.request(i[0].attrs['href']) for i in r if i]
            r = [i.attrs['src'] for i in u] + [
                re.findall("window.location.href='([^']+)", i)[0] for i in r
            ]
            url = multi(r)
    except:
        kodi.idle()
        kodi.notify(msg='Error getting link for (Link Finer) %s' % name)
        kodi.idle()
        quit()

    url += '|SPLIT|%s' % site
    kodi.idle()
    player.resolve_url(url, name, iconimage)
コード例 #3
0
def Favorites(fav, favmode, name, url, img, _folder):
    if fav == "add":
        delFav(url)
        addFav(favmode, name, url, img, _folder)
        kodi.notify('Favorite added', 'Item added to the favorites')
    elif fav == "del":
        delFav(url)
        log_utils.log('Deleting %s from favorites' % (url), xbmc.LOGNOTICE)
        kodi.notify('Favorite deleted', 'Item removed from the list')
        xbmc.executebuiltin('Container.Refresh')
コード例 #4
0
def allNoProgress(_in, _out):

    try:

        zin = zipfile.ZipFile(_in, 'r')
        zin.extractall(_out)

    except Exception as e:

        log(str(e))
        return False

    return True
コード例 #5
0
 def youporn(self, url):
     try:
         r = client.request(url)
         pattern = r"""quality[\'\"]\:[\'\"](\d+)[\'\"]\,[\'\"]videoUrl[\'\"]\:[\'\"]([^\'\"]+)"""
         i = re.findall(pattern, r)
         r = [(e[0], e[1].replace('\/', '/')) for e in i]
         log_utils.log('%s' % str(r), xbmc.LOGERROR)
         u = sorted(r,
                    key=lambda x: int(re.search('(\d+)', x[0]).group(1)),
                    reverse=True)
         return u
     except:
         return
コード例 #6
0
def download(url, name, icon, dest, dp=None):
    xbmc.executebuiltin("Dialog.Close(busydialog)")
    if '|' in url:
        url = url.split('|')[0]
    if not dp:
        dp = kodi.dp
        dp.create(kodi.get_name(), "Downloading: %s" % name, ' ', ' ')
    dp.update(0)
    start_time = time.time()
    log_utils.log('Attempting to download :: %s' % url, xbmc.LOGNOTICE)
    urlretrieve(url, dest,
                lambda nb, bs, fs: _pbhook(dest, nb, bs, fs, dp, start_time))
    addDownload(name, url, icon)
    kodi.notify(msg='Download Complete', sound=True)
    log_utils.log('Download complete.', xbmc.LOGNOTICE)
    finish_up(dest)
コード例 #7
0
def allWithProgress(_in, _out, dp):

    zin = zipfile.ZipFile(_in, 'r')
    nFiles = float(len(zin.infolist()))
    count = 0

    try:
        for item in zin.infolist():
            count += 1
            update = count / nFiles * 100
            dp.update(int(update), '', '', str(item.filename))
            try:
                zin.extract(item, _out)
            except Exception as e:
                log(str(e))

    except Exception as e:
        log(str(e))
        return False

    return True
コード例 #8
0
ファイル: pornhub.py プロジェクト: troywillett/xxxbones
def menu():
    try:
        url = urljoin(base_domain, 'categories?o=al')
        c = client.request(url)
        r = dom_parser2.parse_dom(c, 'li', {'class': 'cat_pic'})
        r = [(dom_parser2.parse_dom(i, 'a', req=['href', 'alt']), \
              dom_parser2.parse_dom(i, 'var'), \
              dom_parser2.parse_dom(i, 'img', req='src')) \
             for i in r if i]
        r = [(urljoin(base_domain, i[0][0].attrs['href']),
              i[0][0].attrs['alt'], i[1][0].content, i[2][0].attrs['src'])
             for i in r if i]
        if (not r):
            log_utils.log(
                'Scraping Error in %s:: Content of request: %s' %
                (base_name.title(), str(c)), xbmc.LOGERROR)
            kodi.notify(msg='Scraping Error: Info Added To Log File',
                        duration=6000,
                        sound=True)
            quit()
    except Exception as e:
        log_utils.log(
            'Fatal Error in %s:: Error: %s' % (base_name.title(), str(e)),
            xbmc.LOGERROR)
        kodi.notify(msg='Fatal Error', duration=4000, sound=True)
        quit()

    dirlst = []

    for i in r:
        try:
            name = kodi.sortX(i[1].encode('utf-8'))
            name = name.title() + ' - [ %s ]' % i[2].split(' ')[0]
            fanarts = xbmc.translatePath(
                os.path.join('special://home/addons/script.adultflix.artwork',
                             'resources/art/%s/fanart.jpg' % filename))
            dirlst.append({
                'name': name,
                'url': i[0],
                'mode': content_mode,
                'icon': i[3],
                'fanart': fanarts,
                'folder': True
            })
        except Exception as e:
            log_utils.log(
                'Error adding menu item %s in %s:: Error: %s' %
                (i[1].title(), base_name.title(), str(e)), xbmc.LOGERROR)

    if dirlst:
        buildDirectory(dirlst)
    else:
        kodi.notify(msg='No Menu Items Found')
        quit()
コード例 #9
0
def find_link(url, name, iconimage, downloadableLink=False):
    xbmc.executebuiltin("ActivateWindow(busydialog)")

    if '|SPLIT|' in url: url = url.split('|SPLIT|')[0]
    if 'site=' in url: url = url.split('site=')[0]
    if '|' in url: url = url.split('|User-Agent')[0]

    c = client.request(url, output='headers')

    checks = ['video', 'mpegurl']
    exts = ['.mp4', '.flv', '.m3u8']

    try:
        if any(f for f in checks if f in c['Content-Type']):
            downloadableLink = True
    except:
        if any(f for f in exts if f in url):
            downloadableLink = True
        else:
            xbmc.executebuiltin("Dialog.Close(busydialog)")
            kodi.notify(msg='Error downloading video.')
            quit()

    name = kodi.stripColor(name)
    if '] -' in name: name = name.split('] -')[1]
    if downloadableLink:
        dest = getDest()
        dest = os.path.join(dest, '%s.mp4' % quote_plus(name))
        download(url, name, iconimage, dest)
    else:
        u = None
        log_utils.log('Sending %s to XXX Resolver' % (url), xbmc.LOGNOTICE)
        if hmf.HostedMediaFile(url).valid_url():
            log_utils.log(
                '%s is a valid SMR resolvable URL. Attempting to resolve.' %
                (url), xbmc.LOGNOTICE)
            try:
                u = hmf.HostedMediaFile(url).resolve()
            except Exception as e:
                log_utils.log(
                    'Error getting valid link from SMR :: %s :: %s' %
                    (url, str(e)), xbmc.LOGERROR)
                kodi.idle()
                kodi.notify(msg='Something went wrong!  | %s' % str(e),
                            duration=8000,
                            sound=True)
                quit()
            log_utils.log('Link returned by XXX Resolver :: %s' % (u),
                          xbmc.LOGNOTICE)
        else:
            log_utils.log(
                '%s is not a valid SMR resolvable link. Attempting to resolve by AdultFlix backup resolver.'
                % (url), xbmc.LOGNOTICE)
            try:
                u = adultresolver.resolve(url)
            except Exception as e:
                log_utils.log(
                    'Error getting valid link from SMR :: %s :: %s' %
                    (url, str(e)), xbmc.LOGERROR)
                kodi.idle()
                kodi.notify(msg='Something went wrong!  | %s' % str(e),
                            duration=8000,
                            sound=True)
                quit()
            log_utils.log('%s returned by AdultFlix backup resolver.' % (u),
                          xbmc.LOGNOTICE)
        if not isinstance(u, str):
            try:
                u = multilinkselector(u)
            except:
                pass
        if u == 'quit':
            xbmc.executebuiltin("Dialog.Close(busydialog)")
            quit()
        if u:
            dest = getDest()
            dest = os.path.join(dest, '%s.tmp_mp4' % quote_plus(name))
            download(u, name, iconimage, dest)
        else:
            xbmc.executebuiltin("Dialog.Close(busydialog)")
            kodi.notify('No Downloadable Link Found.')
            quit()
コード例 #10
0
def request(url,
            close=True,
            redirect=True,
            error=False,
            proxy=None,
            post=None,
            headers=None,
            mobile=False,
            XHR=False,
            limit=None,
            referer=None,
            cookie=None,
            compression=True,
            output='',
            timeout='30'):
    try:
        handlers = []

        if proxy is not None:
            handlers += [ProxyHandler({'http': '%s' % (proxy)}), HTTPHandler]
            opener = build_opener(*handlers)
            install_opener(opener)

        if output == 'cookie' or output == 'extended' or not close == True:
            cookies = cookielib.LWPCookieJar()
            handlers += [
                HTTPHandler(),
                HTTPSHandler(),
                HTTPCookieProcessor(cookies)
            ]
            opener = build_opener(*handlers)
            install_opener(opener)

        if (2, 7, 8) < sys.version_info < (2, 7, 12):
            try:
                import ssl
                ssl_context = ssl.create_default_context()
                ssl_context.check_hostname = False
                ssl_context.verify_mode = ssl.CERT_NONE
                handlers += [HTTPSHandler(context=ssl_context)]
                opener = build_opener(*handlers)
                install_opener(opener)
            except:
                pass

        if url.startswith('//'): url = 'http:' + url

        try:
            headers.update(headers)
        except:
            headers = {}
        if 'User-Agent' in headers:
            pass
        elif mobile is not True:
            # headers['User-Agent'] = agent()
            headers['User-Agent'] = cache.get(randomagent, 1)
        else:
            headers['User-Agent'] = 'Apple-iPhone/701.341'
        if 'Referer' in headers:
            pass
        elif referer is not None:
            headers['Referer'] = referer
        if not 'Accept-Language' in headers:
            headers['Accept-Language'] = 'en-US'
        if 'X-Requested-With' in headers:
            pass
        elif XHR is True:
            headers['X-Requested-With'] = 'XMLHttpRequest'
        if 'Cookie' in headers:
            pass
        elif cookie is not None:
            headers['Cookie'] = cookie
        if 'Accept-Encoding' in headers:
            pass
        elif compression and limit is None:
            headers['Accept-Encoding'] = 'gzip'

        if redirect is False:

            class NoRedirection(HTTPErrorProcessor):
                def http_response(self, request, response):
                    return response

            opener = build_opener(NoRedirection)
            install_opener(opener)

            try:
                del headers['Referer']
            except:
                pass

        if isinstance(post, dict):
            post = urlencode(post)

        request = Request(url, data=post)
        _add_request_header(request, headers)

        try:
            response = urlopen(request, timeout=int(timeout))
        except HTTPError as response:

            if response.code == 503:
                cf_result = response.read(5242880)
                try:
                    encoding = response.info().getheader('Content-Encoding')
                except:
                    encoding = None
                if encoding == 'gzip':
                    cf_result = gzip.GzipFile(
                        fileobj=StringIO(cf_result)).read()

                if 'cf-browser-verification' in cf_result:

                    netloc = '%s://%s' % (urlparse.urlparse(url).scheme,
                                          urlparse.urlparse(url).netloc)

                    ua = headers['User-Agent']

                    cf = cache.get(cfcookie().get, 168, netloc, ua, timeout)

                    headers['Cookie'] = cf

                    request = Request(url, data=post)
                    _add_request_header(request, headers)

                    response = urlopen(request, timeout=int(timeout))
                else:
                    log_utils.log(
                        'Request-Error (%s): %s' % (str(response.code), url),
                        xbmc.LOGDEBUG)
                    if error is False:
                        return
            else:
                log_utils.log(
                    'Request-Error (%s): %s' % (str(response.code), url),
                    xbmc.LOGDEBUG)
                if error is False:
                    return

        if output == 'cookie':
            try:
                result = '; '.join(
                    ['%s=%s' % (i.name, i.value) for i in cookies])
            except:
                pass
            try:
                result = cf
            except:
                pass
            if close is True:
                response.close()
            return result

        elif output == 'geturl':
            result = response.geturl()
            if close == True: response.close()
            return result

        elif output == 'headers':
            result = response.headers
            if close == True: response.close()
            return result

        elif output == 'chunk':
            try:
                content = int(response.headers['Content-Length'])
            except:
                content = (2049 * 1024)
            if content < (2048 * 1024): return
            result = response.read(16 * 1024)
            if close == True: response.close()
            return result

        if limit == '0':
            result = response.read(224 * 1024)
        elif limit is not None:
            result = response.read(int(limit) * 1024)
        else:
            result = response.read(5242880)

        try:
            encoding = response.info().getheader('Content-Encoding')
        except:
            encoding = None
        if encoding == 'gzip':
            result = gzip.GzipFile(fileobj=StringIO(result)).read()

        if 'sucuri_cloudproxy_js' in result:
            su = sucuri().get(result)

            headers['Cookie'] = su

            request = Request(url, data=post)
            _add_request_header(request, headers)

            response = urlopen(request, timeout=int(timeout))

            if limit == '0':
                result = response.read(224 * 1024)
            elif limit is not None:
                result = response.read(int(limit) * 1024)
            else:
                result = response.read(5242880)

            try:
                encoding = response.info().getheader('Content-Encoding')
            except:
                encoding = None
            if encoding == 'gzip':
                result = gzip.GzipFile(fileobj=StringIO(result)).read()

        if 'Blazingfast.io' in result and 'xhr.open' in result:
            netloc = '%s://%s' % (urlparse.urlparse(url).scheme,
                                  urlparse.urlparse(url).netloc)
            ua = headers['User-Agent']
            headers['Cookie'] = cache.get(bfcookie().get, 168, netloc, ua,
                                          timeout)

            result = _basic_request(url,
                                    headers=headers,
                                    post=post,
                                    timeout=timeout,
                                    limit=limit)

        if output == 'extended':
            try:
                response_headers = dict(response.info().items())
            except:
                response_headers = response.headers
            response_code = str(response.code)
            try:
                cookie = '; '.join(
                    ['%s=%s' % (i.name, i.value) for i in cookies])
            except:
                pass
            try:
                cookie = cf
            except:
                pass
            if close == True: response.close()
            return (result, response_code, response_headers, headers, cookie)
        else:
            if close == True: response.close()
            return result
    except Exception as e:
        log_utils.log('Request-Error: (%s) => %s' % (str(e), url),
                      xbmc.LOGDEBUG)
        return
コード例 #11
0
def resolve_url(url, name=None, iconimage=None, pattern=None):

    kodi.busy()

    try:
        url, site = url.split('|SPLIT|')
    except:
        site = 'Unknown'
        log_utils.log('Error getting site information from :: %s' % (url), xbmc.LOGERROR)

    if not name:
        name = 'Unknown'
    if not iconimage:
        iconimage = kodi.addonicon
    name = re.sub(r'(\[.+?\])', '', name)
    name = name.lstrip()
    if '] - ' in name:
        name = name.split('] - ')[-1]
    if 'site=' in url:
        url, site = url.split('site=')

    if '|CHAT|' in url:
        url, site, name = url.split('|CHAT|')
    if '- [' in name:
        name = name.split('- [')[0]

    u = None
    log_utils.log('Sending %s to XXX Resolver' % (url), xbmc.LOGNOTICE)
    if hmf.HostedMediaFile(url).valid_url():
        log_utils.log('%s is a valid SMR resolvable URL. Attempting to resolve.' % (url), xbmc.LOGNOTICE)
        try:
            u = hmf.HostedMediaFile(url).resolve()
        except Exception as e:
            log_utils.log('Error getting valid link from SMR :: %s :: %s' % (url, str(e)), xbmc.LOGERROR)
            kodi.idle()
            kodi.notify(msg='Something went wrong!  | %s' % str(e), duration=8000, sound=True)
            quit()
        log_utils.log('Link returned by XXX Resolver :: %s' % (u), xbmc.LOGNOTICE)
    else:
        log_utils.log('%s is not a valid SMR resolvable link. Attempting to resolve by AdultFlix backup resolver.' % (url), xbmc.LOGNOTICE)
        try:
            u = adultresolver.resolve(url)
            if u:
                if hmf.HostedMediaFile(u).valid_url():
                    u = hmf.HostedMediaFile(u).resolve()
        except Exception as e:
            log_utils.log('Error getting valid link from SMR :: %s :: %s' % (url, str(e)), xbmc.LOGERROR)
            kodi.idle()
            kodi.notify(msg='Something went wrong!  | %s' % str(e), duration=8000, sound=True)
            quit()
        log_utils.log('%s returned by AdultFlix backup resolver.' % (u), xbmc.LOGNOTICE)
    if u == 'offline':
        kodi.idle()
        kodi.notify(msg='This performer is offline.', duration=5000, sound=True)
        quit()
    if u:
        kodi.idle()
        play(u, name, iconimage, url, site)
    else:
        kodi.idle()
        log_utils.log('Failed to get any playable link for :: %s' % (url), xbmc.LOGERROR)
        kodi.notify(msg='Failed to get any playable link.', duration=7500, sound=True)
        quit()
コード例 #12
0
ファイル: pornhub.py プロジェクト: troywillett/xxxbones
def content(url, searched=False):
    import xbmcgui
    dialog = xbmcgui.Dialog()
    try:
        c = client.request(url)
        r = re.findall('<ul id="videoCategory"(.*?)</ul>', c,
                       flags=re.DOTALL)[0]
        b = re.findall(
            '<div class="img fade fadeUp videoPreviewBg">(.*?)</div>',
            r,
            flags=re.DOTALL)
        if (not r) and (not searched):
            log_utils.log(
                'Scraping Error in %s:: Content of request: %s' %
                (base_name.title(), str(c)), xbmc.LOGERROR)
            kodi.notify(msg='Scraping Error: Info Added To Log File',
                        duration=6000,
                        sound=True)
    except Exception as e:
        if (not searched):
            log_utils.log(
                'Fatal Error in %s:: Error: %s' % (base_name.title(), str(e)),
                xbmc.LOGERROR)
            kodi.notify(msg='Fatal Error', duration=4000, sound=True)
            quit()
        else:
            pass

    dirlst = []

    for i in b:
        try:
            name = re.findall('title="(.*?)"', i, flags=re.DOTALL)[0]
            if searched:
                description = 'Result provided by %s' % base_name.title()
            else:
                description = name
            content_url = re.findall('<a href="(.*?)"', i, flags=re.DOTALL)[0]
            if not base_domain in content_url:
                content_url = base_domain + content_url
            icon = re.findall('data-thumb_url\s+=\s+"(.*?)"',
                              i,
                              flags=re.DOTALL)[0]
            fanarts = xbmc.translatePath(
                os.path.join('special://home/addons/script.adultflix.artwork',
                             'resources/art/%s/fanart.jpg' % filename))
            dirlst.append({
                'name': name,
                'url': content_url,
                'mode': player_mode,
                'icon': icon,
                'fanart': fanarts,
                'description': description,
                'folder': False
            })
        except Exception as e:
            log_utils.log(
                'Error adding menu item %s in %s:: Error: %s' %
                (i[1].title(), base_name.title(), str(e)), xbmc.LOGERROR)

    if dirlst:
        buildDirectory(dirlst, stopend=True, isVideo=True, isDownloadable=True)
    else:
        if (not searched):
            kodi.notify(msg='No Content Found')
            quit()

    if searched: return str(len(r))

    if not searched:

        try:
            search_pattern = '''\<link\s*rel\=['"]next['"]\s*href\=['"]([^'"]+)'''
            parse = base_domain
            helper.scraper().get_next_page(content_mode, url, search_pattern,
                                           filename)
        except Exception as e:
            log_utils.log(
                'Error getting next page for %s :: Error: %s' %
                (base_name.title(), str(e)), xbmc.LOGERROR)
コード例 #13
0
    def get_next_page(self,
                      mode,
                      url,
                      pattern,
                      site='',
                      parse=None,
                      pictures=False):

        try:
            dirlst = []
            icon = xbmc.translatePath(
                os.path.join('special://home/addons/script.adultflix.artwork',
                             'resources/art/main/next.png'))
            fanart = xbmc.translatePath(
                os.path.join('special://home/addons/script.adultflix.artwork',
                             'resources/art/%s/fanart.jpg' % site))
            if '|GOT_URL' in url:
                url = url.split('|GOT_URL')[0]
                dirlst.append({
                    'name': kodi.giveColor('Next Page -->', 'white'),
                    'url': url,
                    'mode': mode,
                    'icon': icon,
                    'fanart': fanart,
                    'description': 'Load More......',
                    'folder': True
                })
            else:
                r = client.request(url)
                url = re.findall(r'%s' % pattern, r)[0]
                if parse:
                    url = urljoin(parse, url)
                if '&amp;' in url: url = url.replace('&amp;', '&')
                dirlst.append({
                    'name': kodi.giveColor('Next Page -->', 'white'),
                    'url': url,
                    'mode': mode,
                    'icon': icon,
                    'fanart': fanart,
                    'description': 'Load More......',
                    'folder': True
                })
            if 'chaturbate' in url:
                if dirlst:
                    buildDirectory(dirlst, isVideo=True, chaturbate=True)
            elif pictures:
                if dirlst: buildDirectory(dirlst, pictures=True)
            else:
                if dirlst: buildDirectory(dirlst, isVideo=True)
        except Exception as e:
            log_utils.log(
                'Error getting next page for %s :: Error: %s' %
                (site.title(), str(e)), xbmc.LOGERROR)
            xbmcplugin.setContent(kodi.syshandle, 'movies')
            if 'chaturbate' in url:
                local_utils.setView('chaturbate')
            elif pictures:
                local_utils.setView('pictures')
            else:
                local_utils.setView('thumbs')
            xbmcplugin.endOfDirectory(kodi.syshandle, cacheToDisc=True)
コード例 #14
0
def buildDir(items,
             content='dirs',
             cm=None,
             search=False,
             stopend=False,
             isVideo=False,
             isDownloadable=False,
             cache=True,
             chaturbate=False,
             pictures=False):
    if items is None or len(items) == 0:
        kodi.busy()
        sys.exit()

    if cm is None:
        cm = []

    sysaddon = sys.argv[0]
    syshandle = int(sys.argv[1])

    if chaturbate:
        import sqlite3
        databases = xbmc.translatePath(
            os.path.join(kodi.datafolder, 'databases'))
        chaturbatedb = xbmc.translatePath(
            os.path.join(databases, 'chaturbate.db'))
        conn = sqlite3.connect(chaturbatedb)
        conn.text_factory = str
        c = conn.cursor()
        c.execute("SELECT * FROM chaturbate ORDER BY name ASC")
        chat_urls = []
        for (chat_name, chat_url, chat_icon) in c.fetchall():
            chat_urls.append(chat_url)

    for i in items:

        try:
            name = i['name']

            if 'file_path' not in name:
                try:
                    name = client.replaceHTMLCodes(name)
                    name = kodi.sortX(name)
                except:
                    pass
            else:
                name = name.replace('file_path', '')

            item = xbmcgui.ListItem(label=name)

            try:
                if i['description']: description = i['description']
            except:
                description = name

            try:
                description = client.replaceHTMLCodes(description)
                description = kodi.sortX(description)
            except:
                pass

            kodi.giveColor(description, 'white', True)
            if pictures:
                item.setInfo('picture', {'title': name, 'plot': description})
            else:
                item.setInfo('video', {'title': name, 'plot': description})

            try:
                name = quote_plus(name)
            except:
                name = name.replace(' ', '+')

            try:
                if i['url']:
                    url = i['url']
                else:
                    url = 'none'
            except:
                url = 'none'
            if i['icon'] == None:
                thumb = kodi.addonicon
            else:
                thumb = i['icon']
            if i['fanart'] == None:
                fanart = kodi.addonicon
            else:
                fanart = i['fanart']
            if (not thumb == 'local') and (not fanart == 'local'):
                item.setArt({'icon': thumb, 'thumb': thumb, 'fanart': fanart})
            else:
                item.setArt({'icon': url, 'thumb': url, 'fanart': fanart})

            try:
                if i['folder']:
                    _folder = True
                else:
                    _folder = False
            except:
                _folder = True

            try:
                if i['isDownloaded']:
                    isDownloaded = True
                else:
                    isDownloaded = False
            except:
                isDownloaded = False

            if not isDownloadable:
                try:
                    if i['isDownloadable']:
                        isDownloadable = True
                    else:
                        isDownloadable = False
                except:
                    isDownloadable = False

            if 'typeid=history' in url:
                url = url.replace('typeid=history', '')
                history = '%s?url=%s&mode=%s' \
                          % (sysaddon, quote_plus(url), str('24'))
                htext = "Remove from History"
                cm.append(('%s' % htext, 'xbmc.RunPlugin(' + history + ')'))

            if 'search_term=' in url:
                search_term = '%s?url=%s&mode=%s' \
                              % (sysaddon, quote_plus(url), str('25'))
                stext = "Remove Search Term"
                cm.append(
                    ('%s' % stext, 'xbmc.RunPlugin(' + search_term + ')'))
                url = url.replace('search_term=', '')

            u = '%s?url=%s&mode=%s&name=%s&iconimage=%s&fanart=%s' % (
                sysaddon, quote_plus(url), str(
                    i['mode']), name, quote_plus(thumb), quote_plus(fanart))

            if chaturbate:
                if '|CHAT|' in url:
                    check_url = url.split('|CHAT|')[0]
                else:
                    check_url = url.split('|SPLIT|')[0]
                log_utils.log('URL IS %s' % (check_url), xbmc.LOGERROR)
                if check_url in str(chat_urls):
                    chat = 'del'
                else:
                    chat = 'add'

                chat_compiled = '%s?url=%s&mode=%s&name=%s&iconimage=%s&chat=%s&chatmode=%s&folder=%s' % (
                    sysaddon, quote_plus(check_url), str('101'), name,
                    quote_plus(thumb), chat, str(i['mode']), str(_folder))

                if chat == 'add':
                    ctext = "Add to"
                elif chat == 'del':
                    ctext = "Remove from"
                cm.append(('%s Chaturbate Monitoring' % ctext,
                           'xbmc.RunPlugin(' + chat_compiled + ')'))

            try:
                if i['fav']:
                    fav = i['fav']
                else:
                    fav = 'add'
            except:
                fav = 'add'

            try:
                if i['cm']:
                    for cmitems in i['cm']:
                        log_utils.log('%s' % (cmitems[1]), xbmc.LOGNOTICE)
                        cm.append(('%s' % cmitems[0],
                                   'xbmc.RunPlugin(' + cmitems[1] + ')'))
            except:
                pass

            favorite = '%s?url=%s&mode=%s&name=%s&iconimage=%s&fav=%s&favmode=%s&folder=%s' % (
                sysaddon, quote_plus(url), str('100'), name, quote_plus(thumb),
                fav, str(i['mode']), str(_folder))

            if fav == 'add':
                ftext = "Add to"
            elif fav == 'del':
                ftext = "Remove from"
            cm.append(('%s %s Favorites' % (ftext, kodi.get_name()),
                       'xbmc.RunPlugin(' + favorite + ')'))

            if isDownloadable:
                dwnld = '%s?url=%s&mode=%s&name=%s&iconimage=%s' % (
                    sysaddon, quote_plus(url), str('26'), name,
                    quote_plus(thumb))
                cm.append(('Download Video', 'xbmc.RunPlugin(' + dwnld + ')'))
            if isDownloaded:
                rmdwnld = '%s?url=%s&mode=%s&name=%s' % (
                    sysaddon, quote_plus(url), str('28'), name)
                cm.append(('Delete Video', 'xbmc.RunPlugin(' + rmdwnld + ')'))

            open_set = '%s?mode=%s' % (sysaddon, str('19'))
            stext = "Open AdultFlix Settings"
            cm.append(('%s' % stext, 'xbmc.RunPlugin(' + open_set + ')'))

            if isDownloadable:
                view_type = 'thumb'
            elif pictures:
                view_type = 'picture'
            elif chaturbate:
                view_type = 'chaturbate'
            else:
                view_type = 'list'
            view_compile = '%s?mode=%s&name=%s' % (sysaddon, str('44'),
                                                   view_type)
            cm.append(
                ('Set %s to this view mode by default.' % view_type.title(),
                 'xbmc.RunPlugin(' + view_compile + ')'))

            if cm:
                item.addContextMenuItems(cm, replaceItems=False)
                cm = []

            if isVideo:
                codec_info = {'codec': 'h264'}
                item.addStreamInfo('video', codec_info)

            xbmcplugin.addDirectoryItem(handle=syshandle,
                                        url=u,
                                        listitem=item,
                                        isFolder=_folder)

        except Exception as e:
            log_utils.log(
                'Error adding item %s in BuildDir function ( %s %s ):: Error: %s'
                % (name, url, thumb, str(e)), xbmc.LOGERROR)

    if not stopend:
        if chaturbate:
            xbmcplugin.setContent(kodi.syshandle, 'movies')
            setView('chaturbate')
        elif pictures:
            xbmcplugin.setContent(kodi.syshandle, 'movies')
            setView('pictures')
        elif isVideo:
            xbmcplugin.setContent(kodi.syshandle, 'movies')
            setView('thumbs')
        else:
            xbmcplugin.setContent(kodi.syshandle, 'movies')
            setView('list')
    if not search and not stopend:
        if cache:
            xbmcplugin.endOfDirectory(syshandle, cacheToDisc=True)
        else:
            xbmcplugin.endOfDirectory(syshandle, cacheToDisc=False)
コード例 #15
0
    def generic(self, url, pattern=None):

        try:
            r = client.request(url)
            if pattern:
                s = re.findall(r'%s' % pattern, r)
            else:
                patterns = [
                    r'''\s*=\s*[\'\"](http.+?)[\'\"]''',
                    r'''\s*=\s*['"](http.+?)['"]''',
                    r'''['"][0-9_'"]+:\s[\'\"]([^'"]+)''',
                    r'''\(\w+\([\'\"]([^\'\"]*)''',
                    r'''[\'\"]\w+[\'\"]:['"]([^'"]*)''',
                    r'''\s*=\s*[\'\"](http.+?)[\'\"]''',
                    r'''\s*:\s*[\'\"](//.+?)[\'\"]''',
                    r'''\:[\'\"](\.+?)[\'\"]''',
                    r'''\s*\(\s*[\'\"](http.+?)[\'\"]''',
                    r'''\s*=\s*[\'\"](//.+?)[\'\"]''',
                    r'''\w*:\s*[\'\"](http.+?)[\'\"]''',
                    r'''\w*=[\'\"]([^\'\"]*)''',
                    r'''\w*\s*=\s*[\'\"]([^\'\"]*)''',
                    r'''(?s)<file>([^<]*)''',
                ]

                s = []
                for pattern in patterns:
                    l = re.findall(pattern, r)
                    s += [
                        i for i in l if urlparse(i).path.strip('/').split('/')
                        [-1].split('.')[-1] in ['mp4', 'flv', 'm3u8']
                    ]

                if s:
                    s = [
                        i for i in s if (urlparse(i).path).strip('/').split(
                            '/')[-1].split('.')[-1] in ['mp4', 'flv', 'm3u8']
                    ]
                else:
                    s = client.parseDOM(r,
                                        'source',
                                        ret='src',
                                        attrs={'type': 'video.+?'})

                if not s:
                    raise Exception

                s = ['http:' + i if i.startswith('//') else i for i in s]
                s = [
                    urljoin(url, i) if not i.startswith('http') else i
                    for i in s
                ]
                s = [x for y, x in enumerate(s) if x not in s[:y]]

            self.u = []

            def request(i):
                try:
                    i = i.replace(' ', '%20')
                    c = client.request(i, output='headers', referer=url)
                    checks = ['video', 'mpegurl', 'html']
                    if any(f for f in checks if f in c['Content-Type']):
                        self.u.append((i, int(c['Content-Length'])))
                except:
                    pass

            threads = []
            for i in s:
                threads.append(workers.Thread(request, i))
            [i.start() for i in threads]
            [i.join() for i in threads]

            u = sorted(self.u, key=lambda x: x[1])[::-1]

            mobile_mode = kodi.get_setting('mobile_mode')
            if mobile_mode == 'true':
                u = client.request(u[-1][0], output='geturl', referer=url)
            else:
                u = client.request(u[0][0], output='geturl', referer=url)
            log_utils.log('Returning %s from AdultFlix Resolver' % str(u),
                          xbmc.LOGNOTICE)
            return u
        except Exception as e:
            log_utils.log('Error resolving %s :: Error: %s' % (url, str(e)),
                          xbmc.LOGERROR)