예제 #1
0
    def start(self):
        if not self._shutdown:
            log('(Torrent) Find free port', LOGLEVEL.INFO)
            port = get_free_port()

            log('(Torrent) Starting torrent2http', LOGLEVEL.INFO)
            startupinfo = None
            if Platform.system == "windows":
                startupinfo = subprocess.STARTUPINFO()
                startupinfo.dwFlags |= 1
                startupinfo.wShowWindow = 0

            if _settings.debug:
                self._logpipe = LogPipe(self._debug)

            torrent_options = self._mediaSettings.get_torrent_options(self._magnet, port)
            try:
                self._process = subprocess.Popen(torrent_options, stderr=self._logpipe, stdout=self._logpipe, startupinfo=startupinfo)
            except:
                raise TorrentError("Can't start torrent2http: %s" % str(sys.exc_info()[1]))
            self._url = "http://127.0.0.1:%s/" %port

            start = time.time()
            while not self._shutdown:
                if (time.time() - start) > 5 or not self.isAlive():
                    raise TorrentError("Can't start torrent2http")
                if not self.status(1)['state'] == self.NO_CONNECTION:
                    log("(Torrent) torrent2http successfully started")
                    return True
        return False
예제 #2
0
    def start(self):
        if not self._shutdown:
            log('(Torrent) Find free port', LOGLEVEL.INFO)
            port = get_free_port()

            log('(Torrent) Starting torrent2http', LOGLEVEL.INFO)
            startupinfo = None
            if Platform.system == "windows":
                startupinfo = subprocess.STARTUPINFO()
                startupinfo.dwFlags |= 1
                startupinfo.wShowWindow = 0

            if _settings.debug:
                self._logpipe = LogPipe(self._debug)

            torrent_options = self._mediaSettings.get_torrent_options(self._magnet, port)
            try:
                self._process = subprocess.Popen(torrent_options, stderr=self._logpipe, stdout=self._logpipe, startupinfo=startupinfo)
            except:
                raise TorrentError("Can't start torrent2http: %s" % str(sys.exc_info()[1]))
            self._url = "http://127.0.0.1:%s/" %port

            start = time.time()
            while not self._shutdown:
                if (time.time() - start) > 5 or not self.isAlive():
                    raise TorrentError("Can't start torrent2http")
                if not self.status(1)['state'] == self.NO_CONNECTION:
                    log("(Torrent) torrent2http successfully started")
                    return True
        return False
