Esempio n. 1
0
def resume_data(atp: lt.add_torrent_params) -> bytes:
    if atp.ti is None:
        with ltpy.translate_exceptions():
            return lt.write_resume_data_buf(atp)
    atp = copy(atp)
    atp.ti = None
    with ltpy.translate_exceptions():
        return lt.write_resume_data_buf(atp)
Esempio n. 2
0
def main() -> None:
    parser = optparse.OptionParser()

    parser.add_option("-p", "--port", type="int", help="set listening port")

    parser.add_option(
        "-i",
        "--listen-interface",
        type="string",
        help="set interface for incoming connections",
    )

    parser.add_option(
        "-o",
        "--outgoing-interface",
        type="string",
        help="set interface for outgoing connections",
    )

    parser.add_option(
        "-d",
        "--max-download-rate",
        type="float",
        help="the maximum download rate given in kB/s. 0 means infinite.",
    )

    parser.add_option(
        "-u",
        "--max-upload-rate",
        type="float",
        help="the maximum upload rate given in kB/s. 0 means infinite.",
    )

    parser.add_option(
        "-s",
        "--save-path",
        type="string",
        help="the path where the downloaded file/folder should be placed.",
    )

    parser.add_option(
        "-r",
        "--proxy-host",
        type="string",
        help="sets HTTP proxy host and port (separated by ':')",
    )

    parser.set_defaults(
        port=6881,
        listen_interface="0.0.0.0",
        outgoing_interface="",
        max_download_rate=0,
        max_upload_rate=0,
        save_path=".",
        proxy_host="",
    )

    (options, args) = parser.parse_args()

    if options.port < 0 or options.port > 65525:
        options.port = 6881

    options.max_upload_rate *= 1000
    options.max_download_rate *= 1000

    if options.max_upload_rate <= 0:
        options.max_upload_rate = -1
    if options.max_download_rate <= 0:
        options.max_download_rate = -1

    settings = {
        "user_agent": "python_client/" + lt.__version__,
        "listen_interfaces":
        "%s:%d" % (options.listen_interface, options.port),
        "download_rate_limit": int(options.max_download_rate),
        "upload_rate_limit": int(options.max_upload_rate),
        "alert_mask": lt.alert.category_t.all_categories,
        "outgoing_interfaces": options.outgoing_interface,
    }

    if options.proxy_host != "":
        settings["proxy_hostname"] = options.proxy_host.split(":")[0]
        settings["proxy_type"] = lt.proxy_type_t.http
        settings["proxy_port"] = options.proxy_host.split(":")[1]

    ses = lt.session(settings)

    # map torrent_handle to torrent_status
    torrents: Dict[lt.torrent_handle, lt.torrent_status] = {}
    alerts_log = []

    for filename in args:
        add_torrent(ses, filename, options)

    console: ConsoleType
    if os.name == "nt":
        console = WindowsConsole()
    else:
        console = UnixConsole()

    alive = True
    while alive:
        console.clear()

        out = ""

        for h, t in torrents.items():
            out += "name: %-40s\n" % t.name[:40]

            if t.state != lt.torrent_status.seeding:
                state_str = [
                    "queued",
                    "checking",
                    "downloading metadata",
                    "downloading",
                    "finished",
                    "seeding",
                    "",
                    "checking fastresume",
                ]
                out += state_str[t.state] + " "

                out += "%5.4f%% " % (t.progress * 100)
                out += progress_bar(t.progress, 49)
                out += "\n"

                out += "total downloaded: %d Bytes\n" % t.total_done
                out += "peers: %d seeds: %d distributed copies: %d\n" % (
                    t.num_peers,
                    t.num_seeds,
                    t.distributed_copies,
                )
                out += "\n"

            out += "download: %s/s (%s) " % (
                add_suffix(t.download_rate),
                add_suffix(t.total_download),
            )
            out += "upload: %s/s (%s) " % (
                add_suffix(t.upload_rate),
                add_suffix(t.total_upload),
            )

            if t.state != lt.torrent_status.seeding:
                out += "info-hash: %s\n" % t.info_hashes
                out += "next announce: %s\n" % t.next_announce
                out += "tracker: %s\n" % t.current_tracker

            console.write(out)

            print_peer_info(console, t.handle.get_peer_info())
            print_download_queue(console, t.handle.get_download_queue())

            if t.state != lt.torrent_status.seeding:
                try:
                    out = "\n"
                    fp = h.file_progress()
                    ti = t.torrent_file
                    for idx, p in enumerate(fp):
                        out += progress_bar(
                            p / float(ti.files().file_size(idx)), 20)
                        out += " " + ti.files().file_path(idx) + "\n"
                    console.write(out)
                except Exception:
                    pass

        console.write(76 * "-" + "\n")
        console.write("(q)uit), (p)ause), (u)npause), (r)eannounce\n")
        console.write(76 * "-" + "\n")

        alerts = ses.pop_alerts()
        for a in alerts:
            alerts_log.append(a.message())

            # add new torrents to our list of torrent_status
            if isinstance(a, lt.add_torrent_alert):
                h = a.handle
                h.set_max_connections(60)
                h.set_max_uploads(-1)
                torrents[h] = h.status()

            # update our torrent_status array for torrents that have
            # changed some of their state
            if isinstance(a, lt.state_update_alert):
                for s in a.status:
                    torrents[s.handle] = s

        if len(alerts_log) > 20:
            alerts_log = alerts_log[-20:]

        for a in alerts_log:
            console.write(a + "\n")

        c = console.sleep_and_input(0.5)

        ses.post_torrent_updates()
        if not c:
            continue

        if c == "r":
            for h in torrents:
                h.force_reannounce()
        elif c == "q":
            alive = False
        elif c == "p":
            for h in torrents:
                h.pause()
        elif c == "u":
            for h in torrents:
                h.resume()

    ses.pause()
    for h, t in torrents.items():
        if not h.is_valid() or not t.has_metadata:
            continue
        h.save_resume_data()

    while len(torrents) > 0:
        alerts = ses.pop_alerts()
        for a in alerts:
            if isinstance(a, lt.save_resume_data_alert):
                print(a)
                data = lt.write_resume_data_buf(a.params)
                h = a.handle
                if h in torrents:
                    open(
                        os.path.join(options.save_path,
                                     torrents[h].name + ".fastresume"),
                        "wb",
                    ).write(data)
                    del torrents[h]

            if isinstance(a, lt.save_resume_data_failed_alert):
                h = a.handle
                if h in torrents:
                    print("failed to save resume data for ", torrents[h].name)
                    del torrents[h]
        time.sleep(0.5)
