Git Product home page Git Product logo

torrentool's Introduction

torrentool

https://github.com/idlesign/torrentool

Description

The tool to work with torrent files.

Works on Python 3.7+.

Includes:

  • Command line interface. Requires click package to be installed.

    Use pip install torrentool[cli] to install this dependency automatically.

  • Torrent utils (file creation, read and modification).

  • Bencoding utils (decoder, encoder).

Using CLI

; Make .torrent out of `video.mkv`
$ torrentool torrent create /home/my/files_here/video.mkv

; Make .torrent out of entire `/home/my/files_here` dir,
; and put some open trackers announce URLs into it,
; and publish file on torrent caching service, so it is ready to share.
$ torrentool torrent create /home/my/files_here --open_trackers --cache

; Print out existing file info.
$ torrentool torrent info /home/my/some.torrent

Use command line --help switch to know more.

Note

Some commands require requests package to be installed.

From your Python code

from torrentool.api import Torrent

# Reading and modifying an existing file.
my_torrent = Torrent.from_file('/home/idle/some.torrent')
my_torrent.total_size  # Total files size in bytes.
my_torrent.magnet_link  # Magnet link for you.
my_torrent.comment = 'Your torrents are mine.'  # Set a comment.
my_torrent.to_file()  # Save changes.

# Or we can create a new torrent from a directory.
new_torrent = Torrent.create_from('/home/idle/my_stuff/')  # or it could have been a single file
new_torrent.announce_urls = 'udp://tracker.openbittorrent.com:80'
new_torrent.to_file('/home/idle/another.torrent')

torrentool's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

torrentool's Issues

Permitions help.

I am learning python, and need a little help.

when i make a torrent in C:, it shows an "PermissionError: [Errno 13] Permission denied:" what can it be?

Also can it create private torrents (disabled DHT)?

Missing properties: "source"

Some properties for example source seems to be missing. source is useful for cross seeding and for some trackers it's a requirement.

Improve bencode speed

https://pypi.org/project/modern-bencode/

decode torrentool_bencode 29.49319815635681 s
decode modern-bencode 13.25705099105835 s

Booth libraries are using pure Python code. Maybe you can improve your performance.

def read_torrentool_bencode(torrent_file):
    metadata = torrentool.bencode.Bencode().decode(torrent_file)
    return metadata

def read_modern_bencode(torrent_file):
    metadata = bencode.decode(torrent_file)
    return metadata

torrent_filepath = "aaa.torrent"
with open(torrent_filepath, 'rb') as inp:
    torrent_file = inp.read()

    start = time.time()
    for i in range(0, 100000):
        metadata = read_torrentool_bencode(torrent_file)
    end = time.time()
    print("read_torrentool_bencode", end - start)

    start = time.time()
    for i in range(0, 100000):
        metadata = read_modern_bencode(torrent_file)
    end = time.time()
    print("read_modern_bencode", end - start)

Some torrent files cannot be read correctly

In my repo, an user is having issue with some of his/her torrent files (link to original issue). I have filtered out files that are causing errors and uploaded them here. These torrent files can be read just fine in qBittorrent (macOS).

The majority of the files throw exceptions when using Torrent.from_file with the exception of file 3.torrent.

` char.ool.exceptions.BencodeDecodingError: Unable to interpret `: file 1, 2, 5
torrentool.exceptions.BencodeDecodingError: Unable to interpret `:` char.: file 4, 6
torrentool.exceptions.BencodeDecodingError: Unable to interpret `` char.: file 7

For file 3.torrent, Torrent.from_file works fine but when I try to read the name property, it throws this error: AttributeError: 'list' object has no attribute 'get'.

source tag is not added to the torrent?

        for t in args.tracker:
            out = os.path.join(output_path, ('[' + t + '] ' + name + ".torrent"))             
            
            if t == args.tracker[0] or len(t) == 1:
                new_torrent = Torrent.create_from(f)
                new_torrent.private = config["private"]
                new_torrent.created_by = 'torrentool'
                               
            new_torrent.source = t
            new_torrent.announce_urls = config["tracker_abbreviations"][t]               
            new_torrent.to_file(out)

