libtorrent icon indicating copy to clipboard operation
libtorrent copied to clipboard

What is the best way to get a torrent name by hash?

Open vmtest439 opened this issue 9 months ago • 2 comments

I'm trying to write a script that can retrieve the name of a corresponding torrent file based on its hash. My current code saves the information to disk before fetching the name. Is there a way to optimize it so that nothing is saved to disk, and the name is directly retrieved and displayed?

My code:

import libtorrent as lt
import time

ses = lt.session()

def hex_to_sha1_hash(hex_hash: str) -> lt.sha1_hash:
    """Convert a hexadecimal string to a SHA-1 hash object"""
    hash_bytes = bytes.fromhex(hex_hash)
    return lt.sha1_hash(hash_bytes)

info_hash = hex_to_sha1_hash('<hash_str>')

magnet_link = f'magnet:?xt=urn:btih:{info_hash.to_bytes().hex()}'

params = {
    'save_path': '.',
    'storage_mode': lt.storage_mode_t.storage_mode_allocate,
}

handle = lt.add_magnet_uri(ses, magnet_link, params)

while not handle.has_metadata():
    time.sleep(1)
print(handle.get_torrent_info().name())

ses.remove_torrent(handle)

vmtest439 avatar Mar 15 '25 04:03 vmtest439

I think you need to add flags:

params = {
    "save_path": "./non-existent-path",
    "storage_mode": lt.storage_mode_t.storage_mode_sparse,
    "flags": lt.torrent_flags.upload_mode
    | lt.torrent_flags.auto_managed
    | lt.torrent_flags.default_dont_download,
}

More here: https://www.libtorrent.org/single-page-ref.html#torrent-flags-t

RomaP13 avatar Mar 17 '25 09:03 RomaP13

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Jul 19 '25 05:07 stale[bot]