Esempio n. 3
0
def main():
    from optparse import OptionParser

    parser = OptionParser()

    parser.add_option('-p', '--port', type='int', help='set listening port')

    parser.add_option(
        '-i', '--listen-interface', type='string',
        help='set interface for incoming connections', )

    parser.add_option(
        '-o', '--outgoing-interface', type='string',
        help='set interface for outgoing connections')

    parser.add_option(
        '-d', '--max-download-rate', type='float',
        help='the maximum download rate given in kB/s. 0 means infinite.')

    parser.add_option(
        '-u', '--max-upload-rate', type='float',
        help='the maximum upload rate given in kB/s. 0 means infinite.')

    parser.add_option(
        '-s', '--save-path', type='string',
        help='the path where the downloaded file/folder should be placed.')

    parser.add_option(
        '-r', '--proxy-host', type='string',
        help='sets HTTP proxy host and port (separated by \':\')')

    parser.set_defaults(
        port=6881,
        listen_interface='0.0.0.0',
        outgoing_interface='',
        max_download_rate=0,
        max_upload_rate=0,
        save_path='.',
        proxy_host=''
    )

    (options, args) = parser.parse_args()

    if options.port < 0 or options.port > 65525:
        options.port = 6881

    options.max_upload_rate *= 1000
    options.max_download_rate *= 1000

    if options.max_upload_rate <= 0:
        options.max_upload_rate = -1
    if options.max_download_rate <= 0:
        options.max_download_rate = -1

    settings = {
        'user_agent': 'python_client/' + lt.__version__,
        'listen_interfaces': '%s:%d' % (options.listen_interface, options.port),
        'download_rate_limit': int(options.max_download_rate),
        'upload_rate_limit': int(options.max_upload_rate),
        'alert_mask': lt.alert.category_t.all_categories,
        'outgoing_interfaces': options.outgoing_interface,
    }

    if options.proxy_host != '':
        settings['proxy_hostname'] = options.proxy_host.split(':')[0]
        settings['proxy_type'] = lt.proxy_type_t.http
        settings['proxy_port'] = options.proxy_host.split(':')[1]

    ses = lt.session(settings)

    # map torrent_handle to torrent_status
    torrents = {}
    alerts_log = []

    for f in args:
        add_torrent(ses, f, options)

    if os.name == 'nt':
        console = WindowsConsole()
    else:
        console = UnixConsole()

    alive = True
    while alive:
        console.clear()

        out = ''

        for h, t in torrents.items():
            out += 'name: %-40s\n' % t.name[:40]

            if t.state != lt.torrent_status.seeding:
                state_str = ['queued', 'checking', 'downloading metadata',
                             'downloading', 'finished', 'seeding',
                             'allocating', 'checking fastresume']
                out += state_str[t.state] + ' '

                out += '%5.4f%% ' % (t.progress * 100)
                out += progress_bar(t.progress, 49)
                out += '\n'

                out += 'total downloaded: %d Bytes\n' % t.total_done
                out += 'peers: %d seeds: %d distributed copies: %d\n' % \
                    (t.num_peers, t.num_seeds, t.distributed_copies)
                out += '\n'

            out += 'download: %s/s (%s) ' \
                % (add_suffix(t.download_rate), add_suffix(t.total_download))
            out += 'upload: %s/s (%s) ' \
                % (add_suffix(t.upload_rate), add_suffix(t.total_upload))

            if t.state != lt.torrent_status.seeding:
                out += 'info-hash: %s\n' % t.info_hash
                out += 'next announce: %s\n' % t.next_announce
                out += 'tracker: %s\n' % t.current_tracker

            write_line(console, out)

            print_peer_info(console, t.handle.get_peer_info())
            print_download_queue(console, t.handle.get_download_queue())

            if t.state != lt.torrent_status.seeding:
                try:
                    out = '\n'
                    fp = h.file_progress()
                    ti = t.torrent_file
                    for f, p in zip(ti.files(), fp):
                        out += progress_bar(p / float(f.size), 20)
                        out += ' ' + f.path + '\n'
                    write_line(console, out)
                except Exception:
                    pass

        write_line(console, 76 * '-' + '\n')
        write_line(console, '(q)uit), (p)ause), (u)npause), (r)eannounce\n')
        write_line(console, 76 * '-' + '\n')

        alerts = ses.pop_alerts()
        for a in alerts:
            alerts_log.append(a.message())

            # add new torrents to our list of torrent_status
            if isinstance(a, lt.add_torrent_alert):
                h = a.handle
                h.set_max_connections(60)
                h.set_max_uploads(-1)
                torrents[h] = h.status()

            # update our torrent_status array for torrents that have
            # changed some of their state
            if isinstance(a, lt.state_update_alert):
                for s in a.status:
                    torrents[s.handle] = s

        if len(alerts_log) > 20:
            alerts_log = alerts_log[-20:]

        for a in alerts_log:
            write_line(console, a + '\n')

        c = console.sleep_and_input(0.5)

        ses.post_torrent_updates()
        if not c:
            continue

        if c == 'r':
            for h in torrents:
                h.force_reannounce()
        elif c == 'q':
            alive = False
        elif c == 'p':
            for h in torrents:
                h.pause()
        elif c == 'u':
            for h in torrents:
                h.resume()

    ses.pause()
    for h, t in torrents.items():
        if not h.is_valid() or not t.has_metadata:
            continue
        h.save_resume_data()

    while len(torrents) > 0:
        alerts = ses.pop_alerts()
        for a in alerts:
            if isinstance(a, lt.save_resume_data_alert):
                print(a)
                data = lt.write_resume_data_buf(a.params)
                h = a.handle
                if h in torrents:
                    open(os.path.join(options.save_path, torrents[h].name + '.fastresume'), 'wb').write(data)
                    del torrents[h]

            if isinstance(a, lt.save_resume_data_failed_alert):
                h = a.handle
                if h in torrents:
                    print('failed to save resume data for ', torrents[h].name)
                    del torrents[h]
        time.sleep(0.5)