예제 #3
0
class TorrentEngine:
    QUEUED_FOR_CHECKING     = 0
    CHECKING_FILES          = 1
    DOWNLOADING_METADATA    = 2
    DOWNLOADING             = 3
    FINISHED                = 4
    SEEDING                 = 5
    ALLOCATING              = 6
    CHECKING_RESUME_DATA    = 7
    NO_CONNECTION           = 8

    def __init__(self, mediaSettings, magnet):
        log('(Torrent) Initialize torrent engine', LOGLEVEL.INFO)
        self._mediaSettings      = mediaSettings
        self._magnet             = magnet
        self._url                = None
        self._shutdown           = False
        self._process            = None
        self._logpipe            = None
        self._file_id            = None
        self._json               = request.Json()
        # "IOError: [Errno 9] Bad file descriptor" FIX!!!
        self._last_status   = {"name":"","state":self.NO_CONNECTION,"state_str":"no_connection","error":"","progress":0,"download_rate":0, "upload_rate":0,"total_download":0,"total_upload":0,"num_peers":0,"num_seeds":0,"total_seeds":-1,"total_peers":-1}
        self._last_files    = []

    def __enter__(self):
        return self

    def start(self):
        if not self._shutdown:
            log('(Torrent) Find free port', LOGLEVEL.INFO)
            port = get_free_port()

            log('(Torrent) Starting torrent2http', LOGLEVEL.INFO)
            startupinfo = None
            if Platform.system == "windows":
                startupinfo = subprocess.STARTUPINFO()
                startupinfo.dwFlags |= 1
                startupinfo.wShowWindow = 0

            if _settings.debug:
                self._logpipe = LogPipe(self._debug)

            torrent_options = self._mediaSettings.get_torrent_options(self._magnet, port)
            try:
                self._process = subprocess.Popen(torrent_options, stderr=self._logpipe, stdout=self._logpipe, startupinfo=startupinfo)
            except:
                raise TorrentError("Can't start torrent2http: %s" % str(sys.exc_info()[1]))
            self._url = "http://127.0.0.1:%s/" %port

            start = time.time()
            while not self._shutdown:
                if (time.time() - start) > 5 or not self.isAlive():
                    raise TorrentError("Can't start torrent2http")
                if not self.status(1)['state'] == self.NO_CONNECTION:
                    log("(Torrent) torrent2http successfully started")
                    return True
        return False

    def isAlive(self):
        return self._process and self._process.poll() is None

    def status(self, timeout=10):
        if not self._shutdown:
            try:
                if not self.isAlive():
                    raise TorrentError("torrent2http are not running")
                self._last_status = self._json.request(self._url, "/status", timeout=timeout) or self._last_status
                if self._last_status.get('error'):
                    raise TorrentError("torrent2http error: %s" %self._last_status['error'])
            except (JSONDecodeError, socket.timeout, IOError) as e:
                log('(Torrent) %s: %s' %(e.__class__.__name__, str(e)), LOGLEVEL.NOTICE)
                sys.exc_clear()
        return self._last_status

    def files(self, timeout=10):
        if not self._shutdown:
            try:
                if not self.isAlive():
                    raise TorrentError("torrent2http are not running")
                self._last_files = self._json.request(self._url, "/ls", timeout=timeout)['files'] or self._last_files
            except (JSONDecodeError, socket.timeout, IOError) as e:
                log('(Torrent) %s: %s' %(e.__class__.__name__, str(e)), LOGLEVEL.NOTICE)
                sys.exc_clear()
        return self._last_files


    def playFile(self, timeout=10):
        files = self.files(timeout)
        if not files:
            return {}
        if self._file_id is None:
            size = 0
            for i, f in enumerate(files):
                mimeType = mimetypes.guess_type(f['name'])
                log('(Torrent) File name: %s, MIME info: %s' %(f['name'], str(mimeType)))
                # if mimeType[0] and mimeType[0][:5] == 'video' and f['size'] > size:
                #if 'video' in str(mimeType) and f['size'] > size:
                if(re.match('.*\.avi|.*\.mp4|.*\.mkv',f['name'])):
                    self._file_id = i
                    urllib2.urlopen(f['url'], timeout=50)
        try:
            return files[self._file_id]
        except (KeyError, TypeError):
            raise TorrentError("Can not find a file to play")

    def shutdown(self, timeout=1):
        if self.isAlive():
            if self._logpipe:
                log("(Torrent) Shutting down log pipe")
                self._logpipe.close()
            log("(Torrent) Shutting down torrent2http")
            try:
                request.Send().request(self._url, "/shutdown", timeout=timeout)
                start = time.time()
                while (time.time() - start) < 10:
                    time.sleep(0.100)
                    if not self.isAlive():
                        log("(Torrent) torrent2http successfully shutdown", LOGLEVEL.INFO)
                        break
                else:
                    log("(Torrent) Timeout occurred while shutting down torrent2http", LOGLEVEL.WARNING)
            except:
                log("(Torrent) An error occurred while shutting down torrent2http", LOGLEVEL.WARNING)
            if self.isAlive():
                log("(Torrent) Killing torrent2http", LOGLEVEL.WARNING)
                self._process.kill()
            self._logpipe = self._process = None

    def _debug(self, message):
        log("(Torrent) (torrent2http) %s" % message)

    def __exit__(self, *exc_info):
        self.close()
        return not exc_info[0]

    def __del__(self):
        self.close()

    def close(self):
        if hasattr(self, '_json') and not self._shutdown:
            self._shutdown = True
            try:
                self._json.cancel()
                self.shutdown()
            finally:
                self._json = None
                # Clean debris from the cache dir
                if not self._mediaSettings.user_download_path and self._mediaSettings.delete_files:
                    try:
                        clear_media_cache(self._mediaSettings.media_cache_path)
                    except:
                        pass
