'Gets called when successfully connected to a daemon.'

def on_connect_success(self, result, task, config):

    from deluge.ui.client import client
    from twisted.internet import reactor, defer
    if (not result):
        log.debug(u'on_connect_success    returned    a    failed    result.    BUG?')
    if task.options.test:
        log.debug(u'Test    connection    to    deluge    daemon    successful.')
        client.disconnect()
        return
    def format_label(label):
        u'Makes    a    string    compliant    with    deluge    label    naming    rules'
        return re.sub(u'[^\\w-]+', u'_', label.lower())
    def set_torrent_options(torrent_id, entry, opts):
        u'Gets    called    when    a    torrent    was    added    to    the    daemon.'
        dlist = []
        if (not torrent_id):
            log.error((u'There    was    an    error    adding    %s    to    deluge.' % entry[u'title']))
            return
        log.info((u'%s    successfully    added    to    deluge.' % entry[u'title']))
        entry[u'deluge_id'] = torrent_id
        def create_path(result, path):
            u'Creates    the    specified    path    if    deluge    is    older    than    1.3'
            from deluge.common import VersionSplit
            if (VersionSplit(u'1.3.0') > VersionSplit(self.deluge_version)):
                if client.is_localhost():
                    if (not os.path.isdir(path)):
                        log.debug((u"path    %s    doesn't    exist,    creating" % path))
                        os.makedirs(path)
                else:
                    log.warning(u'If    path    does    not    exist    on    the    machine    running    the    daemon,    move    will    fail.')
        if opts.get(u'movedone'):
            dlist.append(version_deferred.addCallback(create_path, opts[u'movedone']))
            dlist.append(client.core.set_torrent_move_completed(torrent_id, True))
            dlist.append(client.core.set_torrent_move_completed_path(torrent_id, opts[u'movedone']))
            log.debug((u'%s    move    on    complete    set    to    %s' % (entry[u'title'], opts[u'movedone'])))
        if opts.get(u'label'):
            def apply_label(result, torrent_id, label):
                u'Gets    called    after    labels    and    torrent    were    added    to    deluge.'
                return client.label.set_torrent(torrent_id, label)
            dlist.append(label_deferred.addCallback(apply_label, torrent_id, opts[u'label']))
        if (opts.get(u'queuetotop') is not None):
            if opts[u'queuetotop']:
                dlist.append(client.core.queue_top([torrent_id]))
                log.debug((u'%s    moved    to    top    of    queue' % entry[u'title']))
            else:
                dlist.append(client.core.queue_bottom([torrent_id]))
                log.debug((u'%s    moved    to    bottom    of    queue' % entry[u'title']))
        def on_get_torrent_status(status):
            u'Gets    called    with    torrent    status,    including    file    info.\n                                                                Sets    the    torrent    options    which    require    knowledge    of    the    current    status    of    the    torrent.'
            main_file_dlist = []
            move_now_path = None
            if opts.get(u'movedone'):
                if (status[u'progress'] == 100):
                    move_now_path = opts[u'movedone']
                else:
                    log.debug((u'Not    moving    storage    for    %s,    as    this    will    prevent    movedone.' % entry[u'title']))
            elif opts.get(u'path'):
                move_now_path = opts[u'path']
            if (move_now_path and (os.path.normpath(move_now_path) != os.path.normpath(status[u'save_path']))):
                main_file_dlist.append(version_deferred.addCallback(create_path, move_now_path))
                log.debug((u'Moving    storage    for    %s    to    %s' % (entry[u'title'], move_now_path)))
                main_file_dlist.append(client.core.move_storage([torrent_id], move_now_path))
            big_file_name = u''
            if (opts.get(u'content_filename') or opts.get(u'main_file_only')):
                def file_exists(filename):
                    if os.path.exists(os.path.join(status[u'save_path'], filename)):
                        return True
                    elif (status.get(u'move_on_completed') and status.get(u'move_on_completed_path')):
                        if os.path.exists(os.path.join(status[u'move_on_completed_path'], filename)):
                            return True
                    else:
                        return False
                def unused_name(name):
                    if client.is_localhost():
                        counter = 2
                        while file_exists(name):
                            name = u''.join([os.path.splitext(name)[0], u'    (', str(counter), u')', os.path.splitext(name)[1]])
                            counter += 1
                    else:
                        log.debug(u'Cannot    ensure    content_filename    is    unique    when    adding    to    a    remote    deluge    daemon.')
                    return name
                def rename(file, new_name):
                    main_file_dlist.append(client.core.rename_files(torrent_id, [(file[u'index'], new_name)]))
                    log.debug((u'File    %s    in    %s    renamed    to    %s' % (file[u'path'], entry[u'title'], new_name)))
                main_file = None
                for file in status[u'files']:
                    if (file[u'size'] > (status[u'total_size'] * opts.get(u'main_file_ratio'))):
                        main_file = file
                        break
                if (main_file is not None):
                    keep_subs = opts.get(u'keep_subs')
                    sub_file = None
                    if keep_subs:
                        sub_exts = [u'.srt', u'.sub']
                        for file in status[u'files']:
                            ext = os.path.splitext(file[u'path'])[1]
                            if (ext in sub_exts):
                                sub_file = file
                                break
                    if (os.path.dirname(main_file[u'path']) is not (u'' or u'/')):
                        if (opts.get(u'content_filename') and (os.path.dirname(opts[u'content_filename']) is not u'')):
                            top_files_dir = (os.path.dirname(opts[u'content_filename']) + u'/')
                        else:
                            top_files_dir = (os.path.dirname(main_file[u'path']) + u'/')
                    else:
                        top_files_dir = u'/'
                    if opts.get(u'content_filename'):
                        big_file_name = ((top_files_dir + os.path.basename(opts[u'content_filename'])) + os.path.splitext(main_file[u'path'])[1])
                        big_file_name = unused_name(big_file_name)
                        rename(main_file, big_file_name)
                        if ((sub_file is not None) and keep_subs):
                            sub_file_name = (os.path.splitext(big_file_name)[0] + os.path.splitext(sub_file[u'path'])[1])
                            rename(sub_file, sub_file_name)
                    if opts.get(u'main_file_only'):
                        file_priorities = [(1 if ((f == main_file) or ((f == sub_file) and keep_subs)) else 0) for f in status[u'files']]
                        main_file_dlist.append(client.core.set_torrent_file_priorities(torrent_id, file_priorities))
                        if opts.get(u'hide_sparse_files'):
                            sparse_files = [f for f in status[u'files'] if ((f != main_file) and ((f != sub_file) or (not keep_subs)))]
                            rename_pairs = [(f[u'index'], ((top_files_dir + u'.sparse_files/') + os.path.basename(f[u'path']))) for f in sparse_files]
                            main_file_dlist.append(client.core.rename_files(torrent_id, rename_pairs))
                else:
                    log.warning((u'No    files    in    "%s"    are    >    %d%%    of    content    size,    no    files    renamed.' % (entry[u'title'], (opts.get(u'main_file_ratio') * 100))))
            container_directory = pathscrub(entry.render(entry.get(u'container_directory', config.get(u'container_directory', u''))))
            if container_directory:
                if big_file_name:
                    folder_structure = big_file_name.split(os.sep)
                elif (len(status[u'files']) > 0):
                    folder_structure = status[u'files'][0][u'path'].split(os.sep)
                else:
                    folder_structure = []
                if (len(folder_structure) > 1):
                    log.verbose(u'Renaming    Folder    %s    to    %s', folder_structure[0], container_directory)
                    main_file_dlist.append(client.core.rename_folder(torrent_id, folder_structure[0], container_directory))
                else:
                    log.debug(u'container_directory    specified    however    the    torrent    %s    does    not    have    a    directory    structure;    skipping    folder    rename', entry[u'title'])
            return defer.DeferredList(main_file_dlist)
        status_keys = [u'files', u'total_size', u'save_path', u'move_on_completed_path', u'move_on_completed', u'progress']
        dlist.append(client.core.get_torrent_status(torrent_id, status_keys).addCallback(on_get_torrent_status))
        return defer.DeferredList(dlist)
    def on_fail(result, task, entry):
        u'Gets    called    when    daemon    reports    a    failure    adding    the    torrent.'
        log.info((u'%s    was    not    added    to    deluge!    %s' % (entry[u'title'], result)))
        entry.fail(u'Could    not    be    added    to    deluge')
    dlist = []
    labels = set()
    for entry in task.accepted:
        if entry.get(u'label', config.get(u'label')):
            try:
                label = format_label(entry.render(entry.get(u'label', config.get(u'label'))))
                log.debug(u'Rendered    label:    %s', label)
            except RenderError as e:
                log.error(u'Error    rendering    label    `%s`:    %s', label, e)
                continue
            labels.add(label)
    label_deferred = defer.succeed(True)
    if labels:
        def on_get_enabled_plugins(plugins):
            u'Gets    called    with    the    list    of    enabled    deluge    plugins.'
            def on_label_enabled(result):
                u'    This    runs    when    we    verify    the    label    plugin    is    enabled.    '
                def on_get_labels(d_labels):
                    u'Gets    available    labels    from    deluge,    and    adds    any    new    labels    we    need.'
                    dlist = []
                    for label in labels:
                        if (label not in d_labels):
                            log.debug(u'Adding    the    label    `%s`    to    deluge', label)
                            dlist.append(client.label.add(label))
                    return defer.DeferredList(dlist)
                return client.label.get_labels().addCallback(on_get_labels)
            if (u'Label' in plugins):
                return on_label_enabled(True)
            else:
                def on_get_available_plugins(plugins):
                    u'Gets    plugins    available    to    deluge,    enables    Label    plugin    if    available.'
                    if (u'Label' in plugins):
                        log.debug(u'Enabling    label    plugin    in    deluge')
                        return client.core.enable_plugin(u'Label').addCallback(on_label_enabled)
                    else:
                        log.error(u'Label    plugin    is    not    installed    in    deluge')
                return client.core.get_available_plugins().addCallback(on_get_available_plugins)
        label_deferred = client.core.get_enabled_plugins().addCallback(on_get_enabled_plugins)
        dlist.append(label_deferred)
    def on_get_daemon_info(ver):
        u'Gets    called    with    the    daemon    version    info,    stores    it    in    self.'
        log.debug((u'deluge    version    %s' % ver))
        self.deluge_version = ver
    version_deferred = client.daemon.info().addCallback(on_get_daemon_info)
    dlist.append(version_deferred)
    def on_get_session_state(torrent_ids):
        u'Gets    called    with    a    list    of    torrent_ids    loaded    in    the    deluge    session.\n                                                Adds    new    torrents    and    modifies    the    settings    for    ones    already    in    the    session.'
        dlist = []
        for entry in task.accepted:
            @defer.inlineCallbacks
            def _wait_for_metadata(torrent_id, timeout):
                log.verbose((u'Waiting    %d    seconds    for    "%s"    to    magnetize' % (timeout, entry[u'title'])))
                for _ in range(timeout):
                    time.sleep(1)
                    try:
                        status = (yield client.core.get_torrent_status(torrent_id, [u'files']))
                    except Exception as err:
                        log.error((u'wait_for_metadata    Error:    %s' % err))
                        break
                    if status.get(u'files'):
                        log.info((u'"%s"    magnetization    successful' % entry[u'title']))
                        break
                else:
                    log.warning((u'"%s"    did    not    magnetize    before    the    timeout    elapsed,    file    list    unavailable    for    processing.' % entry[u'title']))
                defer.returnValue(torrent_id)
            def add_entry(entry, opts):
                u'Adds    an    entry    to    the    deluge    session'
                (magnet, filedump) = (None, None)
                if entry.get(u'url', u'').startswith(u'magnet:'):
                    magnet = entry[u'url']
                else:
                    if (not os.path.exists(entry[u'file'])):
                        entry.fail((u"Downloaded    temp    file    '%s'    doesn't    exist!" % entry[u'file']))
                        del entry[u'file']
                        return
                    with open(entry[u'file'], u'rb') as f:
                        filedump = base64.encodestring(f.read())
                log.verbose((u'Adding    %s    to    deluge.' % entry[u'title']))
                if magnet:
                    d = client.core.add_torrent_magnet(magnet, opts)
                    if config.get(u'magnetization_timeout'):
                        d.addCallback(_wait_for_metadata, config[u'magnetization_timeout'])
                    return d
                else:
                    return client.core.add_torrent_file(entry[u'title'], filedump, opts)
            add_opts = {}
            try:
                path = entry.render(entry.get(u'path', config[u'path']))
                if path:
                    add_opts[u'download_location'] = pathscrub(os.path.expanduser(path))
            except RenderError as e:
                log.error((u'Could    not    set    path    for    %s:    %s' % (entry[u'title'], e)))
            for (fopt, dopt) in self.options.items():
                value = entry.get(fopt, config.get(fopt))
                if (value is not None):
                    add_opts[dopt] = value
                    if (fopt == u'ratio'):
                        add_opts[u'stop_at_ratio'] = True
            modify_opts = {u'queuetotop': entry.get(u'queuetotop', config.get(u'queuetotop')), u'main_file_only': entry.get(u'main_file_only', config.get(u'main_file_only', False)), u'main_file_ratio': entry.get(u'main_file_ratio', config.get(u'main_file_ratio')), u'hide_sparse_files': entry.get(u'hide_sparse_files', config.get(u'hide_sparse_files', True)), u'keep_subs': entry.get(u'keep_subs', config.get(u'keep_subs', True))}
            try:
                label = entry.render(entry.get(u'label', config[u'label']))
                modify_opts[u'label'] = format_label(label)
            except RenderError as e:
                log.error(u'Error    setting    label    for    `%s`:    %s', entry[u'title'], e)
            try:
                movedone = entry.render(entry.get(u'movedone', config[u'movedone']))
                modify_opts[u'movedone'] = pathscrub(os.path.expanduser(movedone))
            except RenderError as e:
                log.error((u'Error    setting    movedone    for    %s:    %s' % (entry[u'title'], e)))
            try:
                content_filename = entry.get(u'content_filename', config.get(u'content_filename', u''))
                modify_opts[u'content_filename'] = pathscrub(entry.render(content_filename))
            except RenderError as e:
                log.error((u'Error    setting    content_filename    for    %s:    %s' % (entry[u'title'], e)))
            torrent_id = (entry.get(u'deluge_id') or entry.get(u'torrent_info_hash'))
            torrent_id = (torrent_id and torrent_id.lower())
            if (torrent_id in torrent_ids):
                log.info((u'%s    is    already    loaded    in    deluge,    setting    options' % entry[u'title']))
                modify_opts[u'path'] = add_opts.pop(u'download_location', None)
                dlist.extend([set_torrent_options(torrent_id, entry, modify_opts), client.core.set_torrent_options([torrent_id], add_opts)])
            else:
                dlist.append(add_entry(entry, add_opts).addCallbacks(set_torrent_options, on_fail, callbackArgs=(entry, modify_opts), errbackArgs=(task, entry)))
        return defer.DeferredList(dlist)
    dlist.append(client.core.get_session_state().addCallback(on_get_session_state))
    def on_complete(result):
        u'Gets    called    when    all    of    our    tasks    for    deluge    daemon    are    complete.'
        client.disconnect()
    tasks = defer.DeferredList(dlist).addBoth(on_complete)
    def on_timeout(result):
        u'Gets    called    if    tasks    have    not    completed    in    30    seconds.\n                                                Should    only    happen    when    something    goes    wrong.'
        log.error(u'Timed    out    while    adding    torrents    to    deluge.')
        log.debug((u'dlist:    %s' % result.resultList))
        client.disconnect()
    reactor.callLater(600, (lambda : (tasks.called or on_timeout(tasks))))
