Ejemplo n.º 1
0
def index():
    try:
        providers_count = len(PROVIDERS['movie'])
        if not providers_count > 0:
            raise AnErrorOccurred(30315)

        if providers_count == 1:
            sys_kwargs = _get_kwargs()[1]
            item = call_provider(PROVIDERS['movie'][0]).catalogs(**sys_kwargs)
            plugin.redirect(
                plugin.url_for(
                    item.pop('endpoint'),
                    **_build_kwargs(item.pop("kwargs", {}), sys_kwargs,
                                    **{'provider': PROVIDERS['movie'][0]})))
        # If we have more end one provider we createt a provider index
        else:
            sys_kwargs = _get_kwargs()[1]
            for provider in PROVIDERS['movie']:
                item = call_provider(provider).catalogs(**sys_kwargs)
                item["path"] = plugin.url_for(
                    item.pop('endpoint'),
                    **_build_kwargs(item.pop("kwargs", {}), sys_kwargs,
                                    **{'provider': provider}))
                yield item
    except AnErrorOccurred as e:
        errorNotify(e.errno)
    except:
        errorNotify(30308)
Ejemplo n.º 2
0
def url_get(domain, uri, params={}, headers={}, proxyid=None):
    querystring = ""
    if params:
        querystring = "".join(['?', urlencode(params)])
    if proxyid:
        log("(urllib2) Proxy domain is activated", xbmc.LOGDEBUG)
    for pd in (proxyid and proxy.update_list(proxyid, domain) or [domain]):
        url = "".join([pd, uri, querystring])

        req = urllib2.Request(url)
        log("(urllib2) (Request URL) " + url, xbmc.LOGDEBUG)
        req.add_header(
            "User-Agent",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.66 Safari/537.36"
        )
        log(
            "(urllib2) (Request header) User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.66 Safari/537.36",
            xbmc.LOGDEBUG)
        req.add_header("Accept-Encoding", "gzip")
        log("(urllib2) (Request header) Accept-Encoding: gzip", xbmc.LOGDEBUG)
        for k, v in headers.items():
            req.add_header(k, v)
            log("(urllib2) (Request header) {key}: {val}".format(key=k, val=v),
                xbmc.LOGDEBUG)

        try:
            with closing(urllib2.urlopen(req, timeout=20)) as response:
                res = response.read()
                if response.headers.get("Content-Encoding", "") == "gzip":
                    log("(urllib2) The content is gzip compressed",
                        xbmc.LOGDEBUG)
                    res = zlib.decompressobj(16 +
                                             zlib.MAX_WBITS).decompress(res)
                if res:
                    data = simplejson.loads(res)
                    if proxyid:
                        log(
                            "(urllib2) Proxy domain ({proxydomaine}) worked and will be given as first choice in the future"
                            .format(proxydomaine=pd), xbmc.LOGDEBUG)
                        proxy.set_default(proxyid, pd)
                    log("(urllib2) Done", xbmc.LOGDEBUG)
                    return data
                raise AnErrorOccurred(0)
        except urllib2.HTTPError as e:
            log(
                "(urllib2) http error: ({url}) [{code}] {reason}".format(
                    url=url, code=e.code, reason=e.reason), xbmc.LOGERROR)
        except ValueError as e:
            log("(urllib2) JSON error: {e} ({url})".format(e=e, url=url),
                xbmc.LOGERROR)
        except AnErrorOccurred as e:
            log("(urllib2) Empty or wrrong response: " + url, xbmc.LOGERROR)
        except:
            log("(urllib2) Unknown error: " + url, xbmc.LOGERROR)
Ejemplo n.º 3
0
 def system():
     if sys.platform.startswith('linux'):
         if 'ANDROID_DATA' in os.environ:
             return 'android'
         else:
             return 'linux'
     elif sys.platform.startswith('win'):
         return 'windows'
     elif sys.platform.startswith('darwin'):
         return 'darwin'
     else:
         raise AnErrorOccurred(30302)
