pythonpython-2.7libtorrentlibtorrent-rasterbar

python libtorrent save_state


I have a problem. I am not a C/C++ programmer and the libtorrent documentation is not really clear to me. There are no docs to find like the python docs for libtorrent.

At this moment i have tried to search stackoverflow for code examples to find out how to use save_state and load_state for a session.

Can anyone give me an example or explain me how i can save the session state and load it later?

The goal is to resume all torrents on process restart.

ses = libtorrent.session()
ses.listen_on(6881, 6891)

if os.path.isfile('./tempfile'):
    with open('./tempfile', 'wb+') as temp_file:
        ses.load_state(
            libtorrent.bdecode(temp_file.read())
        )
 params = {
            'save_path': '/home/downloads/',
            'storage_mode': libtorrent.storage_mode_t(2),
            'paused': False,
            'auto_managed': True,
            'duplicate_is_error': True
        }
        link = "magnet:?xt=urn:btih:4MR6HU7SIHXAXQQFXFJTNLTYSREDR5EI&tr=http://tracker.vodo.net:6970/announce"
        handle = libtorrent.add_magnet_uri(ses, link, params)
        while not handle.has_metadata():
            time.sleep(1)
with open('./tempfile', 'wb+') as temp_file:
    temp_file.write(libtorrent.bencode(ses.save_state()))

update When using save_state_resume() on a torrent handle it also returns none? I found that executing 'pydoc libtorrent > libtorrentDoc.txt' gives me a useful document to browse and search. At this moment i re-add the magnets to the sessions and use the code above.

Maybe someone has a more efficient way?


Solution

  • See: http://www.libtorrent.org/reference-Session.html#save_state_flags_t

    Looks like save_state does not bother with torrents themselves but that is the method for restoring the session state itself.

    I don't know Python but I used a Lua binding of Libtorrent called Luatorrent before and I just stored all torrents in a table/array then on shutdown I would loop through the table/array and get the paused status of each torrent along with relevant statistics then create a save_resume_data() file stop the torrent then end the session.

    With the data I got I would then store a .dat file in AppData that could be loaded again the next time the client was run and that would start what torrents were running and pause ones that were paused and it would have the data for % complete etc.