1
votes

I have the following code to download a torrent off of a magnet URI.

#python
#lt.storage_mode_t(0) ## tried this, didnt work
ses = lt.session()
params = { 'save_path': "/save/here"}

ses.listen_on(6881,6891)
ses.add_dht_router("router.utorrent.com", 6881)

#ses = lt.session()
link = "magnet:?xt=urn:btih:395603fa..hash..."
handle = lt.add_magnet_uri(ses, link, params)
while (not handle.has_metadata()):
    time.sleep(1)
handle.pause () # got meta data paused, and set priority
handle.file_priority(0, 1)
handle.file_priority(1,0)
handle.file_priority(2,0)
print handle.file_priorities()
#output is [1,0,0]
#i checked no files written into disk yet.
handle.resume()
while (not handle.is_finished()):
    time.sleep(1) #wait until download 

It works, However in this specific torrent, there are 3 files, file 0 - 2 kb, file 1 - 300mb, file 3 - 2kb.

As can be seen from the code, file 0 has a priority of 1, while the rest has priority 0 (i.e. don't download).

The problem is that when the 0 file finishes downloading, i want to it to stop and not download anymore. but it will sometimes download 1 file -partially, sometimes 100mb, or 200mb, sometimes couple kb and sometimes the entire file.

So my question is: How can i make sure only file 0 is downloaded, and not 1 and 2.

EDIT: I added a check for whether i got metadata, then set priority and then resume it, however this still downloads the second file partially.

1

1 Answers

2
votes

The reason this happens is because of the race between adding the torrent (which starts the download) and you setting the file priorities.

To avoid this you can set the file priorities along with adding the torrent, something like this:

p = parse_magnet_uri(link)
p['file_priorities'] = [1, 0, 0]
handle = ses.add_torrent(p)

UPDATE:

You don't need to know the number of files, it's OK to provide file priorities for more files than ends up being in the torrent file. The remaining ones will just be ignored. However, if you don't want to download anything (except for the metadata/.torrent) from the swarm, a better way is to set the flag_upload_mode flag. See documentation.

p = parse_magnet_uri(link)
p['flags'] |= add_torrent_params_flags_t.flag_upload_mode
handle = ses.add_torrent(p)