本文整理汇总了Python中deluge_client.DelugeRPCClient.call方法的典型用法代码示例。如果您正苦于以下问题:Python DelugeRPCClient.call方法的具体用法?Python DelugeRPCClient.call怎么用?Python DelugeRPCClient.call使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类deluge_client.DelugeRPCClient
的用法示例。
在下文中一共展示了DelugeRPCClient.call方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: uploadTorrent
# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import call [as 别名]
def uploadTorrent(self, filename):
"""
Upload a torrent to the deluge host based on the config file
"""
print('Uploading torrent %s' % (filename))
client = DelugeRPCClient(self.hostDeluge, self.portDeluge, self.usernameDeluge, self.passwordDeluge)
client.connect()
f = open(filename, 'rb')
filedump = base64.encodestring(f.read())
f.close()
client.call('core.add_torrent_file', filename, filedump, {}, )
bytes_available = client.call('core.get_free_space')
gig_available = bytes_available/(1024.*1024*1024)
print('There is %.1f GB available on the host \'%s\'.' % (gig_available, self.hostDeluge))
示例2: main
# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import call [as 别名]
def main():
"""
Entry function
"""
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument(
'-d', '--dir', type=lambda x: is_valid_directory(parser, x),
help='the directory to hold the file structure', required=True
)
parser.add_argument(
'hosts', metavar='H', type=lambda x: is_valid_host(parser, x),
nargs='+', help='the Deluge hosts'
)
args = parser.parse_args()
tracker_map = {}
clients = []
for host in args.hosts:
client = DelugeRPCClient(*host)
client.connect()
clients.append(client)
for entry in listdir_fullpath(args.dir):
recursive_rm_dir(entry)
for client in clients:
torrents = client.call(
'core.get_torrents_status',
{},
['name', 'save_path', 'tracker_host']
)
for _, torrent in torrents.items():
if torrent[b'tracker_host'] not in tracker_map:
tracker_map[torrent[b'tracker_host'].decode('utf-8')] = []
tracker_map[torrent[b'tracker_host'].decode('utf-8')].append(torrent)
for tracker, torrents in tracker_map.items():
loc = os.path.join(args.dir, tracker)
if not os.path.exists(loc):
os.makedirs(loc)
for torrent in torrents:
link_from = os.path.join(loc, torrent[b'name'].decode('utf-8'))
link_to = os.path.join(
torrent[b'save_path'].decode('utf-8'),
torrent[b'name'].decode('utf-8')
)
if not os.path.exists(link_from):
try:
os.symlink(link_to, link_from)
except OSError as error:
if error.errno == errno.EEXIST:
os.remove(link_from)
os.symlink(link_to, link_from)
else:
raise error
示例3: DelugePlugin
# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import call [as 别名]
class DelugePlugin(object):
"""Base class for deluge plugins, contains settings and methods for connecting to a deluge daemon."""
def on_task_start(self, task, config):
"""Raise a DependencyError if our dependencies aren't available"""
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()
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.')
self.client = DelugeRPCClient(config['host'], config['port'], config['username'], config['password'],
decode_utf8=True)
def prepare_config(self, config):
config.setdefault('host', 'localhost')
config.setdefault('port', 58846)
return config
def get_torrents_status(self, fields, filters=None):
"""Fetches all torrents and their requested fields optionally filtered"""
if filters is None:
filters = {}
return self.client.call('core.get_torrents_status', filters, fields)
@staticmethod
def get_localhost_auth():
if sys.platform.startswith('win'):
auth_file = os.path.join(os.getenv('APPDATA'), 'deluge', 'auth')
else:
auth_file = os.path.expanduser('~/.config/deluge/auth')
if not os.path.isfile(auth_file):
return None
with open(auth_file) as auth:
for line in auth:
line = line.strip()
if line.startswith('#') or not line:
# This is a comment or blank line
continue
lsplit = line.split(':')
if lsplit[0] == 'localclient':
username, password = lsplit[:2]
return username, password
示例4: torrents_status
# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import call [as 别名]
def torrents_status():
STATUS_KEYS = [
"state",
"download_location",
"tracker_host",
"tracker_status",
"next_announce",
"name",
"total_size",
"progress",
"num_seeds",
"total_seeds",
"num_peers",
"total_peers",
"eta",
"download_payload_rate",
"upload_payload_rate",
"ratio",
"distributed_copies",
"num_pieces",
"piece_length",
"total_done",
"files",
"file_priorities",
"file_progress",
"peers",
"is_seed",
"is_finished",
"active_time",
"seeding_time"
]
from deluge_client import DelugeRPCClient
client = DelugeRPCClient('127.0.0.1', 2196, "seftembr", "TuGsFYqlNP")
client.connect()
print "--- ACTIVE ---"
for (hashid, fields) in client.call('core.get_torrents_status', {"state":"Active"}, STATUS_KEYS).iteritems():
print "%s: %s (%.2f out of %s - active for %s so far)" % (hashid, fields['name'], fields['progress'], sizeof_fmt(fields['total_size']), human_time(seconds=fields['active_time']))
print "--- PAUSED ---"
for (hashid, fields) in client.call('core.get_torrents_status', {"state":"Paused"}, STATUS_KEYS).iteritems():
if fields['progress'] == 100:
print "%s: %s (%s downloaded in %s)" % (hashid, fields['name'], sizeof_fmt(fields['total_size']), human_time(seconds=fields['active_time']))
else:
print "%s: %s (%.2f out of %s - was active for %s - and paused)" % (hashid, fields['name'], fields['progress'], sizeof_fmt(fields['total_size']), human_time(seconds=fields['active_time']))
示例5: DelugeClient
# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import call [as 别名]
class DelugeClient(BaseClient):
identifier = 'deluge'
def __init__(self, host, username, password):
"""
Initializes a new Deluge client.
url - The url where deluge json can be reached.
password - The password used to login
"""
host, port = host.split(':')
self.host = host
self.port = int(port)
self.username = username
self.password = password
self.rpcclient = DelugeRPCClient(self.host, self.port, self.username, self.password)
def _login(self):
"""
Logs into deluge
"""
if not self.rpcclient.connected:
self.rpcclient.connect()
def get_config(self):
"""
Get the current configuration that can be used in the autotorrent config file
"""
return {
'host': '%s:%s' % (self.host, self.port),
'username': self.username,
'password': self.password,
}
@classmethod
def auto_config(cls):
"""
Tries to auto configure deluge using the .config/deluge files
"""
config_path = os.path.expanduser('~/.config/deluge/core.conf')
if not os.path.isfile(config_path):
logger.debug('deluge config file was not found')
return
if not os.access(config_path, os.R_OK):
logger.debug('Unable to access deluge config file at %s' % config_path)
return
auth_path = os.path.expanduser('~/.config/deluge/auth')
if not os.path.isfile(auth_path):
logger.debug('deluge auth file was not found')
return
if not os.access(auth_path, os.R_OK):
logger.debug('Unable to access deluge confauthig file at %s' % auth_path)
return
with open(config_path, 'r') as f:
config_data = f.read()
daemon_port = re.findall('"daemon_port":\s*(\d+)', config_data)
if not daemon_port:
logger.debug('No deluge port, just trying to use default')
daemon_port = 58846
else:
daemon_port = int(daemon_port[0])
with open(auth_path, 'r') as f:
auth_data = f.read()
auth_data = auth_data.split('\n')[0].split(':')
if len(auth_data[0]) < 2:
logger.debug('Invalid entry found in auth file')
return
username = auth_data[0]
password = auth_data[1]
return cls('127.0.0.1:%s' % daemon_port, username, password)
def test_connection(self):
"""
Tests the Deluge RPC connection, returns message if found.
"""
self._login()
return 'Free space: %s' % humanize_bytes(self.rpcclient.call('core.get_free_space'))
def get_torrents(self):
"""
Returns a set of info hashes currently added to the client.
"""
logger.info('Getting a list of torrent hashes')
self._login()
result = self.rpcclient.call('core.get_torrents_status', {}, ['name'])
return set(x.lower().decode('ascii') for x in result.keys())
def add_torrent(self, torrent, destination_path, files, fast_resume=True):
"""
Add a new torrent to Deluge.
#.........这里部分代码省略.........
示例6: DelugeClientKORPI
# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import call [as 别名]
class DelugeClientKORPI():
"""
Class for controlling deluge client.
"""
def __init__(self, username, password, host="127.0.0.1", port=58846):
self._username = username
self._password = password
self._host = host
self._port = port
self.__client = DelugeRPCClient(host, int(port), username, password)
def connect(self):
self.__client.connect()
def list(self):
"""Returns tuple with torrent hashes"""
return self.__client.call("core.get_session_state")
def status(self, thash=None):
if thash:
return self.__client.call('core.get_torrents_status', {"hash": thash}, [])
else:
return self.__client.call('core.get_torrents_status', {}, [])
def completed(self, thash):
"""Returns % of downloaded from torrent."""
status = self.__client.call('core.get_torrents_status', {"hash": thash}, [])
thash = thash.encode("utf-8")
if status[thash][b"total_wanted"] == 0:
return 0
else:
return status[thash][b"total_done"] / status[thash][b"total_wanted"] * 100
def pause(self, thash=None):
"""
If hash not provided, pause/resume all torrents.
Returns False if torrent(s) was paused, True otherwise.
"""
if thash:
status = self.status(thash)[thash.encode("utf-8")][b"paused"]
if status:
self.__client.call('core.resume_torrent', [thash])
else:
self.__client.call('core.pause_torrent', [thash])
return status
else:
if self.all_paused():
self.__client.call("core.resume_torrent", self.list())
else:
self.__client.call("core.pause_torrent", self.list())
return self.all_paused()
def add(self, magnet, directory, max_speed):
return self.__client.call('core.add_torrent_magnet', magnet,
{"download_location": directory, "max_download_speed": max_speed})
def remove(self, thash, with_files):
"""Set with_files True to remove with files"""
if with_files == "True": with_files = True
elif with_files == "False": with_files = False
return self.__client.call("core.remove_torrent", thash, with_files)
def free_space(self, directory):
"""Get free space in megabytes."""
return self.__client.call("core.get_free_space", directory) * TO_GB
def download_speed(self, dmax=-1):
for thash in self.list():
self.__client.call("core.set_torrent_max_download_speed",
thash, int(dmax))
def all_paused(self):
return all(paused[b"paused"]
for _, paused in self.status().items())
示例7: Deluge
# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import call [as 别名]
class Deluge(IntervalModule):
"""
Deluge torrent module
Requires `deluge-client`
.. rubric:: Formatters:
* `{num_torrents}` - number of torrents in deluge
* `{free_space_bytes}` - bytes free in path
* `{used_space_bytes}` - bytes used in path
* `{upload_rate}` - bytes sent per second
* `{download_rate}` - bytes received per second
* `{total_uploaded}` - bytes sent total
* `{total_downloaded}` - bytes received total
"""
settings = (
'format',
('rounding', 'number of decimal places to round numbers too'),
('host', 'address of deluge server (default: 127.0.0.1)'),
('port', 'port of deluge server (default: 58846)'),
('username', 'username to authenticate with deluge'),
('password', 'password to authenticate to deluge'),
('path', 'override "download path" server-side when checking space used/free'),
('offline_string', 'string to output while unable to connect to deluge daemon')
)
required = ('username', 'password')
host = '127.0.0.1'
port = 58846
path = None
libtorrent_stats = False
rounding = 2
offline_string = 'offline'
format = '⛆{num_torrents} ✇{free_space_bytes}'
id = int(time.time()) # something random
def init(self):
self.client = DelugeRPCClient(self.host, self.port, self.username, self.password)
self.data = {}
def run(self):
if not self.client.connected:
try:
self.client.connect()
except OSError:
self.output = {
'full_text': self.offline_string
}
return
try:
self.data = self.get_session_statistics()
torrents = self.get_torrents_status()
if torrents:
self.data['num_torrents'] = len(torrents)
if 'free_space_bytes' in self.format:
self.data['free_space_bytes'] = self.get_free_space(self.path)
if 'used_space_bytes' in self.format:
self.data['used_space_bytes'] = self.get_path_size(self.path)
except FailedToReconnectException:
return
self.parse_values(self.data)
self.output = {
'full_text': self.format.format(**self.data)
}
def parse_values(self, values):
for k, v in values.items():
if v:
if k in ['total_upload', 'total_download', 'download_rate', 'upload_rate'] or k.endswith('_bytes'):
values[k] = '{value:.{round}f}{unit}'.format(round=self.rounding, **bytes_info_dict(v))
def get_path_size(self, path=None):
"""
get used space of path in bytes (default: download location)
"""
if path is None:
path = []
return self.client.call('core.get_path_size', path)
def get_free_space(self, path=None):
"""
get free space of path in bytes (default: download location)
"""
if path is None:
path = []
return self.client.call('core.get_free_space', path)
def get_torrents_status(self, torrent_id=None, keys=None):
if torrent_id is None:
torrent_id = []
if keys is None:
#.........这里部分代码省略.........
示例8: DelugeRPCClient
# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import call [as 别名]
delete_dir = None
log.debug("Path: %s." % path)
log.debug("Torrent: %s." % torrent_name)
log.debug("Hash: %s." % torrent_id)
client = DelugeRPCClient(host=settings.deluge['host'], port=int(settings.deluge['port']), username=settings.deluge['user'], password=settings.deluge['pass'])
client.connect()
if client.connected:
log.info("Successfully connected to Deluge")
else:
log.error("Failed to connect to Deluge")
sys.exit()
torrent_data = client.call('core.get_torrent_status', torrent_id, ['files', 'label'])
torrent_files = torrent_data['files']
category = torrent_data['label'].lower()
files = []
log.debug("List of files in torrent:")
for contents in torrent_files:
files.append(contents['path'])
log.debug(contents['path'])
if category.lower() not in categories:
log.error("No valid category detected.")
sys.exit()
if len(categories) != len(set(categories)):
log.error("Duplicate category detected. Category names must be unique.")
示例9: DelugeClient
# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import call [as 别名]
class DelugeClient(object):
def __init__(self, host, port, username, password):
"""
Initializes a new Deluge client.
url - The url where deluge json can be reached.
password - The password used to login
"""
self.host = host
self.port = port
self.username = username
self.password = password
self.rpcclient = DelugeRPCClient(self.host, self.port, self.username, self.password)
def _login(self):
"""
Logs into deluge
"""
if not self.rpcclient.connected:
self.rpcclient.connect()
def test_connection(self):
"""
Tests the Deluge RPC connection, returns message if found.
"""
self._login()
return 'Free space: %s' % humanize_bytes(self.rpcclient.call('core.get_free_space'))
def get_torrents(self):
"""
Returns a set of info hashes currently added to the client.
"""
logger.info('Getting a list of torrent hashes')
self._login()
result = self.rpcclient.call('core.get_torrents_status', {}, ['name'])
return set(x.lower() for x in result.keys())
def add_torrent(self, torrent, destination_path, files, fast_resume=True):
"""
Add a new torrent to Deluge.
torrent is the decoded file as a python object.
destination_path is where the links are. The complete files must be linked already.
files is a list of files found in the torrent.
"""
name = torrent[b'info'][b'name']
logger.info('Trying to add a new torrent to deluge: %r' % name)
destination_path = os.path.abspath(destination_path)
infohash = hashlib.sha1(bencode(torrent[b'info'])).hexdigest()
encoded_torrent = base64.b64encode(bencode(torrent))
basename = os.path.basename(destination_path)
mapped_files = {}
for i, f in enumerate(files):
mapped_files[i] = os.path.join(basename, *f['path'])
self._login()
result = self.rpcclient.call('core.add_torrent_file', 'torrent.torrent', encoded_torrent, {
'download_location': os.path.dirname(destination_path),
'mapped_files': mapped_files})
return result and result.decode('utf-8') == infohash
示例10: add_torrent
# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import call [as 别名]
def add_torrent(magnet_url):
from deluge_client import DelugeRPCClient
client = DelugeRPCClient('127.0.0.1', 2196, "seftembr", "TuGsFYqlNP")
client.connect()
result = client.call('core.add_torrent_magnet', magnet_url, {})
print "Returned hash:", result
示例11: _mkdtemp
# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import call [as 别名]
class Deluge:
def _mkdtemp(self):
cache_path = cherrypy.config['opmuse'].get('cache.path')
dir = os.path.join(cache_path, 'deluge')
if not os.path.exists(dir):
os.mkdir(dir)
return tempfile.mkdtemp(dir=dir)
def connect(self, timeout=20):
config = cherrypy.tree.apps[''].config['opmuse']
if 'deluge.host' not in config:
log('Deluge not configured, skipping')
return False
host = config['deluge.host']
port = config['deluge.port']
user = config['deluge.user']
password = config['deluge.password']
DelugeRPCClient.timeout = timeout
self.client = DelugeRPCClient(host, port, user, password)
try:
self.client.connect()
except OSError as e:
if e.errno == 113: # "No route to host"
log('No route to host: %s' % host)
return False
else:
raise e
return self.client.connected
def update_torrents(self):
torrents = self.client.call('core.get_torrents_status', {},
['name', 'files', 'save_path', 'time_added',
'total_size', 'paused', 'is_finished', 'progress'])
all_torrents = set()
for torrent_id, in get_database().query(Torrent.torrent_id).all():
all_torrents.add(torrent_id)
for torrent_id, data in torrents.items():
torrent_id = torrent_id.decode('utf-8')
if torrent_id in all_torrents:
all_torrents.remove(torrent_id)
torrent = get_database().query(Torrent).filter(Torrent.torrent_id == torrent_id).one()
else:
torrent = Torrent()
for file in data[b'files']:
if Library.is_supported(file[b'path']):
has_supported_files = True
break
else:
has_supported_files = False
torrent.torrent_id = torrent_id
torrent.name = data[b'name'].decode('utf-8')
torrent.has_supported_files = has_supported_files
torrent.added = datetime.datetime.fromtimestamp(data[b'time_added'])
torrent.size = data[b'total_size']
torrent.paused = data[b'paused']
torrent.finished = data[b'is_finished']
torrent.progress = data[b'progress']
get_database().add(torrent)
get_database().commit()
if len(all_torrents) > 0:
(get_database().query(Torrent).filter(Torrent.torrent_id.in_(all_torrents))
.delete(synchronize_session='fetch'))
get_database().commit()
def import_torrent(self, torrent_id):
config = cherrypy.tree.apps[''].config['opmuse']
ssh_host = config['deluge.ssh_host']
if ssh_host is None:
raise Exception('You need to set deluge.ssh_host')
debug('fetching torrent %s info' % torrent_id)
torrent = self.client.call('core.get_torrent_status', torrent_id, [])
filelist_fd, filelist_path = tempfile.mkstemp()
files = []
tempdir = self._mkdtemp().encode()
with os.fdopen(filelist_fd, 'bw') as f:
for file in torrent[b'files']:
path = os.path.join(torrent[b'save_path'], file[b'path'])
f.write(path + b"\n")
#.........这里部分代码省略.........
示例12: DelugeRPCClient
# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import call [as 别名]
username='localclient' # Se puede ver en home/.config/deluge/auth . Este es de level 10 = admin
password='a66a712b37e2aba2b7873856a0b4de49281a42a7' # Se puede ver en home/.config/deluge/auth
client = DelugeRPCClient(servidor, puerto, username, password)
client.connect()
if client.connected:
print "Conectado a " +servidor+':'+str(puerto)
if len(sys.argv) > 1:
if sys.argv[1] == '-add':
if sys.argv[2] == '-magnet':
uri = sys.argv[3]
client.call('core.add_torrent_magnet', uri,{})
elif sys.argv[2] == '-torrent':
uri = sys.argv[3]
# TODO
else:
print 'Error: Algo no va bien...'
elif sys.argv[1] == '-s':
status = client.call('core.get_torrents_status', {}, [])
if sys.argv > 2:
if sys.argv[2] == '-list':
print 'Num. de Torrents: '+ str(len(status))
c=0
for i in status.values():
c+=1
示例13: DelugeRPCClient
# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import call [as 别名]
client = DelugeRPCClient(
host=settings.deluge["host"],
port=int(settings.deluge["port"]),
username=settings.deluge["user"],
password=settings.deluge["pass"],
)
client.connect()
if client.connected:
log.info("Successfully connected to Deluge")
else:
log.error("Failed to connect to Deluge")
sys.exit()
torrent_data = client.call("core.get_torrent_status", torrent_id, ["files", "label"])
torrent_files = torrent_data["files"]
category = torrent_data["label"].lower()
files = []
log.debug("List of files in torrent:")
for contents in torrent_files:
files.append(contents["path"])
log.debug(contents["path"])
if category.lower() not in categories:
log.error("No valid category detected.")
sys.exit()
if len(categories) != len(set(categories)):
log.error("Duplicate category detected. Category names must be unique.")
示例14: main
# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import call [as 别名]
def main(torrent_id, torrent_name, save_path):
file_extensions = ['r\d+', 'rar', 'zip']
client = DelugeRPCClient(cfg.deluge_address, cfg.deluge_port, cfg.deluge_user, cfg.deluge_pass)
client.connect()
print("Starting '%s' with id='%s' at %s" % (torrent_name, torrent_id, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
if not client.connected:
print("Error connecting to deluge")
sys.exit()
#pprint.pprint(client.call('core.get_torrents_status', {}, ['name']))
#pprint.pprint(client.call('core.get_torrent_status', torrent_id, ['files']))
#print("|".join(file_extensions))
try:
torrent_file = client.call('core.get_torrent_status', torrent_id, ['files'])['files']
except:
print("Error matching torrent_id in deluge")
sys.exit()
neither_radarr_sonarr = True
search = False
for file in torrent_file:
search = re.search("(" + "|".join(file_extensions) + ")$", file['path'])
search = search.group() if search else None
if search:
print("Torrent contained unwanted file type:")
print("\t" + file['path'] + "\t" + str(search))
sonarr_item = search_sonarr_for_torrent_name(torrent_name)
if not sonarr_item:
radarr_item = search_radarr_for_torrent_name(torrent_name)
if not radarr_item:
print("Torrent not found in radarr or sonarr")
break
else:
neither_radarr_sonarr = False
# Blacklist in sonarr
if radarr_item:
id = radarr_item['id']
sonarr_radarr_target = delete_from_radarr
print("\tSending to radarr background thread.")
if sonarr_item:
id = sonarr_item['id']
sonarr_radarr_target = delete_from_sonarr
print("\tSending to sonarr background thread.")
thread = Thread(target = sonarr_radarr_target, args = (id, ))
thread.start()
thread.join()
break
if (not search) and (neither_radarr_sonarr):
# Torrent is okay, lets start the download.
print("Torrent is okay, un-pausing download. Neither radar or sonarr == %s" % (neither_radarr_sonarr))
client.call('core.resume_torrent', [torrent_id])
else:
if sonarr_item:
print("Requesting sonarr searches for the eppisode again")
url = "http://%s:%s/sonarr/api/command?apikey=%s" % (sonarr_host, sonarr_port, cfg.sonarr_apikey)
elif radarr_item:
print("Requesting radarr searches for the eppisode again")
url = "http://%s:%s/radarr/api/command?apikey=%s" % (radarr_host, radarr_port, cfg.radarr_apikey)
else:
print("Neither sonar or radarr... exiting...")
sys.exit(0)
data={"name": "EpisodeSearch", "episodeIds": [sonarr_item['episode']['id']]}
#pprint.pprint(data)
time.sleep(90)
d = requests.post(url, json=data)
print("\t'" + url + "', response=" + str(d.status_code) + "\r\n")
print("____________________________________________\r\n")
示例15: TorrentClient
# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import call [as 别名]
class TorrentClient(object):
def __init__(self):
self.conn = None
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: ' + username + ' Password: ' + password )
try:
self.client = DelugeRPCClient(host,int(portnr),username,password)
except Exception as e:
logger.error('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 find_torrent(self, hash):
logger.debug('Finding Torrent hash: ' + hash)
torrent_info = self.get_torrent(hash)
if torrent_info:
return True
else:
return False
def get_torrent(self, hash):
logger.debug('Getting Torrent info from hash: ' + hash)
try:
torrent_info = self.client.call('core.get_torrent_status', hash, '')
except Exception as e:
logger.error('Could not get torrent info for ' + hash)
return False
else:
if torrent_info is None:
torrent_info = False
return torrent_info
def start_torrent(self, hash):
try:
self.find_torrent(hash)
except Exception as e:
return False
else:
try:
self.client.call('core.resume_torrent', hash)
except Exception as e:
logger.error('Torrent failed to start ' + e)
else:
logger.info('Torrent ' + hash + ' was started')
return True
def stop_torrent(self, hash):
try:
self.client.find_torrent(hash)
except Exception as e:
logger.error('Torrent Not Found')
return False
else:
try:
self.client.call('core.pause_torrent', hash)
except Exception as e:
logger.error('Torrent failed to be stopped: ' + e)
return False
else:
logger.info('Torrent ' + hash + ' was stopped')
return True
def load_torrent(self, filepath):
logger.info('filepath to torrent file set to : ' + filepath)
torrent_id = False
if self.client.connected is True:
logger.info('Checking if Torrent Exists!')
if not filepath.startswith('magnet'):
torrentcontent = open(filepath, 'rb').read()
hash = str.lower(self.get_the_hash(filepath)) # Deluge expects a lower case hash
logger.debug('Torrent Hash (load_torrent): "' + hash + '"')
logger.debug('FileName (load_torrent): ' + str(os.path.basename(filepath)))
#Check if torrent already added
if self.find_torrent(str.lower(hash)):
#.........这里部分代码省略.........