Hi there,

Maybe I got something wrong with this snippet here, my goal is to create a torrent for multiple trackers with different passkeys and sources but it seems everything goes well except for the source tag which I cannot see anywhere after opening the torrent with a bencode editor.

The condition is there just so I don't recompute the torrent twice. Thanks again for any info.

EDIT: Seems that adding these 2 functions in torrent.py (copied the logic from the ones for the comment field) makes the magic operate

    @property
    def source(self) -> Optional[str]:
        """Optional. Source Tag."""
        return self._struct.get('source')

    @source.setter
    def source(self, val: str):
        self._struct['info']['source'] = val

It works when I do it like this else, I don't see any other mention of any source tag in the code but my knowledge is average so you never know.

if file name have some strings samewith path, it will be delete

hello
i am using python3.9
i have some files named by '[date] xxxxx,zip'
then, i create torrent by
torrent = Torrent.create_from('/'+ date+ '/')
torrent.to_file('my.torrent')
but i cant hash it with torrent client, then i find all file name in torrent has been
change to '[] xxxxx,zip', 'date' be deleted
i try to use old torrentool, version before 1.1.0 dont have this problem, but folder in torrent named as '_',mabye its problem of python or other requments version?
and, may i create_torrent by an dict?
i want add multi files but i dislike folder in torrent

thank you

Incorrectly parsed Unicode char

This private tracker torrent file has a file path which includes an unicode character that's being incorrectly parsed

\x008D chr(189) Vulgar Fraction One Half

I noticed it because after loading the file with the Torrent class, the calculated info_hash was different from the original torrent.

Screenshots of original torrent file and a new one created with Torrent.to_file from the same data in the hex editor

Original:
Screenshot 2023-09-26 142545

Created with Torrent class
Screenshot 2023-09-26 142612

When using the Bencode class to read and write the torrent, the char is correctly parsed and the hashes match.

Here's a version of the original torrent without the tracker url

431f76f60e05250df162c90a73ab8377dc4ca9c8.zip

screenshot of the terminal output when reading the file with Torrent class (the file name is the correct sha1 hash)
Screenshot 2023-09-26 151205

Can't mix strings and bytes in path components [RUS]

Здравствуйте.
В некоторых торрентах возникает проблема с files.

    log.info('files: {}'.format(t.files))

  File "C:\Users\Alex\AppData\Local\Programs\Python\Python38\lib\site-packages\torrentool\torrent.py", line 96, in files
    files.append(TorrentFile(join(base, *f['path']), f['length']))
  File "C:\Users\Alex\AppData\Local\Programs\Python\Python38\lib\ntpath.py", line 117, in join
    genericpath._check_arg_types('join', path, *paths)
  File "C:\Users\Alex\AppData\Local\Programs\Python\Python38\lib\genericpath.py", line 155, in _check_arg_types
    raise TypeError("Can't mix strings and bytes in path components") from None
TypeError: Can't mix strings and bytes in path components

IndexError on creating torrent from an empty file

using the line myTorrent = Torrent.create_from(activeFile) with activeFile = C:/Users/user/Desktop/test/file2.txt returns:

File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\torrentool\torrent.py", line 410, in create_from
info['length'] = target_files[0][1]
IndexError: list index out of range

Failed to parse torrents with all string values encoded with `encoding`

error code:

