when I use python-libtorrent to implement a client I find an example on GitHub
import libtorrent as lt
import time
ses = lt.session()
ses.listen_on(6881, 6891)
e = lt.bdecode(open("test.torrent", 'rb').read())
info = lt.torrent_info(e)
h = ses.add_torrent(info, "d:\\temp")
while (not h.is_seed()):
s = h.status()
state_str = ['queued', 'checking', 'downloading metadata', \
'downloading', 'finished', 'seeding', 'allocating', 'checking fastresume']
print s.download_rate
print '%.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d) %s' % \
(s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000, \
s.num_peers, state_str[s.state])
time.sleep(1)
It works fine. But it will download all the include files
I want ask user to select the files and this client should only download the specific files.
How to ? Thank you.
At first you need to find out which pieces belong to the chosen file/files. In order to do that you first need to find out the index of your file. Doing that is as simple as going through info.files()
i=0
for f in info.files():
if fileIndex == i:
fileStr = f
break
i += 1
You can confirm that's the correct file by printing its path:
print fileStr.path
Now you need to find the file to piece mapping and assign priorities (0 means don't download)
h = ses.add_torrent(info, "d:\\temp")
pr = info.map_file(fileIndex,0,fileStr.size)
n_pieces = pr.length / info.piece_length() + 1
for i in range(info.num_pieces()):
if i in range(pr.piece,pr.piece+n_pieces):
h.piece_priority(i,7)
else:
h.piece_priority(i,0)
Now you can download the files as before. Keep in mind that you now need to stop downloading by checking the progress since you do not enter seed mode as before:
while (not h.is_seed()):
s = h.status()
state_str = ['queued', 'checking', 'downloading metadata', \
'downloading', 'finished', 'seeding', 'allocating', 'checking fastresume']
print s.download_rate
print '%.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d) %s' % \
(s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000, \
s.num_peers, state_str[s.state])
if s.progress>=1:
break
time.sleep(1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With