Ejemplo n.º 4
0
    def play(self, uri, item, subtitle=None, subtitle_provider=None):
        #
        torrent2http_options = {
            "uri": str(uri),
            # Files
            "download_path": xbmc.validatePath(xbmc.translatePath(__addon__.getSetting("download_path"))) or CACHE_DIR,
            "keep_files": __addon__.getSetting("keep_files") == 'true' and True or False,
            "keep_complete": __addon__.getSetting("keep_complete") == 'true' and True or False,
            "keep_incomplete": __addon__.getSetting("keep_incomplete") == 'true' and True or False,
            # Network
            "download_kbps": int(__addon__.getSetting("download_kbps")) or 0,
            "upload_kbps":  int(__addon__.getSetting("upload_kbps")) or 0,
            "connections_limit": int(__addon__.getSetting("connections_limit")) or 200,
            "encryption": int(__addon__.getSetting("encryption")) or 1,
            # Port
            "listen_port": int(__addon__.getSetting("listen_port")) or 6881,
            "use_random_port": __addon__.getSetting("use_random_port") == 'true' and True or False,
            # Peers
            "torrent_connect_boost": int(__addon__.getSetting("torrent_connect_boost")) or 50,
            "connection_speed": int(__addon__.getSetting("connection_speed")) or 50,
            "peer_connect_timeout": int(__addon__.getSetting("peer_connect_timeout")) or 15,
            "min_reconnect_time": int(__addon__.getSetting("min_reconnect_time")) or 60,
            "max_failcount": int(__addon__.getSetting("max_failcount")) or 3,
            # Features
            "enable_tcp": __addon__.getSetting("enable_tcp") == 'true' and False or True,
            "enable_dht": __addon__.getSetting("enable_dht") == 'true' and False or True,
            "enable_lsd": __addon__.getSetting("enable_lsd") == 'true' and False or True,
            "enable_utp": __addon__.getSetting("enable_utp") == 'true' and False or True,
            "enable_scrape": __addon__.getSetting("enable_scrape") == 'true' and True or False,
            "enable_upnp": __addon__.getSetting("enable_upnp") == 'true' and False or True,
            "enable_natpmp": __addon__.getSetting("enable_natpmp") == 'true' and False or True,
            # Additional
            "trackers": not __addon__.getSetting("trackers") == "" and __addon__.getSetting['trackers'].split(',') or None,
            "dht_routers": not __addon__.getSetting("dht_routers") == "" and __addon__.getSetting['dht_routers'].split(',') or None,
            # Log / Debug
            "log_stats": __addon__.getSetting("debug") == 'true' and True or False,
            "debug_alerts": __addon__.getSetting("debug_alerts") == 'true' and True or False,
            # Bin
            "binaries_path": os.path.join(RESOURCES_PATH, 'bin')
        }
        # List item
        self.item = item

        ###
        if torrent2http_options['download_kbps'] <= 0:
            torrent2http_options['download_kbps'] = None

        if torrent2http_options['upload_kbps'] <= 0:
            torrent2http_options['upload_kbps'] = None
        elif torrent2http_options['upload_kbps'] < 15:
            notify(__addon__.getLocalizedString(30313))
            torrent2http_options['upload_kbps'] = 15
            __addon__.setSetting('upload_kbps', '15')

        log('(Player) Start the torrent2http file', xbmc.LOGDEBUG)
        with closing(Engine(**torrent2http_options)) as engine:
            # Start engine and instruct torrent2http to begin download first file
            engine.start(0)

            log('(Player) Pre-Loading the movie', xbmc.LOGDEBUG)
            ready = False
            with closing(SafeDialogProgress(delay_create=0)) as dialog:
                dialog.create(self.item['info']['title'])
                dialog.update(self.progressed, *self._get_status_lines())

                file_id = None
                while not xbmc.abortRequested and not dialog.iscanceled():
                    xbmc.sleep(self.progressSleepTime)

                    # Get status
                    status = engine.status()
                    # Check if there is loading error and raise exception 
                    engine.check_torrent_error(status)

                    # We need a file id
                    if file_id is None:
                        # Get torrent files list, filtered by video file type only
                        files = engine.list(media_types=[MediaType.VIDEO])
                        if files is None:
                            continue
                        # Torrent has no video files
                        if not files:
                            raise AnErrorOccurred(30316)
                        # Select first matching file                    
                        file_id = files[0].index
                        file_status = files[0]

                    # Get file status
                    file_status = engine.file_status(file_id)
                    if not file_status:
                        continue

                    if status.state == State.DOWNLOADING:
                        self._calculate_progress(int(self.item['info'].get('duration', 0)), status, file_status)
                        if self.progressed >= 100:
                            ready = True
                            break
                        dialog.update(int(self.progressed), *self._get_status_lines(status))
                        continue

                    if status.state in [State.FINISHED, State.SEEDING]:
                        ready = True
                        break

                if ready:
                    log('(Player) Finished with pre-loading the movie', xbmc.LOGDEBUG)
                    # Download subtitle
                    if subtitle:
                        log('(Player) Download subtitle', xbmc.LOGDEBUG)
                        dialog.update(99, *[__addon__.getLocalizedString(30019), ' ', ' '])
                        path = file_status.save_path
                        subtitle = subtitle_provider.download(subtitle, os.path.dirname(path), ".".join([os.path.splitext(os.path.basename(path))[0], self.item['stream_info']['subtitle']['language']]))
                    dialog.update(100, *[__addon__.getLocalizedString(30020), ' ', ' '])
                elif xbmc.abortRequested or dialog.iscanceled():
                    log('(Player) Pre-Loading was canceled or interrupted', xbmc.LOGDEBUG)

            if ready:
                # Resolve URL to XBMC
                self.item.update({"path": file_status.url})

                # Starts the playback
                log('(Player) Start the playback', xbmc.LOGDEBUG)
                #xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, self.item)
                plugin.set_resolved_url(self.item)
                for _ in xrange(60):
                    if not self.isPlaying():
                        xbmc.sleep(1000)
                        continue

                    if subtitle:
                        log('(Player) Adds the subtitle to the player', xbmc.LOGDEBUG)
                        self.setSubtitles(subtitle)

                    # Wait for the playback to finish
                    log('(Player) Wait for the playback to finish', xbmc.LOGDEBUG)
                    with closing(OverlayText()) as self.overlay:
                        while not xbmc.abortRequested and self.isPlaying():
                            if self.overlay.isShowing():
                                self.overlay.setText("\n".join(self._get_status_lines(engine.status())))
                            xbmc.sleep(100)

                    log('(Player) Playback is finished', xbmc.LOGDEBUG)
                    if subtitle and torrent2http_options["keep_files"] == False and torrent2http_options["keep_complete"] == False and torrent2http_options["keep_incomplete"] == False:
                        # Delete subtitle
                        log('(Player) Delete subtitle', xbmc.LOGDEBUG)
                        subtitle_provider.remove(subtitle)
                    break
                else:
                    log('(Player) Playback is terminated due to timeout', xbmc.LOGERROR)
