示例#1
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)
示例#2
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)