Esempio n. 4
0
def main():
    from optparse import OptionParser

    parser = OptionParser()

    parser.add_option('-p', '--port', type='int', help='set listening port')

    parser.add_option(
        '-i',
        '--listen-interface',
        type='string',
        help='set interface for incoming connections',
    )

    parser.add_option('-o',
                      '--outgoing-interface',
                      type='string',
                      help='set interface for outgoing connections')

    parser.add_option(
        '-d',
        '--max-download-rate',
        type='float',
        help='the maximum download rate given in kB/s. 0 means infinite.')

    parser.add_option(
        '-u',
        '--max-upload-rate',
        type='float',
        help='the maximum upload rate given in kB/s. 0 means infinite.')

    parser.add_option(
        '-s',
        '--save-path',
        type='string',
        help='the path where the downloaded file/folder should be placed.')

    parser.add_option(
        '-r',
        '--proxy-host',
        type='string',
        help='sets HTTP proxy host and port (separated by \':\')')

    parser.set_defaults(port=6881,
                        listen_interface='0.0.0.0',
                        outgoing_interface='',
                        max_download_rate=0,
                        max_upload_rate=0,
                        save_path='.',
                        proxy_host='')

    (options, args) = parser.parse_args()

    if options.port < 0 or options.port > 65525:
        options.port = 6881

    options.max_upload_rate *= 1000
    options.max_download_rate *= 1000

    if options.max_upload_rate <= 0:
        options.max_upload_rate = -1
    if options.max_download_rate <= 0:
        options.max_download_rate = -1

    settings = {
        'user_agent': 'python_client/' + lt.__version__,
        'listen_interfaces':
        '%s:%d' % (options.listen_interface, options.port),
        'download_rate_limit': int(options.max_download_rate),
        'upload_rate_limit': int(options.max_upload_rate),
        'alert_mask': lt.alert.category_t.all_categories,
        'outgoing_interfaces': options.outgoing_interface,
    }

    if options.proxy_host != '':
        settings['proxy_hostname'] = options.proxy_host.split(':')[0]
        settings['proxy_type'] = lt.proxy_type_t.http
        settings['proxy_port'] = options.proxy_host.split(':')[1]

    ses = lt.session(settings)

    # map torrent_handle to torrent_status
    torrents = {}
    alerts_log = []

    for f in args:
        add_torrent(ses, f, options)

    if os.name == 'nt':
        console = WindowsConsole()
    else:
        console = UnixConsole()

    alive = True
    while alive:
        console.clear()

        out = ''

        for h, t in torrents.items():
            out += 'name: %-40s\n' % t.name[:40]

            if t.state != lt.torrent_status.seeding:
                state_str = [
                    'queued', 'checking', 'downloading metadata',
                    'downloading', 'finished', 'seeding', 'allocating',
                    'checking fastresume'
                ]
                out += state_str[t.state] + ' '

                out += '%5.4f%% ' % (t.progress * 100)
                out += progress_bar(t.progress, 49)
                out += '\n'

                out += 'total downloaded: %d Bytes\n' % t.total_done
                out += 'peers: %d seeds: %d distributed copies: %d\n' % \
                    (t.num_peers, t.num_seeds, t.distributed_copies)
                out += '\n'

            out += 'download: %s/s (%s) ' \
                % (add_suffix(t.download_rate), add_suffix(t.total_download))
            out += 'upload: %s/s (%s) ' \
                % (add_suffix(t.upload_rate), add_suffix(t.total_upload))

            if t.state != lt.torrent_status.seeding:
                out += 'info-hash: %s\n' % t.info_hashes
                out += 'next announce: %s\n' % t.next_announce
                out += 'tracker: %s\n' % t.current_tracker

            write_line(console, out)

            print_peer_info(console, t.handle.get_peer_info())
            print_download_queue(console, t.handle.get_download_queue())

            if t.state != lt.torrent_status.seeding:
                try:
                    out = '\n'
                    fp = h.file_progress()
                    ti = t.torrent_file
                    for f, p in zip(ti.files(), fp):
                        out += progress_bar(p / float(f.size), 20)
                        out += ' ' + f.path + '\n'
                    write_line(console, out)
                except Exception:
                    pass

        write_line(console, 76 * '-' + '\n')
        write_line(console, '(q)uit), (p)ause), (u)npause), (r)eannounce\n')
        write_line(console, 76 * '-' + '\n')

        alerts = ses.pop_alerts()
        for a in alerts:
            alerts_log.append(a.message())

            # add new torrents to our list of torrent_status
            if isinstance(a, lt.add_torrent_alert):
                h = a.handle
                h.set_max_connections(60)
                h.set_max_uploads(-1)
                torrents[h] = h.status()

            # update our torrent_status array for torrents that have
            # changed some of their state
            if isinstance(a, lt.state_update_alert):
                for s in a.status:
                    torrents[s.handle] = s

        if len(alerts_log) > 20:
            alerts_log = alerts_log[-20:]

        for a in alerts_log:
            write_line(console, a + '\n')

        c = console.sleep_and_input(0.5)

        ses.post_torrent_updates()
        if not c:
            continue

        if c == 'r':
            for h in torrents:
                h.force_reannounce()
        elif c == 'q':
            alive = False
        elif c == 'p':
            for h in torrents:
                h.pause()
        elif c == 'u':
            for h in torrents:
                h.resume()

    ses.pause()
    for h, t in torrents.items():
        if not h.is_valid() or not t.has_metadata:
            continue
        h.save_resume_data()

    while len(torrents) > 0:
        alerts = ses.pop_alerts()
        for a in alerts:
            if isinstance(a, lt.save_resume_data_alert):
                print(a)
                data = lt.write_resume_data_buf(a.params)
                h = a.handle
                if h in torrents:
                    open(
                        os.path.join(options.save_path,
                                     torrents[h].name + '.fastresume'),
                        'wb').write(data)
                    del torrents[h]

            if isinstance(a, lt.save_resume_data_failed_alert):
                h = a.handle
                if h in torrents:
                    print('failed to save resume data for ', torrents[h].name)
                    del torrents[h]
        time.sleep(0.5)
Esempio n. 5
0
def copy(atp: lt.add_torrent_params) -> lt.add_torrent_params:
    # TODO: use copy constructor when available
    with ltpy.translate_exceptions():
        return lt.read_resume_data(lt.write_resume_data_buf(atp))