Ejemplo n.º 5
0
def browse(provider, separate, page):
    try:
        page = int(page)
        kwargs = _get_kwargs()[0]
        mediaprovider = call_provider(provider)

        with closing(SafeDialogProgress(delay_close=0)) as dialog:
            dialog.create(__addon__.getAddonInfo('name'))
            # Update progress
            dialog.update(0, line1=__addon__.getLocalizedString(30007))

            # Setting content type
            plugin.set_content(mediaprovider.provides)

            # Getting items
            result = None
            with conFutures.ThreadPoolExecutor(max_workers=1) as pool:
                future = pool.submit(mediaprovider.browse, *(separate, page),
                                     **kwargs)
                while not future.done():
                    if xbmc.abortRequested or dialog.iscanceled():
                        pool.shutdown(wait=False)
                        return
                    xbmc.sleep(100)
                result = future.result()

            if not result:
                raise AnErrorOccurred(30305)
            items = result.pop('items', [])
            if not items:
                raise AnErrorOccurred(30307)
            itemsCount = len(items)

            # Build status
            status = {'jobs': (itemsCount + 1) * 2, 'done': 1}

            # Update progress
            dialog.update(int(status['done'] * 100 / status['jobs']),
                          line1=__addon__.getLocalizedString(30018))

            # Getting meta data and subtitles
            def on_status_update(future):
                data = future.result()
                status['done'] = status['done'] + 1
                if not data:
                    dialog.update(int(status['done'] * 100 / status['jobs']))
                if data.get('stream_info', {}).get('subtitle',
                                                   {}).get('language', None):
                    dialog.update(
                        int(status['done'] * 100 / status['jobs']),
                        line1=data["label"],
                        line2=u'{lang} subtitle'.format(
                            lang=data['stream_info']['subtitle']['language']))
                else:
                    dialog.update(int(status['done'] * 100 / status['jobs']),
                                  line1=data["label"],
                                  line2='Metadata')

            futures = []
            providers = {
                'metadata': call_provider(PROVIDERS['meta_tmdb']),
                'subtitles': call_provider(PROVIDERS['subtitle_yify'])
            }
            refresh = _isSettingsChanged()
            with conFutures.ThreadPoolExecutor(max_workers=2) as pool:
                for item in items:
                    futures.append(
                        pool.submit(
                            _shelf_mediainfo,
                            *(
                                'metadata',
                                item,
                                providers['metadata'],
                                refresh,
                            )))
                    futures.append(
                        pool.submit(
                            _shelf_mediainfo,
                            *(
                                'subtitles',
                                item,
                                providers['subtitles'],
                                refresh,
                            )))
                [
                    future.add_done_callback(on_status_update)
                    for future in futures
                ]
                while not all(future.done() for future in futures):
                    if xbmc.abortRequested or dialog.iscanceled():
                        pool.shutdown(wait=False)
                        return
                    xbmc.sleep(100)

            # Build item
            mediainfo = map(lambda i: i.result(), futures)
            for i in xrange(itemsCount):
                # Update item with mediainfo
                items[i].update(mediainfo[i * 2])  # Metadata
                items[i].update(mediainfo[i * 2 + 1])  # Subtitle

                # Set video width and hight
                width = 1920
                height = 1080
                if not items[i]['torrents'].get('1080p', None):
                    width = 1280
                    height = 720
                items[i].setdefault("stream_info", {}).setdefault("video",
                                                                  {}).update({
                                                                      "width":
                                                                      width,
                                                                      "height":
                                                                      height
                                                                  })

                # Create player url
                play_kwargs = {
                    'torrents': items[i].pop('torrents'),
                    'subtitle': items[i].pop('subtitle', None),
                    'item': items[i]
                }
                items[i]["path"] = plugin.url_for('play', **play_kwargs)

                # The item is now playable
                items[i]["is_playable"] = True

            # Add next page, but we stop at page 20... yes 20 pages sounds all right
            if page < int(result.get("pages", 1)) and page < 21:
                plugin.log.debug('(Main) page: ' + str(page))
                items.append({
                    "label":
                    '>> ' + __addon__.getLocalizedString(30009),
                    "path":
                    plugin.url_for(
                        'browse',
                        **_build_kwargs(
                            kwargs, {
                                'provider': provider,
                                'separate': separate,
                                'page': page + 1
                            }))
                })

            # Update progress
            dialog.update(100,
                          line1=__addon__.getLocalizedString(30017),
                          line2=' ')

            return items

    except AnErrorOccurred as e:
        errorNotify(e.errno)
    except:
        errorNotify(30308)
    return