def __init__(self, host, port, username, password): self.deluge_client = DelugeRPCClient(host, port, username, password) try: self.deluge_client.connect() self.connected = self.deluge_client.connected except Exception, e: raise e
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Deluge sensors.""" name = config[CONF_NAME] host = config[CONF_HOST] username = config[CONF_USERNAME] password = config[CONF_PASSWORD] port = config[CONF_PORT] deluge_api = DelugeRPCClient(host, port, username, password) try: deluge_api.connect() except ConnectionRefusedError as err: _LOGGER.error("Connection to Deluge Daemon failed") raise PlatformNotReady from err monitored_variables = config[CONF_MONITORED_VARIABLES] entities = [ DelugeSensor(deluge_api, name, description) for description in SENSOR_TYPES if description.key in monitored_variables ] add_entities(entities)
def dwnTorrent(magnet, hash, dir): client = DelugeRPCClient(dHost, dPort, dUser, dPass) try: client.connect() except: return path = '' torrent = client.call('core.get_torrent_status', hash, []) if torrent: percent = float(torrent[b'file_progress'][0] * 100) #msg = 'already in deluge ({0})'.format(percent) else: client.call('core.add_torrent_magnet', magnet, {'download_location': dir}) #msg = 'not found, adding to deluge' #waiting for the files to appear while not (client.call('core.get_torrent_status', hash, [])[b'files']): time.sleep(2) else: files = client.call('core.get_torrent_status', hash, [])[b'files'] for format in video_formats: for file in files: if format in file[b'path'].decode('utf-8'): path = file[b'path'].replace(b'/', b'\\').decode('utf-8') client.disconnect() return path
def deluge_add_torrent(ip, port, user, password, torrent_binary): client = DelugeRPCClient(ip, int(port), user, password, decode_utf8=True) client.connect() return client.core.add_torrent_file( filename="", filedump=b64encode(torrent_binary).decode('ascii'), options={})
def delete_torrent(): if not request.json or not request.json['torrent_id']: return { 'error': 'Request JSON not correct', 'code': 10, } torrent_id = request.json['torrent_id'] data = {'torrent_id': torrent_id, 'remove_data': True} with DelugeRPCClient(DELUGE_ADDR, int(DELUGE_PORT), DELUGE_USER, DELUGE_PASS) as client: # result = client.call('core.remove_torrent', data) result = client.core.remove_torrent(torrent_id, True) if result: return { 'torrent_id': torrent_id, 'success': 'success', 'code': 0, } else: return { 'torrent_id': torrent_id, 'error': 'Error deleting the torrent', 'code': 11, 'result': result }
def get_client(): c = DelugeRPCClient(plugin.get_setting('ip', unicode), plugin.get_setting('port', int), plugin.get_setting('username', unicode), plugin.get_setting('password', unicode)) c.connect() return c
def on_created(self, event): logging.debug(f"witnessed the creation of {event.src_path}") filepath = Path(event.src_path) if not _valid_torrent_file(filepath): logging.warning(f"ignored invalid torrent file: {event.src_path}") return with DelugeRPCClient(*self._deluge_args) as client: logging.debug(f"connected to deluge: {self._deluge_args}") for field in ("download_location", "move_completed_path"): if field not in self._dir_config["options"]: continue field_value = self._dir_config["options"][field] self._dir_config["options"][field] = field_value.format( FILE=str(filepath), FILE_PARENT=str(filepath.parent), ) try: client.core.add_torrent_file( filepath.name, b64encode(filepath.read_bytes()), self._dir_config["options"], ) except: logging.exception(f"failed to add torrent file: {event.src_path}") logging.info(f"added torrent {event.src_path}")
def connect(self, host, username, password): if self.conn is not None: return self.connect if not host: return False # Get port from the config host,portnr = host.split(':') #if username and password: # logger.info('Connecting to ' + host + ':' + portnr + ' Username: '******' Password: '******'Could not create DelugeRPCClient Object' + e) return False else: try: self.client.connect() except Exception as e: logger.error('Could not connect to Deluge ' + host) else: return self.client
def __init__(self): self.client = DelugeRPCClient(config["deluge_hostname"], config["deluge_port"], config["deluge_username"], config["deluge_password"], decode_utf8=True, automatic_reconnect=True)
def setup_client(self, config): try: from deluge_client import DelugeRPCClient except ImportError as e: log.debug('Error importing deluge-client: %s' % e) raise plugin.DependencyError( 'deluge', 'deluge-client', 'deluge-client >=1.5 is required. `pip install deluge-client` to install.', log, ) config = self.prepare_config(config) if config['host'] in ['localhost', '127.0.0.1' ] and not config.get('username'): # If an username is not specified, we have to do a lookup for the localclient username/password auth = self.get_localhost_auth(config.get('config_path')) if auth and auth[0]: config['username'], config['password'] = auth else: raise plugin.PluginError( 'Unable to get local authentication info for Deluge. You may need to ' 'specify an username and password from your Deluge auth file.' ) return DelugeRPCClient( config['host'], config['port'], config['username'], config['password'], decode_utf8=True, )
def deluge(torrent, CLIENT_URL, TOR_CLIENT_USER, TOR_CLIENT_PW, logger): TOR_CLIENT = "Deluge" print(f"Sending {torrent.description.decode('ascii')} to {TOR_CLIENT}") url = fetch_torrent_url(torrent) try: logger.debug("Connecting to torrent client...") # Connection logger.debug( f"{TOR_CLIENT} connection info: {CLIENT_URL.split(':')[0]}, {int(CLIENT_URL.split(':')[1])}, {TOR_CLIENT_USER}" ) client = DelugeRPCClient( CLIENT_URL.split(':')[0], int(CLIENT_URL.split(':')[1]), TOR_CLIENT_USER, TOR_CLIENT_PW) client.connect() logger.debug(f"Connected to {TOR_CLIENT}") # Add torrent logger.debug( f"Adding {torrent.description.decode('ascii')} with url: {url}") client.call("download_torrent_from_url", url) print("Torrent sent!") except Exception as e: print( f"Unable to send to {TOR_CLIENT}. Check the logs for more information." ) logger.error(f"Error sending to {TOR_CLIENT}. {str(e)}") exit()
def query_torrents_status(self): """Updates downloaded torrents to the Deluse client""" job_list = self.get_jobs_by_status(JobStatus.DOWNLOADING) if len(job_list) == 0: self.logger.info( "No downloading jobs to query for status during job processing" ) return self.logger.info( "Marking completed downloads on Deluge instance at %s", self.config.conversion.deluge_host) with DelugeRPCClient(self.config.conversion.deluge_host, self.config.conversion.deluge_port, self.config.conversion.deluge_user_name, self.config.conversion.deluge_password) as client: for job in job_list: torrent = client.core.get_torrent_status( job.torrent_hash, ["name", "download_location", "is_finished"]) if torrent.get("is_finished".encode(), False): job.name = torrent["name".encode()].decode() job.status = JobStatus.PENDING job.save(self.logger)
def connect(self, host, username, password, test=False): if self.conn is not None: return self.connect if not host: return {'status': False, 'error': 'No host specified'} if not username: return {'status': False, 'error': 'No username specified'} if not password: return {'status': False, 'error': 'No password specified'} # Get port from the config host,portnr = host.split(':') # logger.info('Connecting to ' + host + ':' + portnr + ' Username: '******' Password: '******'Could not create DelugeRPCClient Object %s' % e) return {'status': False, 'error': e} else: try: self.client.connect() except Exception as e: logger.error('Could not connect to Deluge: %s' % host) return {'status': False, 'error': e} else: if test is True: daemon_version = self.client.call('daemon.info') libtorrent_version = self.client.call('core.get_libtorrent_version') return {'status': True, 'daemon_version': daemon_version, 'libtorrent_version': libtorrent_version} else: return self.client
def downloadTorrent(url): url = url + "&authkey=" + AuthKey + "&torrent_pass="******"Downloading: " + url) client = DelugeRPCClient(DelugeIp, DelugePort, DelugeUser, DelugePass) client.connect() hash = client.core.add_torrent_url(url, [], []) print("Hash: " + str(hash)) client.disconnect()
def connect(self): """Connect to the host using synchronousdeluge API.""" try: self.client = DelugeRPCClient(self.host, self.port, self.username, self.password, decode_utf8=True) self.client.connect() except Exception as error: log.warning('Error while trying to connect to deluge daemon. Error: {error}', {'error': error}) raise
def connect(self): """Connect to the host using synchronousdeluge API.""" self.client = DelugeRPCClient(self.host, self.port, self.username, self.password, decode_utf8=True) self.client.connect()
def client(self): return DelugeRPCClient( host=self.host, port=self.port, username=self.username, password=self.password, decode_utf8=True, )
def NewClient(config): return DelugeRPCClient( config["host"].split(":")[0], int(config["host"].split(":")[1]), config["user"], config["pass"], True, False, )
def __init__(self): import config self.client = DelugeRPCClient( host=config.DELUGE['host'], port=config.DELUGE['port'], username=config.DELUGE['uname'], password=config.DELUGE['pword'] ) self.client.connect() self.torrent_status_data = None
def _get_client(self): with DBSession() as db: cred = db.query(DelugeCredentials).first() if not cred: return False if not cred.port: cred.port = self.DEFAULT_PORT return DelugeRPCClient(cred.host, cred.port, cred.username, cred.password)
def add_rutracker_torrent(self, filename: str, torrent: bytes) -> None: logger.info("Add torrent") client = DelugeRPCClient( self.host, self.port, self.user, self.password, ) client.call('core.add_torrent_file', filename, b64encode(torrent), {})
def __init__(self, username='******', password='******', host='127.0.0.1', port=58846): self.checkDelugeExist() if username and password: self.client = DelugeRPCClient(host, port, username, password) try: self.client.connect() except ConnectionRefusedError: pass self.checkConnection() self.getMethods() self.getTorrents()
def validate_deluge( deluge_args: Tuple[str, int, str, str] ) -> Tuple[str, int, str, str]: try: logging.debug(f"testing connection to deluge: {deluge_args}") with DelugeRPCClient(*deluge_args): pass except Exception as e: raise Exception(f"failed to connect to deluge: {e.message}") return deluge_args
def setup(self): parsed_url = urlparse(self.host) if self.client and all([ self.client.host == parsed_url.hostname, self.client.port == parsed_url.port, self.client.username == self.username, self.client.password == self.password ]): return self.client = DelugeRPCClient(parsed_url.hostname, parsed_url.port or 58846, self.username, self.password)
def __init__(self, host="", port=58846, username="", password=""): self.filter = {} self.rpc = DelugeRPCClient( host, port, username, password, ) self.rpc.connect() if not self.rpc.connected: raise RuntimeError("Failed to connect to deluge rpc")
def __init__(self): super().__init__() __DE_URL__ = input("输入客户端IP(http://IP):") __DE_PORT__ = int(input("输入客户端后端端口(非WebUI端口):")) __DE_USER__ = input("输入客户端用户名:") __DE_PW__ = input("输入客户端密码:") self.client = DelugeRPCClient(__DE_URL__, __DE_PORT__, __DE_USER__, __DE_PW__) print("开始连接 Deluge 客户端...") self.client.connect()
def __init__(self, host, port, username, password): self.host = host self.port = port self.username = username self.password = password self.client = DelugeRPCClient( self.host, self.port, self.username, self.password ) self.client.connect() if not self.client.connected: raise DelugeNotConnectedException()
def deluge(self): deluge_rpc = os.environ.get('DELUGE_ADDRESS') if deluge_rpc is not None: client = DelugeRPCClient( deluge_rpc, int(os.environ.get('DELUGE_PORT')), os.environ.get('DELUGE_USER'), os.environ.get('DELUGE_PASS') ) client.connect() return client return None
def main(): parser = argparse.ArgumentParser( description="Add torrents to one or more deluge instances") parser.add_argument( "-s", "--server", action="append", type=DelugeUri, required=True, help= "Deluge host or IP addresses to connect to in the form of user:pass@hostname:port" ) parser.add_argument("torrents", nargs="+", help="torrent files to add") args = parser.parse_args() clients = [] futures = [] for server in args.server: uri = urlparse('deluge://{}'.format(server)) client = DelugeRPCClient(uri.hostname, uri.port if uri.port else 58846, uri.username, uri.password) client.connect() clients.append(client) with ThreadPoolExecutor(max_workers=1) as pool: for torrent_path in args.torrents: t_data = parse_torrent(torrent_path) namehash = md5() t_name = t_data[b'info'][b'name'] namehash.update(t_name) torrent_host = int(namehash.hexdigest(), 16) % len(args.server) futures += [ pool.submit(add_torrent, clients[torrent_host], torrent_path) ] added_by_host = defaultdict(list) for future in futures: client, size, name = future.result() if name: client_id = "{}:{}".format(client.host, client.port) added_by_host[client_id].append(size) added_by_host = dict(added_by_host) print( tabulate([(host, len(added), round(sum(added) / GB, 2)) for host, added in added_by_host.items()], ["host", "added", "size (gb)"]))
def get_client(): from deluge_client import DelugeRPCClient, FailedToReconnectException try: deluge = DelugeRPCClient(config.TORRENT_HOST, int(config.TORRENT_PORT), config.TORRENT_USER, config.TORRENT_PASS) deluge.connect() if not deluge.connected: raise FailedToReconnectException except FailedToReconnectException: logger.error('Не удалось соединиться с торрент торрент клиентом') return None return deluge