当前位置: 首页>>代码示例>>Python>>正文


Python DelugeRPCClient.connect方法代码示例

本文整理汇总了Python中deluge_client.DelugeRPCClient.connect方法的典型用法代码示例。如果您正苦于以下问题:Python DelugeRPCClient.connect方法的具体用法?Python DelugeRPCClient.connect怎么用?Python DelugeRPCClient.connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在deluge_client.DelugeRPCClient的用法示例。


在下文中一共展示了DelugeRPCClient.connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import connect [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
开发者ID:dangmai,项目名称:deluge-virtual-dir,代码行数:60,代码来源:main.py

示例2: uploadTorrent

# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import connect [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))
开发者ID:Bilb,项目名称:t411todeluge,代码行数:16,代码来源:t411todeluge.py

示例3: setup_platform

# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import connect [as 别名]
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Deluge switch."""
    from deluge_client import DelugeRPCClient

    name = config.get(CONF_NAME)
    host = config.get(CONF_HOST)
    username = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    port = config.get(CONF_PORT)

    deluge_api = DelugeRPCClient(host, port, username, password)
    try:
        deluge_api.connect()
    except ConnectionRefusedError:
        _LOGGER.error("Connection to Deluge Daemon failed")
        raise PlatformNotReady

    add_entities([DelugeSwitch(deluge_api, name)])
开发者ID:EarthlingRich,项目名称:home-assistant,代码行数:20,代码来源:deluge.py

示例4: torrents_status

# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import connect [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']))
开发者ID:yonatanp,项目名称:controlroom,代码行数:45,代码来源:controlroom.py

示例5: setup_platform

# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import connect [as 别名]
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the Deluge sensors."""
    from deluge_client import DelugeRPCClient

    name = config.get(CONF_NAME)
    host = config.get(CONF_HOST)
    username = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    port = config.get(CONF_PORT)

    deluge_api = DelugeRPCClient(host, port, username, password)
    try:
        deluge_api.connect()
    except ConnectionRefusedError:
        _LOGGER.error("Connection to Deluge Daemon failed")
        raise PlatformNotReady
    dev = []
    for variable in config[CONF_MONITORED_VARIABLES]:
        dev.append(DelugeSensor(variable, deluge_api, name))

    add_devices(dev)
开发者ID:W00D00,项目名称:home-assistant,代码行数:23,代码来源:deluge.py

示例6: connect_to_deluge

# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import connect [as 别名]
def connect_to_deluge():
    client = DelugeRPCClient(config.DLGD_HOST, config.DLGD_PORT, config.DLGD_USER, config.DLGD_PASS)
    client.connect()
    if client.connected: print "Connected to deluge daemon"

    from types import MethodType
    
    def add_torr_url(self, url):
        return self.call('core.add_torrent_url', wz.urls.url_fix(url), {})
    client.add_torr_url = MethodType(add_torr_url, client, DelugeRPCClient)

    def add_torr_file(self, file):
        f = open(file, 'rb')
        filedump = base64.encodestring(f.read())
        f.close()
        return self.call('core.add_torrent_file', file, filedump, {})
    client.add_torr_file = MethodType(add_torr_file, client, DelugeRPCClient)
    
    def add_label(self, label, options={}):
        label = normalize_label(label)
        self.call('label.add', label)
        if options:
            if options['move_completed_path']:
                    options.update({'move_completed': True, 'apply_move_completed': True})
            self.call('label.set_options', label, options)
    client.add_label = MethodType(add_label, client, DelugeRPCClient)
    
    def label_exist(self, label):
        label = normalize_label(label)
        if label in self.list_labels():
            return True
        else:
            return False
    client.label_exist = MethodType(label_exist, client, DelugeRPCClient)            
        
    def list_labels(self):
        return self.call('label.get_labels')
    client.list_labels = MethodType(list_labels, client, DelugeRPCClient)
    
    def add_tor_label(self, tor_id, label):
        return self.call('label.set_torrent', tor_id, normalize_label(label))
    client.add_tor_label = MethodType(add_tor_label, client, DelugeRPCClient)

    def session_state(self):
        return self.call('core.get_session_state')
    client.session_state = MethodType(session_state, client, DelugeRPCClient)
    
    def torrent_status(self, tid, fields = {}):
        return self.call('core.get_torrent_status', tid, fields)
    client.torrent_status = MethodType(torrent_status, client, DelugeRPCClient)

    def torrents_status(self, filters = {}, fields = []):
        return self.call('core.get_torrents_status', filters, fields)
    client.torrents_status = MethodType(torrents_status, client, DelugeRPCClient)
    
    def get_finished(self):
        torrs = torrents_status(self)
        for k,v in torrs.items():
            #print(k,v['name'])
            if v['is_finished'] == False:
                #print("Removing unfinished: " + v['name'] + " " + str(v['is_finished']))
                torrs.pop(k)
            elif v['tracker_host'] in config.REMOVE_SEEDS_EXCEPTION_TRACKERS:
                #print("Removing exception_tracker: " + v['name'])
                torrs.pop(k)
            elif not is_all_files_done(v):
                #print("Removing not_all_done: " + v['name'])
                torrs.pop(k)
        return torrs
    client.get_finished = MethodType(get_finished, client, DelugeRPCClient)
    
    def remove_finished(self):
        for k in get_finished(self):
            self.call('core.remove_torrent', k, False)
    client.remove_finished = MethodType(remove_finished, client, DelugeRPCClient)
    
    def is_all_files_done(tor):
        for i in tor['file_progress']:
            if i != 1.0: 
                return False
        return True

    return client
开发者ID:maziara,项目名称:deluge-feed-inoreader,代码行数:85,代码来源:delugeapi.py

示例7: DelugeClientKORPI

# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import connect [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())
开发者ID:kongzii,项目名称:korpi,代码行数:82,代码来源:torrent_client.py

示例8: DelugeClient

# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import connect [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.
        
#.........这里部分代码省略.........
开发者ID:Hellowlol,项目名称:autotorrent,代码行数:103,代码来源:deluge.py

示例9: len

# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import connect [as 别名]
if len(sys.argv) < 4:
    log.error("Not enough command line parameters present, are you launching this from deluge?")
    sys.exit()

path = str(sys.argv[3])
torrent_name = str(sys.argv[2])
torrent_id = str(sys.argv[1])
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'])
开发者ID:sammys,项目名称:sickbeard_mp4_automator,代码行数:32,代码来源:delugePostProcess.py

示例10: Deluge

# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import connect [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:
#.........这里部分代码省略.........
开发者ID:fmarchenko,项目名称:i3pystatus,代码行数:103,代码来源:deluge.py

示例11: add_torrent

# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import connect [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
开发者ID:yonatanp,项目名称:controlroom,代码行数:8,代码来源:controlroom.py

示例12: main

# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import connect [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")
开发者ID:Mattie432,项目名称:Matts-Scripts,代码行数:82,代码来源:CheckRarAndBlacklist.py

示例13: DelugeClient

# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import connect [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
开发者ID:pombredanne,项目名称:autotorrent,代码行数:66,代码来源:deluge.py

示例14: _mkdtemp

# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import connect [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")
#.........这里部分代码省略.........
开发者ID:opmuse,项目名称:opmuse,代码行数:103,代码来源:deluge.py

示例15: DelugePlugin

# 需要导入模块: from deluge_client import DelugeRPCClient [as 别名]
# 或者: from deluge_client.DelugeRPCClient import connect [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 on_task_abort(self, task, config):
        pass

    def prepare_config(self, config):
        config.setdefault('host', 'localhost')
        config.setdefault('port', 58846)
        return config

    def connect(self):
        """Connects to the deluge daemon and runs on_connect_success """

        self.client.connect()

        if not self.client.connected:
            raise plugin.PluginError('Deluge failed to connect.')

    def disconnect(self):
        self.client.disconnect()

    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
开发者ID:AnthonyGuerreiro,项目名称:Flexget,代码行数:73,代码来源:deluge.py


注:本文中的deluge_client.DelugeRPCClient.connect方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。