torram-ng 2.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
torram_ng-2.0.0/NOTICE ADDED
@@ -0,0 +1,12 @@
1
+ torram-ng
2
+ Copyright 2026 Brian K
3
+
4
+ This product includes software originally developed as "torram"
5
+ (formerly "torrent-upstart") by Volodymyr Buell:
6
+
7
+ https://github.com/vbuell/torram
8
+
9
+ The original project was published without a license file. The Apache
10
+ License 2.0 in this repository covers contributions made to this fork.
11
+ See https://github.com/kanya-approve/torram-ng/issues for the tracking
12
+ issue on resolving the upstream licensing status.
@@ -0,0 +1,155 @@
1
+ Metadata-Version: 2.4
2
+ Name: torram-ng
3
+ Version: 2.0.0
4
+ Summary: Recover torrent data by reconstructing files from fully and partially downloaded sources
5
+ Keywords: torrent,bittorrent,recovery,data-recovery,salvage
6
+ Author: Brian K
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ License-File: NOTICE
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: End Users/Desktop
13
+ Classifier: Intended Audience :: System Administrators
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Topic :: Communications :: File Sharing
18
+ Classifier: Topic :: System :: Archiving
19
+ Classifier: Topic :: System :: Recovery Tools
20
+ Requires-Dist: bencode-py>=4.0
21
+ Maintainer: Brian K
22
+ Requires-Python: >=3.8
23
+ Project-URL: Homepage, https://github.com/kanya-approve/torram-ng
24
+ Project-URL: Repository, https://github.com/kanya-approve/torram-ng
25
+ Project-URL: Issues, https://github.com/kanya-approve/torram-ng/issues
26
+ Description-Content-Type: text/markdown
27
+
28
+ # torram-ng
29
+
30
+ Recover torrent data by reconstructing files from fully and partially downloaded sources.
31
+
32
+ Given a `.torrent` file and one or more directories containing incomplete copies of its
33
+ contents, torram-ng identifies which pieces are intact by checking them against the piece
34
+ hashes in the torrent, and rebuilds the most complete output it can from what it finds.
35
+
36
+ If you have two dead torrents of the same release — one 75% done, the other 85% — the pieces
37
+ you are missing from one may be present in the other. Combined, they can add up to a complete
38
+ file.
39
+
40
+ > **Status: early.** This is a modernization of the unmaintained
41
+ > [`vbuell/torram`](https://github.com/vbuell/torram). This release makes the project
42
+ > installable, tested and continuously integrated; **the recovery engine itself is still the
43
+ > original 0.9.0 code and has known correctness defects.** Read
44
+ > [Known limitations](#known-limitations) before trusting it with anything you care about.
45
+
46
+ ## Install
47
+
48
+ ```sh
49
+ uv tool install git+https://github.com/kanya-approve/torram-ng
50
+ ```
51
+
52
+ Or run it once without installing:
53
+
54
+ ```sh
55
+ uvx --from git+https://github.com/kanya-approve/torram-ng torram-ng --help
56
+ ```
57
+
58
+ Both `torram-ng` and `torram` are installed as commands. Python 3.8 or newer.
59
+
60
+ ## Usage
61
+
62
+ ```
63
+ torram-ng [-h] [--symlink] [--minsize MINSIZE] [-v] [-o OUTPUT_DIR] [-a]
64
+ [-c] [-s] [--fileext FILE_EXT] [--version]
65
+ torrentFile root
66
+ ```
67
+
68
+ | Argument | Meaning |
69
+ |---|---|
70
+ | `torrentFile` | the `.torrent` to analyze |
71
+ | `root` | directory to search recursively for candidate files |
72
+ | `-o`, `--output_dir` | where to write recovered files (**required in practice**, see limitations) |
73
+ | `--minsize` | smallest file size to consider, in bytes. Defaults to 1 MiB, which silently excludes smaller files — pass `--minsize 0` |
74
+ | `-s`, `--autoskip` | skip prompting when there is only one option; `-ss` automates further |
75
+ | `-v`, `--verbose` | repeat for more detail (`-vv`, `-vvv`) |
76
+ | `-c`, `--use_color` | ANSI colour output |
77
+ | `--fileext` | suffix to append to output files, e.g. `.!qB` for incomplete qBittorrent files |
78
+
79
+ Example — scan two drives and rebuild into `./recovered`:
80
+
81
+ ```sh
82
+ torram-ng show.torrent /mnt/disk1 -o ./recovered --minsize 0 -ss
83
+ ```
84
+
85
+ After recovery, run a **force recheck** in your torrent client so it notices the files changed.
86
+
87
+ ## How it works
88
+
89
+ A torrent describes its contents as one continuous byte stream, split into fixed-size pieces.
90
+ Each piece has a **SHA-1** hash stored in the `.torrent`. torram-ng walks the search directory,
91
+ picks out files whose size matches a file in the torrent, and hashes their pieces to find which
92
+ ones are intact. Where several sources each hold different good pieces, it can combine them.
93
+
94
+ ## Known limitations
95
+
96
+ These are inherited from the original implementation and are tracked as
97
+ [issues](https://github.com/kanya-approve/torram-ng/issues). The most significant:
98
+
99
+ - **Pieces spanning file boundaries never verify.** In a multi-file torrent, a piece that
100
+ straddles two files is read from only the first one, so it always fails. Even a perfect,
101
+ complete source reports missing pieces. ([#3](https://github.com/kanya-approve/torram-ng/issues/3))
102
+ - **Files with no attributable piece default to being skipped.** A file that fits entirely
103
+ inside a piece beginning in an earlier file gets no piece assigned to it, so it is reported
104
+ `[0 of 0] (Bad)` and the suggested action is Skip. Interactively you can override this by
105
+ choosing a candidate number; under `-s`/`-ss` it is dropped without prompting. On a real
106
+ torrent this is not rare — 7 of the 12 files in Big Buck Bunny are affected.
107
+ ([#3](https://github.com/kanya-approve/torram-ng/issues/3),
108
+ [#11](https://github.com/kanya-approve/torram-ng/issues/11))
109
+ - **The merge path writes pieces at incorrect offsets** and never verifies the result, so
110
+ combining sources can produce a corrupt file that reports success.
111
+ ([#1](https://github.com/kanya-approve/torram-ng/issues/1))
112
+ - **Scanning several drives can lose candidates**, because hardlink de-duplication keys on the
113
+ inode number without the device. ([#6](https://github.com/kanya-approve/torram-ng/issues/6))
114
+ - **`--minsize` defaults to 1 MiB**, so small-file torrents recover nothing unless you pass
115
+ `--minsize 0`. ([#14](https://github.com/kanya-approve/torram-ng/issues/14))
116
+ - **`--symlink` does nothing** — it is parsed but never implemented.
117
+ ([#17](https://github.com/kanya-approve/torram-ng/issues/17))
118
+ - **`-a` / `--autodetect_output_dir` cannot work**; it needs PyQt4, which has no Python 3 build.
119
+ ([#18](https://github.com/kanya-approve/torram-ng/issues/18))
120
+ - **Performance does not scale.** The verification loop is roughly
121
+ `candidates × pieces × files`, so large or many-file torrents are impractically slow.
122
+ ([#21](https://github.com/kanya-approve/torram-ng/issues/21))
123
+ - Only BitTorrent v1 is supported. v2 and hybrid torrents are untested.
124
+
125
+ A [rewrite of the core](https://github.com/kanya-approve/torram-ng/issues/28) around a global
126
+ piece model is planned; it addresses most of the above structurally rather than one at a time.
127
+
128
+ The tool only ever reads from the directories you point it at, and writes solely to the output
129
+ directory. It does not modify your sources.
130
+
131
+ ## Development
132
+
133
+ ```sh
134
+ uv sync --all-groups
135
+ uv run pytest
136
+ uv run ruff check
137
+ uv run ruff format --check
138
+ ```
139
+
140
+ Tests generate their own torrents and content deterministically, so nothing large is committed.
141
+ Two real torrents are included as parse-only fixtures — see [`tests/data/README.md`](tests/data/README.md).
142
+
143
+ Known bugs are covered by `xfail(strict=True)` tests referencing their issue number. They keep
144
+ CI green while documenting each defect as executable behaviour; when one is fixed its test
145
+ starts failing, which is the signal to remove the marker.
146
+
147
+ ## Credits
148
+
149
+ Originally written by Volodymyr Buell as
150
+ [torram](https://github.com/vbuell/torram) (formerly torrent-upstart). See [NOTICE](NOTICE).
151
+
152
+ ## License
153
+
154
+ [Apache-2.0](LICENSE). Note that the upstream project was published without a license; see
155
+ [#29](https://github.com/kanya-approve/torram-ng/issues/29).
@@ -0,0 +1,128 @@
1
+ # torram-ng
2
+
3
+ Recover torrent data by reconstructing files from fully and partially downloaded sources.
4
+
5
+ Given a `.torrent` file and one or more directories containing incomplete copies of its
6
+ contents, torram-ng identifies which pieces are intact by checking them against the piece
7
+ hashes in the torrent, and rebuilds the most complete output it can from what it finds.
8
+
9
+ If you have two dead torrents of the same release — one 75% done, the other 85% — the pieces
10
+ you are missing from one may be present in the other. Combined, they can add up to a complete
11
+ file.
12
+
13
+ > **Status: early.** This is a modernization of the unmaintained
14
+ > [`vbuell/torram`](https://github.com/vbuell/torram). This release makes the project
15
+ > installable, tested and continuously integrated; **the recovery engine itself is still the
16
+ > original 0.9.0 code and has known correctness defects.** Read
17
+ > [Known limitations](#known-limitations) before trusting it with anything you care about.
18
+
19
+ ## Install
20
+
21
+ ```sh
22
+ uv tool install git+https://github.com/kanya-approve/torram-ng
23
+ ```
24
+
25
+ Or run it once without installing:
26
+
27
+ ```sh
28
+ uvx --from git+https://github.com/kanya-approve/torram-ng torram-ng --help
29
+ ```
30
+
31
+ Both `torram-ng` and `torram` are installed as commands. Python 3.8 or newer.
32
+
33
+ ## Usage
34
+
35
+ ```
36
+ torram-ng [-h] [--symlink] [--minsize MINSIZE] [-v] [-o OUTPUT_DIR] [-a]
37
+ [-c] [-s] [--fileext FILE_EXT] [--version]
38
+ torrentFile root
39
+ ```
40
+
41
+ | Argument | Meaning |
42
+ |---|---|
43
+ | `torrentFile` | the `.torrent` to analyze |
44
+ | `root` | directory to search recursively for candidate files |
45
+ | `-o`, `--output_dir` | where to write recovered files (**required in practice**, see limitations) |
46
+ | `--minsize` | smallest file size to consider, in bytes. Defaults to 1 MiB, which silently excludes smaller files — pass `--minsize 0` |
47
+ | `-s`, `--autoskip` | skip prompting when there is only one option; `-ss` automates further |
48
+ | `-v`, `--verbose` | repeat for more detail (`-vv`, `-vvv`) |
49
+ | `-c`, `--use_color` | ANSI colour output |
50
+ | `--fileext` | suffix to append to output files, e.g. `.!qB` for incomplete qBittorrent files |
51
+
52
+ Example — scan two drives and rebuild into `./recovered`:
53
+
54
+ ```sh
55
+ torram-ng show.torrent /mnt/disk1 -o ./recovered --minsize 0 -ss
56
+ ```
57
+
58
+ After recovery, run a **force recheck** in your torrent client so it notices the files changed.
59
+
60
+ ## How it works
61
+
62
+ A torrent describes its contents as one continuous byte stream, split into fixed-size pieces.
63
+ Each piece has a **SHA-1** hash stored in the `.torrent`. torram-ng walks the search directory,
64
+ picks out files whose size matches a file in the torrent, and hashes their pieces to find which
65
+ ones are intact. Where several sources each hold different good pieces, it can combine them.
66
+
67
+ ## Known limitations
68
+
69
+ These are inherited from the original implementation and are tracked as
70
+ [issues](https://github.com/kanya-approve/torram-ng/issues). The most significant:
71
+
72
+ - **Pieces spanning file boundaries never verify.** In a multi-file torrent, a piece that
73
+ straddles two files is read from only the first one, so it always fails. Even a perfect,
74
+ complete source reports missing pieces. ([#3](https://github.com/kanya-approve/torram-ng/issues/3))
75
+ - **Files with no attributable piece default to being skipped.** A file that fits entirely
76
+ inside a piece beginning in an earlier file gets no piece assigned to it, so it is reported
77
+ `[0 of 0] (Bad)` and the suggested action is Skip. Interactively you can override this by
78
+ choosing a candidate number; under `-s`/`-ss` it is dropped without prompting. On a real
79
+ torrent this is not rare — 7 of the 12 files in Big Buck Bunny are affected.
80
+ ([#3](https://github.com/kanya-approve/torram-ng/issues/3),
81
+ [#11](https://github.com/kanya-approve/torram-ng/issues/11))
82
+ - **The merge path writes pieces at incorrect offsets** and never verifies the result, so
83
+ combining sources can produce a corrupt file that reports success.
84
+ ([#1](https://github.com/kanya-approve/torram-ng/issues/1))
85
+ - **Scanning several drives can lose candidates**, because hardlink de-duplication keys on the
86
+ inode number without the device. ([#6](https://github.com/kanya-approve/torram-ng/issues/6))
87
+ - **`--minsize` defaults to 1 MiB**, so small-file torrents recover nothing unless you pass
88
+ `--minsize 0`. ([#14](https://github.com/kanya-approve/torram-ng/issues/14))
89
+ - **`--symlink` does nothing** — it is parsed but never implemented.
90
+ ([#17](https://github.com/kanya-approve/torram-ng/issues/17))
91
+ - **`-a` / `--autodetect_output_dir` cannot work**; it needs PyQt4, which has no Python 3 build.
92
+ ([#18](https://github.com/kanya-approve/torram-ng/issues/18))
93
+ - **Performance does not scale.** The verification loop is roughly
94
+ `candidates × pieces × files`, so large or many-file torrents are impractically slow.
95
+ ([#21](https://github.com/kanya-approve/torram-ng/issues/21))
96
+ - Only BitTorrent v1 is supported. v2 and hybrid torrents are untested.
97
+
98
+ A [rewrite of the core](https://github.com/kanya-approve/torram-ng/issues/28) around a global
99
+ piece model is planned; it addresses most of the above structurally rather than one at a time.
100
+
101
+ The tool only ever reads from the directories you point it at, and writes solely to the output
102
+ directory. It does not modify your sources.
103
+
104
+ ## Development
105
+
106
+ ```sh
107
+ uv sync --all-groups
108
+ uv run pytest
109
+ uv run ruff check
110
+ uv run ruff format --check
111
+ ```
112
+
113
+ Tests generate their own torrents and content deterministically, so nothing large is committed.
114
+ Two real torrents are included as parse-only fixtures — see [`tests/data/README.md`](tests/data/README.md).
115
+
116
+ Known bugs are covered by `xfail(strict=True)` tests referencing their issue number. They keep
117
+ CI green while documenting each defect as executable behaviour; when one is fixed its test
118
+ starts failing, which is the signal to remove the marker.
119
+
120
+ ## Credits
121
+
122
+ Originally written by Volodymyr Buell as
123
+ [torram](https://github.com/vbuell/torram) (formerly torrent-upstart). See [NOTICE](NOTICE).
124
+
125
+ ## License
126
+
127
+ [Apache-2.0](LICENSE). Note that the upstream project was published without a license; see
128
+ [#29](https://github.com/kanya-approve/torram-ng/issues/29).
@@ -0,0 +1,89 @@
1
+ [build-system]
2
+ requires = ["uv_build>=0.12,<0.13"]
3
+ build-backend = "uv_build"
4
+
5
+ [project]
6
+ name = "torram-ng"
7
+ version = "2.0.0"
8
+ description = "Recover torrent data by reconstructing files from fully and partially downloaded sources"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = "Apache-2.0"
12
+ license-files = [
13
+ "LICENSE",
14
+ "NOTICE",
15
+ ]
16
+ keywords = [
17
+ "torrent",
18
+ "bittorrent",
19
+ "recovery",
20
+ "data-recovery",
21
+ "salvage",
22
+ ]
23
+ classifiers = [
24
+ "Development Status :: 3 - Alpha",
25
+ "Environment :: Console",
26
+ "Intended Audience :: End Users/Desktop",
27
+ "Intended Audience :: System Administrators",
28
+ "Operating System :: OS Independent",
29
+ "Programming Language :: Python :: 3",
30
+ "Programming Language :: Python :: 3 :: Only",
31
+ "Topic :: Communications :: File Sharing",
32
+ "Topic :: System :: Archiving",
33
+ "Topic :: System :: Recovery Tools",
34
+ ]
35
+ dependencies = ["bencode.py>=4.0"]
36
+
37
+ [[project.authors]]
38
+ name = "Brian K"
39
+
40
+ [[project.maintainers]]
41
+ name = "Brian K"
42
+
43
+ [project.urls]
44
+ Homepage = "https://github.com/kanya-approve/torram-ng"
45
+ Repository = "https://github.com/kanya-approve/torram-ng"
46
+ Issues = "https://github.com/kanya-approve/torram-ng/issues"
47
+
48
+ [project.scripts]
49
+ torram-ng = "torram_ng.cli:main"
50
+ torram = "torram_ng.cli:main"
51
+
52
+ [dependency-groups]
53
+ dev = [
54
+ "pytest>=8.0",
55
+ "ruff>=0.6",
56
+ ]
57
+
58
+ [tool.uv.build-backend]
59
+ module-name = "torram_ng"
60
+ module-root = "src"
61
+
62
+ [tool.pytest.ini_options]
63
+ minversion = "8.0"
64
+ testpaths = ["tests"]
65
+ addopts = "-ra --strict-markers --strict-config -m 'not network'"
66
+ xfail_strict = true
67
+ markers = ["network: fetches real torrent content over HTTPS; deselected by default, run with -m network"]
68
+
69
+ [tool.ruff]
70
+ target-version = "py38"
71
+ line-length = 120
72
+ src = [
73
+ "src",
74
+ "tests",
75
+ ]
76
+ extend-exclude = ["src/torram_ng/cli.py"]
77
+
78
+ [tool.ruff.lint]
79
+ select = [
80
+ "E",
81
+ "F",
82
+ "W",
83
+ "I",
84
+ "UP",
85
+ "B",
86
+ "C4",
87
+ "PIE",
88
+ "RUF",
89
+ ]
@@ -0,0 +1,65 @@
1
+ [build-system]
2
+ requires = ["uv_build>=0.12,<0.13"]
3
+ build-backend = "uv_build"
4
+
5
+ [project]
6
+ name = "torram-ng"
7
+ version = "2.0.0"
8
+ description = "Recover torrent data by reconstructing files from fully and partially downloaded sources"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE", "NOTICE"]
13
+ authors = [{ name = "Brian K" }]
14
+ maintainers = [{ name = "Brian K" }]
15
+ keywords = ["torrent", "bittorrent", "recovery", "data-recovery", "salvage"]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Environment :: Console",
19
+ "Intended Audience :: End Users/Desktop",
20
+ "Intended Audience :: System Administrators",
21
+ "Operating System :: OS Independent",
22
+ "Programming Language :: Python :: 3",
23
+ "Programming Language :: Python :: 3 :: Only",
24
+ "Topic :: Communications :: File Sharing",
25
+ "Topic :: System :: Archiving",
26
+ "Topic :: System :: Recovery Tools",
27
+ ]
28
+ dependencies = ["bencode.py>=4.0"]
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/kanya-approve/torram-ng"
32
+ Repository = "https://github.com/kanya-approve/torram-ng"
33
+ Issues = "https://github.com/kanya-approve/torram-ng/issues"
34
+
35
+ [project.scripts]
36
+ torram-ng = "torram_ng.cli:main"
37
+ torram = "torram_ng.cli:main"
38
+
39
+ [dependency-groups]
40
+ dev = ["pytest>=8.0", "ruff>=0.6"]
41
+
42
+ [tool.uv.build-backend]
43
+ module-name = "torram_ng"
44
+ module-root = "src"
45
+
46
+ [tool.pytest.ini_options]
47
+ minversion = "8.0"
48
+ testpaths = ["tests"]
49
+ addopts = "-ra --strict-markers --strict-config -m 'not network'"
50
+ xfail_strict = true
51
+ markers = [
52
+ "network: fetches real torrent content over HTTPS; deselected by default, run with -m network",
53
+ ]
54
+
55
+ [tool.ruff]
56
+ target-version = "py38"
57
+ line-length = 120
58
+ src = ["src", "tests"]
59
+ # cli.py is the original torram 0.9.0 script, vendored near-verbatim so the diff
60
+ # against upstream stays reviewable. Its defects are tracked as issues and will be
61
+ # resolved by the rewrite, not by lint churn. Excluded from both lint and format.
62
+ extend-exclude = ["src/torram_ng/cli.py"]
63
+
64
+ [tool.ruff.lint]
65
+ select = ["E", "F", "W", "I", "UP", "B", "C4", "PIE", "RUF"]
@@ -0,0 +1,10 @@
1
+ """torram-ng: recover torrent data from fully and partially downloaded files."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ try:
6
+ __version__ = version("torram-ng")
7
+ except PackageNotFoundError: # running from a source tree without an install
8
+ __version__ = "0+unknown"
9
+
10
+ __all__ = ["__version__"]
@@ -0,0 +1,410 @@
1
+ import functools
2
+ import hashlib
3
+ import io
4
+ import os
5
+ import re
6
+ import shutil
7
+ import stat
8
+ import sys
9
+ import tempfile
10
+ import bencode
11
+
12
+ from torram_ng import __version__ as VERSION
13
+
14
+
15
+ DELUGE_DIR = '~/.config/deluge/state'
16
+ QBITTORRENT_RESUME_CONF = '~/.config/qBittorrent/qBittorrent-resume.conf'
17
+ FILES_DIR = '~'
18
+ MINIMUM_FILESIZE_TO_SEARCH = 1024 * 1024
19
+
20
+
21
+ class AnsiFormatter(object):
22
+ aaa = {'RED': "\033[31m",
23
+ 'BOLD': "\033[1m",
24
+ 'YELLOW': "\033[33m",
25
+ 'INVERT': "\033[40m\033[37m",
26
+ 'GREEN': "\033[32m",
27
+ 'BLUE': "\033[34m",
28
+ 'BLACK2': "\033[90m",
29
+ 'BLACK1': "\033[37m",
30
+ 'BLACK0': "\033[97m",
31
+ }
32
+
33
+ def format(self, txt, *code):
34
+ return ''.join([self.aaa[c] for c in code]) + txt + "\033[0m"
35
+
36
+
37
+ class BaseFormatter(object):
38
+ def format(self, txt, *code):
39
+ return txt
40
+
41
+
42
+ fmt = BaseFormatter()
43
+ args = None
44
+
45
+
46
+ class FileInfo():
47
+ def __init__(self):
48
+ self.start_offset = None
49
+ self.isOriginal = False
50
+ self.isHardlink = False
51
+
52
+
53
+ def suggest_method(file_infos):
54
+ fullest_file_idx = None
55
+ fullest_file_rate = 0
56
+ downladed_file_rate = 0
57
+ mixed_pieces = []
58
+
59
+ # calculate per file
60
+ for idx, file_info in enumerate(file_infos):
61
+ if len(file_info.chunks) == 0:
62
+ return 'S'
63
+ num_of_success = file_info.num_of_good_chunks
64
+ rate = float(num_of_success) / len(file_info.chunks)
65
+ if file_info.isOriginal:
66
+ downladed_file_rate = rate
67
+ if rate > fullest_file_rate:
68
+ fullest_file_rate = rate
69
+ fullest_file_idx = idx
70
+
71
+ # calculate mixed
72
+ if len(file_infos) > 1:
73
+ for aa in zip(*[fi.chunks for fi in file_infos]):
74
+ # print aa, type(aa), any(aa)
75
+ mixed_pieces.append(any(aa))
76
+ num_of_success = functools.reduce(lambda x, y: x + int(y), mixed_pieces, 0)
77
+
78
+ if float(num_of_success) / len(mixed_pieces) > fullest_file_rate:
79
+ pattern = 'Got [{0} of {1} good pieces from {2} files.'
80
+ print(fmt.format(pattern.format(num_of_success, len(mixed_pieces), len(file_infos)), 'RED', 'BOLD'))
81
+ return 'M'
82
+
83
+ if downladed_file_rate >= fullest_file_rate:
84
+ return 'S'
85
+ return str(fullest_file_idx)
86
+
87
+
88
+ def get_similatity_rate_and_color(success_blocks, all_blocks):
89
+ if all_blocks == 0:
90
+ return 'BLACK2', 'Bad'
91
+
92
+ rate = float(success_blocks) / all_blocks
93
+ if rate > 0.9:
94
+ return 'GREEN', 'Excellent'
95
+ if rate > 0.5:
96
+ return 'YELLOW', 'Good'
97
+ if rate > 0.01:
98
+ return 'YELLOW', 'Poor'
99
+ else:
100
+ return 'BLACK2', 'Bad'
101
+
102
+
103
+ def get_file_sizes(info):
104
+ global args
105
+ if 'files' in info: # yield pieces from a multi-file torrent
106
+ return [fi['length'] for fi in info['files'] if fi['length'] > int(args.minsize)]
107
+ else: # yield pieces from a single file torrent
108
+ return [info['length']]
109
+
110
+
111
+ def get_possible_files(rootdir, sizes):
112
+ """Find duplicate files in directory tree."""
113
+ filesizes = {}
114
+ # Build up dict with key as filesize and value is list of filenames.
115
+ for path, dirs, files in os.walk(rootdir):
116
+ for filename in files:
117
+ filepath = os.path.join(path, filename)
118
+ filesize = os.lstat(filepath).st_size
119
+ if args.verbose >= 2:
120
+ print("File registered: %s (%d bytes)" % (filepath, filesize))
121
+ if filesize in sizes:
122
+ filesizes.setdefault(filesize, []).append(filepath)
123
+ return filesizes
124
+
125
+
126
+ def remove_hard_links(files):
127
+ inode_to_filename = {}
128
+ for filename in files:
129
+ stat_info = os.stat(filename)
130
+ inode_to_filename[stat_info[stat.ST_INO]] = filename
131
+ return inode_to_filename.values()
132
+
133
+
134
+ def load_qbittorrent_conf(hash):
135
+ """Load qBittorrent settings."""
136
+ from PyQt4 import QtCore
137
+
138
+ settings = QtCore.QSettings(os.path.expanduser(QBITTORRENT_RESUME_CONF), QtCore.QSettings.IniFormat)
139
+
140
+ root = settings.value('torrents').toPyObject()
141
+ record = root[QtCore.QString(hash)]
142
+ path = record[QtCore.QString('save_path')]
143
+
144
+ if isinstance(path, QtCore.QString):
145
+ path = str(path)
146
+
147
+ return path
148
+
149
+
150
+ def check_file_chunk(hash, offset, length, filename):
151
+ with open(filename, "rb") as sfile:
152
+ sfile.seek(offset)
153
+ piece = sfile.read(length)
154
+
155
+ piece_hash = hashlib.sha1(piece).digest()
156
+ return piece_hash == hash
157
+
158
+
159
+ def get_chunk(filesizes, global_offset):
160
+ """
161
+ Returns file offset using global continuous file
162
+
163
+ >>> get_chunk([], 0)
164
+ (0, 0)
165
+ >>> get_chunk([100], 0)
166
+ (0, 0)
167
+ >>> get_chunk([100], 100)
168
+ (0, 0)
169
+ >>> get_chunk([50,50,30], 100)
170
+ (2, 0)
171
+ """
172
+ file_offset = 0
173
+ file_idx = 0
174
+
175
+ # Find file idx
176
+ for filesize in filesizes:
177
+ if file_offset + filesize > global_offset:
178
+ break
179
+
180
+ file_offset += filesize
181
+ file_idx += 1
182
+
183
+ return (file_idx, global_offset - file_offset)
184
+
185
+
186
+ def construct_file(file_infos, piece_length, dest_filename):
187
+ # TODO: Get biggest file
188
+ max_num_of_good_chunks = max(fi.num_of_good_chunks for fi in file_infos)
189
+ biggest_file = next(fi for fi in file_infos if fi.num_of_good_chunks == max_num_of_good_chunks)
190
+
191
+ f = tempfile.NamedTemporaryFile(mode='w+b', delete=False)
192
+ file_name = f.name
193
+ print("Temporary file:", file_name)
194
+ f.close()
195
+ print("Copy file: ", biggest_file.path)
196
+ shutil.copy(biggest_file.path, f.name)
197
+
198
+ if len(file_infos) > 1:
199
+ with open(file_name, 'r+b') as f:
200
+ for chunk_idx, chunks_merged in enumerate(zip(*[fi.chunks for fi in file_infos])):
201
+ for i, p in enumerate(chunks_merged):
202
+ if p:
203
+ # copy chunk from and to (file_offset, piece_length)
204
+ file_info = file_infos[i]
205
+ src = open(file_info.path, 'rb')
206
+ src.seek(file_info.start_offset + chunk_idx * piece_length)
207
+ f.seek(file_info.start_offset + chunk_idx * piece_length)
208
+ f.write(src.read(piece_length))
209
+ src.close()
210
+ break
211
+
212
+ print("Move temporary file to ", dest_filename)
213
+ shutil.move(file_name, dest_filename)
214
+
215
+
216
+ def ensure_dir_exists(f):
217
+ d = os.path.dirname(f)
218
+ if not os.path.exists(d):
219
+ os.makedirs(d)
220
+
221
+
222
+ def guess_file(file_info, file_idx, files, pieces, piece_length, files_sizes_array, basedir):
223
+ global args
224
+ global fmt
225
+ global save_path
226
+
227
+ if 'path' in file_info:
228
+ file_name = os.path.join(*file_info['path'])
229
+ else:
230
+ file_name = file_info['name']
231
+
232
+ file_length = file_info['length']
233
+ destination_path = os.path.join(save_path, basedir, file_name)
234
+
235
+ if file_length in files:
236
+ print("Processing file: " + fmt.format(str(file_name), 'BLUE', 'BOLD'))
237
+ file_infos = []
238
+
239
+ add_incomplete_file_with_different_size(destination_path, files[file_length])
240
+
241
+ if args.autoskip and len(files[file_length]) < 2 and \
242
+ max(file.startswith(destination_path) for file in files[file_length]):
243
+ print("Only one file found. Thus, skipping...")
244
+ return
245
+
246
+ uniq_filenames = remove_hard_links(files[file_length])
247
+
248
+ for file_number, file in enumerate(files[file_length]):
249
+ file_info = FileInfo()
250
+ file_info.path = file
251
+
252
+ if file.startswith(destination_path):
253
+ number_to_show = ' * '
254
+ file_info.isOriginal = True
255
+ else:
256
+ number_to_show = ' ' + str(file_number) + ' '
257
+ if file in uniq_filenames:
258
+ pieces.seek(0)
259
+ sys.stdout.write(fmt.format(number_to_show, 'BLACK0', 'BOLD') + str(file))
260
+
261
+ num_of_checks = 0
262
+ num_of_successes = 0
263
+ offset = 0
264
+ pieces_list = []
265
+ while True:
266
+ hash = pieces.read(20)
267
+ if not hash:
268
+ break
269
+ idx, file_offset = get_chunk(files_sizes_array, offset * piece_length)
270
+ if not file_info.start_offset:
271
+ file_info.start_offset = file_offset
272
+
273
+ if idx == file_idx:
274
+ num_of_checks += 1
275
+ hash_result = check_file_chunk(hash, file_offset, piece_length, file)
276
+ pieces_list.append(hash_result)
277
+ if hash_result:
278
+ num_of_successes += 1
279
+
280
+ offset += 1
281
+
282
+ file_info.chunks = pieces_list
283
+ file_info.num_of_good_chunks = num_of_successes
284
+ file_infos.append(file_info)
285
+
286
+ color_code, result_message = get_similatity_rate_and_color(num_of_successes, num_of_checks)
287
+ pattern = ' [{0} of {1}] ({2})'
288
+ print(fmt.format(pattern.format(num_of_successes, num_of_checks, result_message), color_code))
289
+ else:
290
+ sys.stdout.write(fmt.format(number_to_show, 'BLACK0', 'BOLD') + str(file) + " hardlink -> skipped\n")
291
+
292
+ suggestion = suggest_method(file_infos)
293
+ while True:
294
+ user_input = ''
295
+ if args.autoskip < 2 and not (suggestion == 'S' and args.autoskip > 0):
296
+ user_input = input(fmt.format('Choose file number or [S]kip/co[M]bine/[A]uto [<N>/S/M/A] ({0}) '.format(suggestion), 'INVERT'))
297
+
298
+ if user_input == '':
299
+ user_input = suggestion
300
+ if re.match('^[0-9]+$', user_input):
301
+ src_path = file_infos[int(user_input)].path
302
+ print('Copying:', destination_path, src_path)
303
+ ensure_dir_exists(destination_path)
304
+ shutil.copyfile(src_path, destination_path + args.file_ext)
305
+ break
306
+ elif user_input.upper() == 'M':
307
+ print('Creating mixed file from multiple sources')
308
+ ensure_dir_exists(destination_path)
309
+ construct_file(file_infos, piece_length, destination_path + args.file_ext)
310
+ break
311
+ elif user_input.upper() == 'S':
312
+ print('Skipping...')
313
+ break
314
+ elif user_input.upper() == 'A':
315
+ print('Autoselect default option')
316
+ args.autoskip = 2
317
+ else:
318
+ print('Mmmm?')
319
+
320
+ else:
321
+ if args.verbose > 0:
322
+ print("Skipping file: %s (%d bytes)" % (file_name, file_length))
323
+
324
+
325
+ def add_incomplete_file_with_different_size(filepath, list):
326
+ if os.path.exists(filepath):
327
+ for filename in os.listdir(os.path.dirname(filepath)):
328
+ curr_filepath = os.path.join(os.path.dirname(filepath), filename)
329
+ if curr_filepath.startswith(filepath):
330
+ if curr_filepath not in list:
331
+ list.append(curr_filepath)
332
+
333
+
334
+ def run():
335
+ global args
336
+ global save_path
337
+
338
+ # Open torrent file
339
+ torrent_file = open(args.torrentfile, "rb")
340
+ metainfo = bencode.bdecode(torrent_file.read())
341
+ info = metainfo['info']
342
+ pieces = io.BytesIO(info['pieces'])
343
+
344
+ hash = hashlib.sha1(bencode.bencode(info)).hexdigest()
345
+ print("Hash:", hash)
346
+
347
+ sizes = get_file_sizes(info)
348
+ print('Sizes', sizes)
349
+
350
+ if args.autodetect_output_dir:
351
+ save_path = load_qbittorrent_conf(hash)
352
+ print(save_path)
353
+ else:
354
+ save_path = args.output_dir
355
+
356
+ # Get possible files
357
+ print('Searching for file pretenders...')
358
+ files = get_possible_files(os.path.expanduser(args.root), sizes)
359
+
360
+ # Check files one by one
361
+ if 'files' in info:
362
+ files_sizes_array = [f['length'] for f in info['files']]
363
+ file_idx = 0
364
+ for f in info['files']:
365
+ guess_file(f, file_idx, files, pieces, info['piece length'], files_sizes_array, info['name'])
366
+ file_idx += 1
367
+ else:
368
+ files_sizes_array = [info['length']]
369
+ guess_file(info, 0, files, pieces, info['piece length'], files_sizes_array, '')
370
+
371
+
372
+ def main(argv=None):
373
+ global args
374
+ global fmt
375
+
376
+ from argparse import ArgumentParser
377
+
378
+ parser = ArgumentParser(prog='torram-ng', description='Recreate download directory for .torrent file from fully and partially downloaded file(s).')
379
+ parser.add_argument('torrentfile', metavar='torrentFile', help='.torrent file to analyze')
380
+ parser.add_argument('root', metavar='root', help='Directory to recursively search files in')
381
+ parser.add_argument('--symlink', action='store_true',
382
+ help='Use symlinks instead of copying files. '
383
+ '(Caution: You may lose your data if files are not actually identical.)')
384
+ parser.add_argument('--minsize', default=MINIMUM_FILESIZE_TO_SEARCH,
385
+ help='Minimum file size in bytes to be recoverable. Default: ' + str(MINIMUM_FILESIZE_TO_SEARCH))
386
+ parser.add_argument('-v', '--verbose', action='count', default=0,
387
+ help='Be verbose (multiple levels: use -vv or -vvv to see more)')
388
+ parser.add_argument('-o', '--output_dir', dest='output_dir',
389
+ help='Output directory where to place recreated files')
390
+ parser.add_argument('-a', '--autodetect_output_dir', dest='autodetect_output_dir', action='store_true',
391
+ help='Autodetect output directory (only qBittorrent currently supported)')
392
+ parser.add_argument('-c', '--use_color', dest='use_color', action='store_true', help='Output format: [ansi, ascii]')
393
+ parser.add_argument('-s', '--autoskip', dest='autoskip', action='count', default=0,
394
+ help='Dont ask questions if there is only one viable choice. Use -ss to behave even more automated')
395
+ parser.add_argument('--fileext', dest='file_ext', default='',
396
+ help='Extension to be added to output files (ex, .!qB for incomplete qBittorrent files)')
397
+ parser.add_argument('--version', action='version', version=VERSION)
398
+ args = parser.parse_args(argv)
399
+
400
+ if args.use_color:
401
+ fmt = AnsiFormatter()
402
+ else:
403
+ fmt = BaseFormatter()
404
+
405
+ run()
406
+ return 0
407
+
408
+
409
+ if __name__ == "__main__":
410
+ sys.exit(main())