Question

Je souhaite (rapidement) assembler un programme / script pour lire l'ensemble de fichiers à partir d'un fichier .torrent. Je souhaite ensuite utiliser ce jeu pour supprimer tous les fichiers d'un répertoire spécifique n'appartenant pas au torrent.

Avez-vous des recommandations sur une bibliothèque pratique pour lire cet index à partir du fichier .torrent? Même si je ne m'y oppose pas, je ne veux pas approfondir les spécifications de BitTorrent et lancer une charge de code à partir de rien dans ce but simple.

Je n'ai pas de préférence sur la langue.

Était-ce utile?

La solution

Vous avez répondu à votre question sur Effbot . Voici le code complet pour lire la liste des fichiers du fichier .torrent (Python 2.4 +):

import re

def tokenize(text, match=re.compile("([idel])|(\d+):|(-?\d+)").match):
    i = 0
    while i < len(text):
        m = match(text, i)
        s = m.group(m.lastindex)
        i = m.end()
        if m.lastindex == 2:
            yield "s"
            yield text[i:i+int(s)]
            i = i + int(s)
        else:
            yield s

def decode_item(next, token):
    if token == "i":
        # integer: "i" value "e"
        data = int(next())
        if next() != "e":
            raise ValueError
    elif token == "s":
        # string: "s" value (virtual tokens)
        data = next()
    elif token == "l" or token == "d":
        # container: "l" (or "d") values "e"
        data = []
        tok = next()
        while tok != "e":
            data.append(decode_item(next, tok))
            tok = next()
        if token == "d":
            data = dict(zip(data[0::2], data[1::2]))
    else:
        raise ValueError
    return data

def decode(text):
    try:
        src = tokenize(text)
        data = decode_item(src.next, src.next())
        for token in src: # look for more tokens
            raise SyntaxError("trailing junk")
    except (AttributeError, ValueError, StopIteration):
        raise SyntaxError("syntax error")
    return data

if __name__ == "__main__":
    data = open("test.torrent", "rb").read()
    torrent = decode(data)
    for file in torrent["info"]["files"]:
        print "%r - %d bytes" % ("/".join(file["path"]), file["length"])

Autres conseils

J'utiliserais la libtorrent de rasterbar, qui est une petite bibliothèque C ++ rapide.
Pour parcourir les fichiers, vous pouvez utiliser la classe torrent_info (begin_files (), end_files ()).

Il existe également une interface python pour libtorrent:

import libtorrent
info = libtorrent.torrent_info('test.torrent')
for f in info.files():
    print "%s - %s" % (f.path, f.size)

bencode.py à partir du client BitTorrent 5.x d'origine Mainline ( http://download.bittorrent.com/dl/BitTorrent-5.2.2.tar.gz ) vous donnerait à peu près l'implémentation de référence en Python.

Il a une dépendance d’importation sur le paquet BTL, mais c’est très facile à enlever. Vous devriez alors regarder bencode.bdecode (filecontent) ['info'] ['fichiers'].

En développant les idées ci-dessus, j’ai fait ce qui suit:

~> cd ~/bin

~/bin> ls torrent*
torrent-parse.py  torrent-parse.sh

~/bin> cat torrent-parse.py
# torrent-parse.py
import sys
import libtorrent

# get the input torrent file
if (len(sys.argv) > 1):
    torrent = sys.argv[1]
else:
    print "Missing param: torrent filename"
    sys.exit()
# get names of files in the torrent file
info = libtorrent.torrent_info(torrent);
for f in info.files():
    print "%s - %s" % (f.path, f.size)

~/bin> cat torrent-parse.sh
#!/bin/bash
if [ $# -lt 1 ]; then
  echo "Missing param: torrent filename"
  exit 0
fi

python torrent-parse.py "$*"

Vous souhaitez définir les autorisations de manière à rendre le script shell exécutable:

~/bin> chmod a+x torrent-parse.sh

J'espère que cela aidera quelqu'un:)

Voici le code de la réponse de Constantine ci-dessus, légèrement modifié pour gérer les caractères Unicode dans les noms de fichiers torrent et les noms de fichiers d'ensembles de fichiers dans les informations torrent:

import re

def tokenize(text, match=re.compile("([idel])|(\d+):|(-?\d+)").match):
    i = 0
    while i < len(text):
        m = match(text, i)
        s = m.group(m.lastindex)
        i = m.end()
        if m.lastindex == 2:
            yield "s"
            yield text[i:i+int(s)]
            i = i + int(s)
        else:
            yield s

def decode_item(next, token):
    if token == "i":
        # integer: "i" value "e"
        data = int(next())
        if next() != "e":
            raise ValueError
    elif token == "s":
        # string: "s" value (virtual tokens)
        data = next()
    elif token == "l" or token == "d":
        # container: "l" (or "d") values "e"
        data = []
        tok = next()
        while tok != "e":
            data.append(decode_item(next, tok))
            tok = next()
        if token == "d":
            data = dict(zip(data[0::2], data[1::2]))
    else:
        raise ValueError
    return data

def decode(text):
    try:
        src = tokenize(text)
        data = decode_item(src.next, src.next())
        for token in src: # look for more tokens
            raise SyntaxError("trailing junk")
    except (AttributeError, ValueError, StopIteration):
        raise SyntaxError("syntax error")
    return data

n = 0
if __name__ == "__main__":
    data = open("C:\\Torrents\\test.torrent", "rb").read()
    torrent = decode(data)
    for file in torrent["info"]["files"]:
        n = n + 1
        filenamepath = file["path"]     
        print str(n) + " -- " + ', '.join(map(str, filenamepath))
        fname = ', '.join(map(str, filenamepath))

        print fname + " -- " + str(file["length"])
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top