예제 #4
0
class TorrentEngine:
    QUEUED_FOR_CHECKING     = 0
    CHECKING_FILES          = 1
    DOWNLOADING_METADATA    = 2
    DOWNLOADING             = 3
    FINISHED                = 4
    SEEDING                 = 5
    ALLOCATING              = 6
    CHECKING_RESUME_DATA    = 7
    NO_CONNECTION           = 8

    def __init__(self, mediaSettings, magnet):
        log('(Torrent) Initialize torrent engine', LOGLEVEL.INFO)
        self._mediaSettings      = mediaSettings
        self._magnet             = magnet
        self._url                = None
        self._shutdown           = False
        self._process            = None
        self._logpipe            = None
        self._file_id            = None
        self._json               = request.Json()
        # "IOError: [Errno 9] Bad file descriptor" FIX!!!
        self._last_status   = {"name":"","state":self.NO_CONNECTION,"state_str":"no_connection","error":"","progress":0,"download_rate":0, "upload_rate":0,"total_download":0,"total_upload":0,"num_peers":0,"num_seeds":0,"total_seeds":-1,"total_peers":-1}
        self._last_files    = []

    def __enter__(self):
        return self

    def start(self):
        if not self._shutdown:
            log('(Torrent) Find free port', LOGLEVEL.INFO)
            port = get_free_port()

            log('(Torrent) Starting torrent2http', LOGLEVEL.INFO)
            startupinfo = None
            if Platform.system == "windows":
                startupinfo = subprocess.STARTUPINFO()
                startupinfo.dwFlags |= 1
                startupinfo.wShowWindow = 0

            if _settings.debug:
                self._logpipe = LogPipe(self._debug)

            torrent_options = self._mediaSettings.get_torrent_options(self._magnet, port)
            try:
                self._process = subprocess.Popen(torrent_options, stderr=self._logpipe, stdout=self._logpipe, startupinfo=startupinfo)
            except:
                raise TorrentError("Can't start torrent2http: %s" % str(sys.exc_info()[1]))
            self._url = "http://127.0.0.1:%s/" %port

            start = time.time()
            while not self._shutdown:
                if (time.time() - start) > 5 or not self.isAlive():
                    raise TorrentError("Can't start torrent2http")
                if not self.status(1)['state'] == self.NO_CONNECTION:
                    log("(Torrent) torrent2http successfully started")
                    return True
        return False

    def isAlive(self):
        return self._process and self._process.poll() is None

    def status(self, timeout=10):
        if not self._shutdown:
            try:
                if not self.isAlive():
                    raise TorrentError("torrent2http are not running")
                self._last_status = self._json.request(self._url, "/status", timeout=timeout) or self._last_status
                if self._last_status.get('error'):
                    raise TorrentError("torrent2http error: %s" %self._last_status['error'])
            except (JSONDecodeError, socket.timeout, IOError) as e:
                log('(Torrent) %s: %s' %(e.__class__.__name__, str(e)), LOGLEVEL.NOTICE)
                sys.exc_clear()
        return self._last_status

    def files(self, timeout=10):
        if not self._shutdown:
            try:
                if not self.isAlive():
                    raise TorrentError("torrent2http are not running")
                self._last_files = self._json.request(self._url, "/ls", timeout=timeout)['files'] or self._last_files
            except (JSONDecodeError, socket.timeout, IOError) as e:
                log('(Torrent) %s: %s' %(e.__class__.__name__, str(e)), LOGLEVEL.NOTICE)
                sys.exc_clear()
        return self._last_files

    def playFile(self, timeout=10):
        files = self.files(timeout)
        if not files:
            return {}
        if self._file_id is None:
            size = 0
            for i, f in enumerate(files):
                mimeType = mimetypes.guess_type(f['name'])
                log('(Torrent) File name: %s, MIME info: %s' %(f['name'], str(mimeType)))
                if mimeType[0] and mimeType[0][:5] == 'video' and f['size'] > size:
                    self._file_id = i
        try:
            return files[self._file_id]
        except (KeyError, TypeError):
            raise TorrentError("Can not find a file to play")

    def shutdown(self, timeout=1):
        if self.isAlive():
            if self._logpipe:
                log("(Torrent) Shutting down log pipe")
                self._logpipe.close()
            log("(Torrent) Shutting down torrent2http")
            try:
                request.Send().request(self._url, "/shutdown", timeout=timeout)
                start = time.time()
                while (time.time() - start) < 10:
                    time.sleep(0.100)
                    if not self.isAlive():
                        log("(Torrent) torrent2http successfully shutdown", LOGLEVEL.INFO)
                        break
                else:
                    log("(Torrent) Timeout occurred while shutting down torrent2http", LOGLEVEL.WARNING)
            except:
                log("(Torrent) An error occurred while shutting down torrent2http", LOGLEVEL.WARNING)
            if self.isAlive():
                log("(Torrent) Killing torrent2http", LOGLEVEL.WARNING)
                self._process.kill()
            self._logpipe = self._process = None

    def _debug(self, message):
        log("(Torrent) (torrent2http) %s" % message)

    def __exit__(self, *exc_info):
        self.close()
        return not exc_info[0]

    def __del__(self):
        self.close()

    def close(self):
        if hasattr(self, '_json') and not self._shutdown:
            self._shutdown = True
            try:
                self._json.cancel()
                self.shutdown()
            finally:
                self._json = None
                # Clean debris from the cache dir
                if not self._mediaSettings.user_download_path and self._mediaSettings.delete_files:
                    try:
                        clear_media_cache(self._mediaSettings.media_cache_path)
                    except:
                        pass