Traceback (most recent call last):
  File "...\torrentool-0.2.0\torrentool-0.2.0\Untitled-1.py", line 15, in <module>
    print(torrent.total_size())
  File "...\torrentool-0.2.0\torrentool-0.2.0\torrentool\torrent.py", line 45, in total_size
    return reduce(lambda prev, curr: prev + curr[1], self.files, 0)
  File "...\torrentool-0.2.0\torrentool-0.2.0\torrentool\torrent.py", line 35, in files
    files.append((join(base, *f['path']), f['length']))
  File "...\AppData\Local\Programs\Python\Python35\lib\ntpath.py", line 113, in join
    genericpath._check_arg_types('join', path, *paths)
  File "...\AppData\Local\Programs\Python\Python35\lib\genericpath.py", line 145, in _check_arg_types
    raise TypeError("Can't mix strings and bytes in path components") from None
TypeError: Can't mix strings and bytes in path components

added print code print(type(base), type(*f['path'])) after line 34, it print:

<class 'bytes'> <class 'bytes'>
<class 'bytes'> <class 'str'>

Feature request

This is more a wish list then a feature request, I'm prob gonna send a pr for all them.

  • Support for webseed and http seed
  • Dynamically set a piece size
  • Set max piece size (some torrent sites dont like huge torrents)
  • md5 check sum.
  • allow .api to omitted
  • allow options to set when calling the instance
  • add upload torrent to torrent cache to the torrent class or util

AttributeError when trying to set files property on Torrent object

I am using the torrentool library to read and modify a torrent file in Python. When I try to set the files property of a Torrent object, I get an AttributeError saying that the property has no setter.

Here is my code:

`from torrentool.api import Torrent

Read the original torrent file

original_torrent = Torrent.from_file('test.torrent')

Create a new torrent file with modified files

new_torrent = Torrent()
new_torrent.comment = original_torrent.comment
new_torrent.created_by = original_torrent.created_by
new_torrent.creation_date = original_torrent.creation_date
new_torrent.creation_date = original_torrent.creation_date
new_torrent.files = []

Modify the files

for file in original_torrent.files:
if not file.name.endswith('.srt'):
new_torrent.files.append((file.name, file.size))

Write the new torrent file

new_torrent.to_file('new.torrent')
`

I expect this code to create a new torrent file with the same properties as the original, but with some files removed. However, when I try to set the files property of the new Torrent object, I get an AttributeError saying that the property has no setter.

Please advise on how I can modify the files in the torrent and create a new torrent file with the modified files.

Thank you.

IndexError: pop from empty list

Sometimes when parsing torrent files, an IndexError: pop from empty list error may occur. The torrent file appears to be fine since it can be opened and downloaded normally.
This torrent file cannot be parsed correctly:
88.torrent.zip

Valid torrent file trips up torrentool (and other python torrent libraries)

Hi!

I run riff.cc and we're ingesting 1M+ torrents from archive.org at the moment.

I noticed this torrent:

https://archive.org/details/electricsheep-flock-244-72500-6

causes this error:

DEBUG/opt/radio/collections/ElectricSheep/archive.org/download/electricsheep-flock-244-45000-0/electricsheep-flock-244-45000-0_archive.torrent
Traceback (most recent call last):
  File "/Users/wings/projects/librarian/sizer.py", line 18, in <module>
    torrentstats = Torrent.from_file(os.path.join(path, name))
  File "/opt/homebrew/lib/python3.9/site-packages/torrentool/torrent.py", line 430, in from_file
    torrent = cls(Bencode.read_file(filepath, byte_keys={'pieces'}))
  File "/opt/homebrew/lib/python3.9/site-packages/torrentool/bencode.py", line 206, in read_file
    return cls.decode(contents, byte_keys=byte_keys)
  File "/opt/homebrew/lib/python3.9/site-packages/torrentool/bencode.py", line 167, in decode
    raise BencodeDecodingError(f'Unable to interpret `{char}` char.')
torrentool.exceptions.BencodeDecodingError: Unable to interpret `T` char.

but it's a valid torrent.

condition never meets

Maybe the intended code on line 356 on torrent.py is:
if (size_data>size_max)
because the condition:
if (size_piece>size_max) seems impossible to meet from code above it

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.