├── requirements.txt ├── dottorrent ├── version.py ├── exceptions.py └── __init__.py ├── .vscode └── settings.json ├── docs ├── install.rst ├── library.rst ├── index.rst ├── changelog.rst ├── Makefile ├── make.bat └── conf.py ├── README.rst ├── LICENSE ├── setup.py └── .gitignore /requirements.txt: -------------------------------------------------------------------------------- 1 | bencoder.pyx>=2.0.0 2 | -------------------------------------------------------------------------------- /dottorrent/version.py: -------------------------------------------------------------------------------- 1 | __version__ = '1.10.1' 2 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.linting.pylintEnabled": false 3 | } -------------------------------------------------------------------------------- /docs/install.rst: -------------------------------------------------------------------------------- 1 | Installation 2 | ============ 3 | 4 | Requirements 5 | ------------ 6 | 7 | * Python 3.3+ (Python 3.5+ recommended) 8 | * See ``requirements.txt`` for additional dependencies. 9 | 10 | Stable releases are available on PyPI and can be installed using ``pip``. 11 | :: 12 | 13 | pip install dottorrent 14 | 15 | To install from the latest development sources, clone the git repo and run 16 | ``pip install .`` 17 | -------------------------------------------------------------------------------- /docs/library.rst: -------------------------------------------------------------------------------- 1 | Library 2 | ======= 3 | 4 | The dottorrent library can be used in a Python script or program to create .torrent files. 5 | 6 | .. autoclass:: dottorrent.Torrent 7 | :members: 8 | :undoc-members: 9 | 10 | Example Usage 11 | ------------- 12 | :: 13 | 14 | from dottorrent import Torrent 15 | 16 | t = Torrent('/my/data/', trackers=['http://tracker.openbittorrent.com:80/announce']) 17 | t.generate() 18 | with open('mydata.torrent', 'wb') as f: 19 | t.save(f) -------------------------------------------------------------------------------- /dottorrent/exceptions.py: -------------------------------------------------------------------------------- 1 | class EmptyInputException(Exception): 2 | 3 | def __init__(self, *args, **kwargs): 4 | super().__init__('Input path must be non-empty') 5 | 6 | 7 | class InvalidInputException(Exception): 8 | 9 | def __init__(self, *args, **kwargs): 10 | super().__init__('Input path is invalid') 11 | 12 | 13 | class InvalidURLException(Exception): 14 | 15 | def __init__(self, url, *args, **kwargs): 16 | super().__init__("{} is not a valid URL".format(url)) 17 | 18 | 19 | class InvalidPieceSizeException(Exception): 20 | 21 | def __init__(self, *args, **kwargs): 22 | super().__init__(*args, **kwargs) 23 | 24 | 25 | class TorrentNotGeneratedException(Exception): 26 | 27 | def __init__(self, *args, **kwargs): 28 | super().__init__('Torrent not generated - call generate() first') 29 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | dottorrent 2 | ========== 3 | 4 | High-level Python 3 library for creating .torrent files 5 | 6 | Documentation 7 | ------------- 8 | 9 | Full documentation on how to use dottorrent 10 | is available at `dottorrent.readthedocs.io `_. 11 | 12 | .. image:: https://readthedocs.org/projects/dottorrent/badge/ 13 | 14 | 15 | Installation 16 | ------------ 17 | 18 | Stable releases are available on PyPI and can be installed using ``pip``. 19 | :: 20 | 21 | pip install dottorrent 22 | 23 | 24 | To install from the latest development sources, clone the git repo and run 25 | ``pip install .`` 26 | 27 | CLI and GUI 28 | ----------- 29 | 30 | Looking for a command-line interface? Check out `dottorrent-cli `_. 31 | 32 | Looking for a GUI? Check out `dottorrent-gui `_. 33 | 34 | License 35 | ------- 36 | 37 | `MIT `_ 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Kevin Zhang 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. dottorrent documentation master file, created by 2 | sphinx-quickstart on Sun Aug 21 22:54:46 2016. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to dottorrent's documentation! 7 | ====================================== 8 | 9 | **dottorrent** is a high-level Python 3 library for creating .torrent files. 10 | 11 | Features 12 | -------- 13 | 14 | * Fast (capable of several hundred MB/s) 15 | * Full Unicode support 16 | * Automatic and manual piece size selection 17 | * HTTP/web seeds support `(BEP 19) `_ 18 | * Private flag support `(BEP 27) `_ 19 | * Source string support 20 | * Info hash generation for created torrents 21 | * User-definable comment field, creation date, creator, etc. 22 | * Filename pattern exclusion 23 | * Per-file MD5 hash inclusion 24 | 25 | 26 | 27 | Contents: 28 | 29 | .. toctree:: 30 | :maxdepth: 3 31 | 32 | install 33 | library 34 | changelog 35 | 36 | 37 | Indices and tables 38 | ================== 39 | 40 | * :ref:`genindex` 41 | * :ref:`modindex` 42 | * :ref:`search` 43 | 44 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | with open('dottorrent/version.py') as f: 4 | exec(f.read()) 5 | 6 | setup( 7 | name="dottorrent", 8 | version=__version__, 9 | packages=find_packages(), 10 | 11 | # Project uses reStructuredText, so ensure that the docutils get 12 | # installed or upgraded on the target machine 13 | install_requires=['bencoder.pyx>=2.0.0'], 14 | 15 | # metadata for upload to PyPI 16 | author="Kevin Zhang", 17 | author_email="kevin@kevinzhang.me", 18 | description="High-level Python 3 library for creating .torrent files", 19 | long_description=open('README.rst').read(), 20 | keywords="bittorrent torrent bencode", 21 | url="https://github.com/kz26/dottorrent", # project home page, if any 22 | 23 | # could also include long_description, download_url, classifiers, etc. 24 | classifiers=[ 25 | 'Development Status :: 5 - Production/Stable', 26 | 'Intended Audience :: Developers', 27 | 'License :: OSI Approved :: MIT License', 28 | 'Programming Language :: Python :: 3.3', 29 | 'Programming Language :: Python :: 3.4', 30 | 'Programming Language :: Python :: 3.5', 31 | 'Programming Language :: Python :: 3.6' 32 | ] 33 | ) 34 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | -------------------------------------------------------------------------------- /docs/changelog.rst: -------------------------------------------------------------------------------- 1 | Changelog 2 | ========= 3 | 4 | 1.10.1 5 | ------ 6 | * Bump bencoder.pyx dependency to v2.0.0 7 | 8 | 1.10.0 9 | ------ 10 | * Expose torrent data dictionary as a public property 11 | * Refactor dottorrent CLI into its own package 12 | 13 | 1.9.2 14 | ----- 15 | * Always set announce key, even for multi-tracker torrents (https://github.com/kz26/dottorrent-gui/issues/15) 16 | 17 | 1.9.1 18 | ----- 19 | * Fix unreferenced piece size error in CLI 20 | 21 | 1.9.0 22 | ----- 23 | * Increase MAX_PIECE_SIZE to 64 MiB 24 | * Minor docstring improvements 25 | 26 | 1.8.0 27 | ----- 28 | * Human-friendly piece size specification in CLI 29 | * Minor string formatting improvements 30 | 31 | 1.7.0 32 | ----- 33 | * Implement filename pattern exclusion from PR #7 (--exclude, -x) 34 | 35 | 1.6.0 36 | ----- 37 | * Add support for source strings (--source option) 38 | * Exclude hidden dotfiles from being added 39 | * Exclude hidden files on Windows (requires Python 3.5+) 40 | * Refactor - CLI tool is now simply `dottorrent` 41 | 42 | 1.5.3 43 | ----- 44 | * Use relative paths instead of absolute paths for directory mode path generation 45 | * Add invalid input path check in get_info() and generate() 46 | 47 | 1.5.2 48 | ----- 49 | * Use humanfriendly.format_size in binary mode 50 | * Pin major versions of dependencies in requirements.txt and setup.py 51 | 52 | 1.5.1 53 | ----- 54 | * Fix filename clobbering when filename contains parent path string (issue #2) 55 | 56 | 1.5.0 57 | ----- 58 | * Allow both file and directory names to be specified for output_path (PR #1, @mahkitah) 59 | 60 | 1.4.3 61 | ----- 62 | * dottorrent_cli: Change output_path to output_file for clarity 63 | 64 | 1.4.2 65 | ----- 66 | * Rename dottorrent_cli.py to dottorrent_cli 67 | 68 | 1.4.1 69 | ----- 70 | * Ignore empty files in get_info() and generate() 71 | 72 | 1.4.0 73 | ----- 74 | * Use custom exceptions (see exceptions.py) 75 | * Add check for empty input 76 | 77 | 1.3.0 78 | ----- 79 | * Unicode support 80 | 81 | 1.2.2 82 | ----- 83 | * Fix auto piece sizing in generate() with small files 84 | 85 | 1.2.0 86 | ----- 87 | * Switch to BEP 19 (GetRight style) web seeds 88 | 89 | 1.1.1 90 | ----- 91 | * Return True/False in generate() 92 | 93 | 1.1.0 94 | ----- 95 | * Move include_md5 option to Torrent constructor 96 | * Add cancellation functionality to generate function via existing callback 97 | * get_info() now always scans/rescans the input path instead of checking for cached data 98 | * Documentation improvements 99 | 100 | 1.0.2 101 | ----- 102 | * Raise exception when path is a directory and no files exist 103 | 104 | 1.0.1 105 | ----- 106 | * Change bencoder.pyx minimum version dependency to 1.1.1 107 | * Add none/now to CLI date option 108 | * Minor tweaks 109 | 110 | 111 | 1.0.0 112 | ----- 113 | * Initial release. 114 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 14 | # the i18n builder cannot share the environment and doctrees with the others 15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 16 | 17 | .PHONY: help 18 | help: 19 | @echo "Please use \`make ' where is one of" 20 | @echo " html to make standalone HTML files" 21 | @echo " dirhtml to make HTML files named index.html in directories" 22 | @echo " singlehtml to make a single large HTML file" 23 | @echo " pickle to make pickle files" 24 | @echo " json to make JSON files" 25 | @echo " htmlhelp to make HTML files and a HTML help project" 26 | @echo " qthelp to make HTML files and a qthelp project" 27 | @echo " applehelp to make an Apple Help Book" 28 | @echo " devhelp to make HTML files and a Devhelp project" 29 | @echo " epub to make an epub" 30 | @echo " epub3 to make an epub3" 31 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 32 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 33 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 34 | @echo " text to make text files" 35 | @echo " man to make manual pages" 36 | @echo " texinfo to make Texinfo files" 37 | @echo " info to make Texinfo files and run them through makeinfo" 38 | @echo " gettext to make PO message catalogs" 39 | @echo " changes to make an overview of all changed/added/deprecated items" 40 | @echo " xml to make Docutils-native XML files" 41 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 42 | @echo " linkcheck to check all external links for integrity" 43 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 44 | @echo " coverage to run coverage check of the documentation (if enabled)" 45 | @echo " dummy to check syntax errors of document sources" 46 | 47 | .PHONY: clean 48 | clean: 49 | rm -rf $(BUILDDIR)/* 50 | 51 | .PHONY: html 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | .PHONY: dirhtml 58 | dirhtml: 59 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 60 | @echo 61 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 62 | 63 | .PHONY: singlehtml 64 | singlehtml: 65 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 66 | @echo 67 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 68 | 69 | .PHONY: pickle 70 | pickle: 71 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 72 | @echo 73 | @echo "Build finished; now you can process the pickle files." 74 | 75 | .PHONY: json 76 | json: 77 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 78 | @echo 79 | @echo "Build finished; now you can process the JSON files." 80 | 81 | .PHONY: htmlhelp 82 | htmlhelp: 83 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 84 | @echo 85 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 86 | ".hhp project file in $(BUILDDIR)/htmlhelp." 87 | 88 | .PHONY: qthelp 89 | qthelp: 90 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 91 | @echo 92 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 93 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 94 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/dottorrent.qhcp" 95 | @echo "To view the help file:" 96 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/dottorrent.qhc" 97 | 98 | .PHONY: applehelp 99 | applehelp: 100 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 101 | @echo 102 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 103 | @echo "N.B. You won't be able to view it unless you put it in" \ 104 | "~/Library/Documentation/Help or install it in your application" \ 105 | "bundle." 106 | 107 | .PHONY: devhelp 108 | devhelp: 109 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 110 | @echo 111 | @echo "Build finished." 112 | @echo "To view the help file:" 113 | @echo "# mkdir -p $$HOME/.local/share/devhelp/dottorrent" 114 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/dottorrent" 115 | @echo "# devhelp" 116 | 117 | .PHONY: epub 118 | epub: 119 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 120 | @echo 121 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 122 | 123 | .PHONY: epub3 124 | epub3: 125 | $(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3 126 | @echo 127 | @echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3." 128 | 129 | .PHONY: latex 130 | latex: 131 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 132 | @echo 133 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 134 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 135 | "(use \`make latexpdf' here to do that automatically)." 136 | 137 | .PHONY: latexpdf 138 | latexpdf: 139 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 140 | @echo "Running LaTeX files through pdflatex..." 141 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 142 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 143 | 144 | .PHONY: latexpdfja 145 | latexpdfja: 146 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 147 | @echo "Running LaTeX files through platex and dvipdfmx..." 148 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 149 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 150 | 151 | .PHONY: text 152 | text: 153 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 154 | @echo 155 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 156 | 157 | .PHONY: man 158 | man: 159 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 160 | @echo 161 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 162 | 163 | .PHONY: texinfo 164 | texinfo: 165 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 166 | @echo 167 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 168 | @echo "Run \`make' in that directory to run these through makeinfo" \ 169 | "(use \`make info' here to do that automatically)." 170 | 171 | .PHONY: info 172 | info: 173 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 174 | @echo "Running Texinfo files through makeinfo..." 175 | make -C $(BUILDDIR)/texinfo info 176 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 177 | 178 | .PHONY: gettext 179 | gettext: 180 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 181 | @echo 182 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 183 | 184 | .PHONY: changes 185 | changes: 186 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 187 | @echo 188 | @echo "The overview file is in $(BUILDDIR)/changes." 189 | 190 | .PHONY: linkcheck 191 | linkcheck: 192 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 193 | @echo 194 | @echo "Link check complete; look for any errors in the above output " \ 195 | "or in $(BUILDDIR)/linkcheck/output.txt." 196 | 197 | .PHONY: doctest 198 | doctest: 199 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 200 | @echo "Testing of doctests in the sources finished, look at the " \ 201 | "results in $(BUILDDIR)/doctest/output.txt." 202 | 203 | .PHONY: coverage 204 | coverage: 205 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 206 | @echo "Testing of coverage in the sources finished, look at the " \ 207 | "results in $(BUILDDIR)/coverage/python.txt." 208 | 209 | .PHONY: xml 210 | xml: 211 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 212 | @echo 213 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 214 | 215 | .PHONY: pseudoxml 216 | pseudoxml: 217 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 218 | @echo 219 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 220 | 221 | .PHONY: dummy 222 | dummy: 223 | $(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy 224 | @echo 225 | @echo "Build finished. Dummy builder generates no files." 226 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. epub3 to make an epub3 31 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 32 | echo. text to make text files 33 | echo. man to make manual pages 34 | echo. texinfo to make Texinfo files 35 | echo. gettext to make PO message catalogs 36 | echo. changes to make an overview over all changed/added/deprecated items 37 | echo. xml to make Docutils-native XML files 38 | echo. pseudoxml to make pseudoxml-XML files for display purposes 39 | echo. linkcheck to check all external links for integrity 40 | echo. doctest to run all doctests embedded in the documentation if enabled 41 | echo. coverage to run coverage check of the documentation if enabled 42 | echo. dummy to check syntax errors of document sources 43 | goto end 44 | ) 45 | 46 | if "%1" == "clean" ( 47 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 48 | del /q /s %BUILDDIR%\* 49 | goto end 50 | ) 51 | 52 | 53 | REM Check if sphinx-build is available and fallback to Python version if any 54 | %SPHINXBUILD% 1>NUL 2>NUL 55 | if errorlevel 9009 goto sphinx_python 56 | goto sphinx_ok 57 | 58 | :sphinx_python 59 | 60 | set SPHINXBUILD=python -m sphinx.__init__ 61 | %SPHINXBUILD% 2> nul 62 | if errorlevel 9009 ( 63 | echo. 64 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 65 | echo.installed, then set the SPHINXBUILD environment variable to point 66 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 67 | echo.may add the Sphinx directory to PATH. 68 | echo. 69 | echo.If you don't have Sphinx installed, grab it from 70 | echo.http://sphinx-doc.org/ 71 | exit /b 1 72 | ) 73 | 74 | :sphinx_ok 75 | 76 | 77 | if "%1" == "html" ( 78 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 79 | if errorlevel 1 exit /b 1 80 | echo. 81 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 82 | goto end 83 | ) 84 | 85 | if "%1" == "dirhtml" ( 86 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 87 | if errorlevel 1 exit /b 1 88 | echo. 89 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 90 | goto end 91 | ) 92 | 93 | if "%1" == "singlehtml" ( 94 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 95 | if errorlevel 1 exit /b 1 96 | echo. 97 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 98 | goto end 99 | ) 100 | 101 | if "%1" == "pickle" ( 102 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 103 | if errorlevel 1 exit /b 1 104 | echo. 105 | echo.Build finished; now you can process the pickle files. 106 | goto end 107 | ) 108 | 109 | if "%1" == "json" ( 110 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 111 | if errorlevel 1 exit /b 1 112 | echo. 113 | echo.Build finished; now you can process the JSON files. 114 | goto end 115 | ) 116 | 117 | if "%1" == "htmlhelp" ( 118 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 119 | if errorlevel 1 exit /b 1 120 | echo. 121 | echo.Build finished; now you can run HTML Help Workshop with the ^ 122 | .hhp project file in %BUILDDIR%/htmlhelp. 123 | goto end 124 | ) 125 | 126 | if "%1" == "qthelp" ( 127 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 128 | if errorlevel 1 exit /b 1 129 | echo. 130 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 131 | .qhcp project file in %BUILDDIR%/qthelp, like this: 132 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\dottorrent.qhcp 133 | echo.To view the help file: 134 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\dottorrent.ghc 135 | goto end 136 | ) 137 | 138 | if "%1" == "devhelp" ( 139 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 140 | if errorlevel 1 exit /b 1 141 | echo. 142 | echo.Build finished. 143 | goto end 144 | ) 145 | 146 | if "%1" == "epub" ( 147 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 148 | if errorlevel 1 exit /b 1 149 | echo. 150 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 151 | goto end 152 | ) 153 | 154 | if "%1" == "epub3" ( 155 | %SPHINXBUILD% -b epub3 %ALLSPHINXOPTS% %BUILDDIR%/epub3 156 | if errorlevel 1 exit /b 1 157 | echo. 158 | echo.Build finished. The epub3 file is in %BUILDDIR%/epub3. 159 | goto end 160 | ) 161 | 162 | if "%1" == "latex" ( 163 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 164 | if errorlevel 1 exit /b 1 165 | echo. 166 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 167 | goto end 168 | ) 169 | 170 | if "%1" == "latexpdf" ( 171 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 172 | cd %BUILDDIR%/latex 173 | make all-pdf 174 | cd %~dp0 175 | echo. 176 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 177 | goto end 178 | ) 179 | 180 | if "%1" == "latexpdfja" ( 181 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 182 | cd %BUILDDIR%/latex 183 | make all-pdf-ja 184 | cd %~dp0 185 | echo. 186 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 187 | goto end 188 | ) 189 | 190 | if "%1" == "text" ( 191 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 192 | if errorlevel 1 exit /b 1 193 | echo. 194 | echo.Build finished. The text files are in %BUILDDIR%/text. 195 | goto end 196 | ) 197 | 198 | if "%1" == "man" ( 199 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 200 | if errorlevel 1 exit /b 1 201 | echo. 202 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 203 | goto end 204 | ) 205 | 206 | if "%1" == "texinfo" ( 207 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 208 | if errorlevel 1 exit /b 1 209 | echo. 210 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 211 | goto end 212 | ) 213 | 214 | if "%1" == "gettext" ( 215 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 216 | if errorlevel 1 exit /b 1 217 | echo. 218 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 219 | goto end 220 | ) 221 | 222 | if "%1" == "changes" ( 223 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 224 | if errorlevel 1 exit /b 1 225 | echo. 226 | echo.The overview file is in %BUILDDIR%/changes. 227 | goto end 228 | ) 229 | 230 | if "%1" == "linkcheck" ( 231 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 232 | if errorlevel 1 exit /b 1 233 | echo. 234 | echo.Link check complete; look for any errors in the above output ^ 235 | or in %BUILDDIR%/linkcheck/output.txt. 236 | goto end 237 | ) 238 | 239 | if "%1" == "doctest" ( 240 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 241 | if errorlevel 1 exit /b 1 242 | echo. 243 | echo.Testing of doctests in the sources finished, look at the ^ 244 | results in %BUILDDIR%/doctest/output.txt. 245 | goto end 246 | ) 247 | 248 | if "%1" == "coverage" ( 249 | %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage 250 | if errorlevel 1 exit /b 1 251 | echo. 252 | echo.Testing of coverage in the sources finished, look at the ^ 253 | results in %BUILDDIR%/coverage/python.txt. 254 | goto end 255 | ) 256 | 257 | if "%1" == "xml" ( 258 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 259 | if errorlevel 1 exit /b 1 260 | echo. 261 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 262 | goto end 263 | ) 264 | 265 | if "%1" == "pseudoxml" ( 266 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 267 | if errorlevel 1 exit /b 1 268 | echo. 269 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 270 | goto end 271 | ) 272 | 273 | if "%1" == "dummy" ( 274 | %SPHINXBUILD% -b dummy %ALLSPHINXOPTS% %BUILDDIR%/dummy 275 | if errorlevel 1 exit /b 1 276 | echo. 277 | echo.Build finished. Dummy builder generates no files. 278 | goto end 279 | ) 280 | 281 | :end 282 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # dottorrent documentation build configuration file, created by 5 | # sphinx-quickstart on Sun Aug 21 22:54:46 2016. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | # 20 | import os 21 | import sys 22 | sys.path.insert(0, os.path.abspath('..')) 23 | 24 | on_rtd = os.environ.get('READTHEDOCS') == 'True' 25 | 26 | # -- General configuration ------------------------------------------------ 27 | 28 | # If your documentation needs a minimal Sphinx version, state it here. 29 | # 30 | # needs_sphinx = '1.0' 31 | 32 | # Add any Sphinx extension module names here, as strings. They can be 33 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 34 | # ones. 35 | extensions = [ 36 | 'sphinx.ext.autodoc', 37 | ] 38 | 39 | autoclass_content = 'both' 40 | 41 | # Add any paths that contain templates here, relative to this directory. 42 | templates_path = ['_templates'] 43 | 44 | # The suffix(es) of source filenames. 45 | # You can specify multiple suffix as a list of string: 46 | # 47 | # source_suffix = ['.rst', '.md'] 48 | source_suffix = '.rst' 49 | 50 | # The encoding of source files. 51 | # 52 | # source_encoding = 'utf-8-sig' 53 | 54 | # The master toctree document. 55 | master_doc = 'index' 56 | 57 | # General information about the project. 58 | project = 'dottorrent' 59 | copyright = '2016, Kevin Zhang' 60 | author = 'Kevin Zhang' 61 | 62 | # The version info for the project you're documenting, acts as replacement for 63 | # |version| and |release|, also used in various other places throughout the 64 | # built documents. 65 | # 66 | # The short X.Y version. 67 | with open('../dottorrent/version.py') as f: 68 | exec(f.read()) 69 | version = __version__ 70 | # The full version, including alpha/beta/rc tags. 71 | release = version 72 | 73 | # The language for content autogenerated by Sphinx. Refer to documentation 74 | # for a list of supported languages. 75 | # 76 | # This is also used if you do content translation via gettext catalogs. 77 | # Usually you set "language" from the command line for these cases. 78 | language = None 79 | 80 | # There are two options for replacing |today|: either, you set today to some 81 | # non-false value, then it is used: 82 | # 83 | # today = '' 84 | # 85 | # Else, today_fmt is used as the format for a strftime call. 86 | # 87 | # today_fmt = '%B %d, %Y' 88 | 89 | # List of patterns, relative to source directory, that match files and 90 | # directories to ignore when looking for source files. 91 | # This patterns also effect to html_static_path and html_extra_path 92 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 93 | 94 | # The reST default role (used for this markup: `text`) to use for all 95 | # documents. 96 | # 97 | # default_role = None 98 | 99 | # If true, '()' will be appended to :func: etc. cross-reference text. 100 | # 101 | # add_function_parentheses = True 102 | 103 | # If true, the current module name will be prepended to all description 104 | # unit titles (such as .. function::). 105 | # 106 | # add_module_names = True 107 | 108 | # If true, sectionauthor and moduleauthor directives will be shown in the 109 | # output. They are ignored by default. 110 | # 111 | # show_authors = False 112 | 113 | # The name of the Pygments (syntax highlighting) style to use. 114 | pygments_style = 'sphinx' 115 | 116 | # A list of ignored prefixes for module index sorting. 117 | # modindex_common_prefix = [] 118 | 119 | # If true, keep warnings as "system message" paragraphs in the built documents. 120 | # keep_warnings = False 121 | 122 | # If true, `todo` and `todoList` produce output, else they produce nothing. 123 | todo_include_todos = False 124 | 125 | 126 | # -- Options for HTML output ---------------------------------------------- 127 | 128 | # The theme to use for HTML and HTML Help pages. See the documentation for 129 | # a list of builtin themes. 130 | # 131 | if not on_rtd: 132 | html_theme = 'sphinx_rtd_theme' 133 | 134 | # Theme options are theme-specific and customize the look and feel of a theme 135 | # further. For a list of options available for each theme, see the 136 | # documentation. 137 | # 138 | # html_theme_options = {} 139 | 140 | # Add any paths that contain custom themes here, relative to this directory. 141 | if not on_rtd: 142 | html_theme_path = ["_themes"] 143 | 144 | # The name for this set of Sphinx documents. 145 | # " v documentation" by default. 146 | # 147 | # html_title = 'dottorrent v1.0.0' 148 | 149 | # A shorter title for the navigation bar. Default is the same as html_title. 150 | # 151 | # html_short_title = None 152 | 153 | # The name of an image file (relative to this directory) to place at the top 154 | # of the sidebar. 155 | # 156 | # html_logo = None 157 | 158 | # The name of an image file (relative to this directory) to use as a favicon of 159 | # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 160 | # pixels large. 161 | # 162 | # html_favicon = None 163 | 164 | # Add any paths that contain custom static files (such as style sheets) here, 165 | # relative to this directory. They are copied after the builtin static files, 166 | # so a file named "default.css" will overwrite the builtin "default.css". 167 | html_static_path = ['_static'] 168 | 169 | # Add any extra paths that contain custom files (such as robots.txt or 170 | # .htaccess) here, relative to this directory. These files are copied 171 | # directly to the root of the documentation. 172 | # 173 | # html_extra_path = [] 174 | 175 | # If not None, a 'Last updated on:' timestamp is inserted at every page 176 | # bottom, using the given strftime format. 177 | # The empty string is equivalent to '%b %d, %Y'. 178 | # 179 | # html_last_updated_fmt = None 180 | 181 | # If true, SmartyPants will be used to convert quotes and dashes to 182 | # typographically correct entities. 183 | # 184 | # html_use_smartypants = True 185 | 186 | # Custom sidebar templates, maps document names to template names. 187 | # 188 | # html_sidebars = {} 189 | 190 | # Additional templates that should be rendered to pages, maps page names to 191 | # template names. 192 | # 193 | # html_additional_pages = {} 194 | 195 | # If false, no module index is generated. 196 | # 197 | # html_domain_indices = True 198 | 199 | # If false, no index is generated. 200 | # 201 | # html_use_index = True 202 | 203 | # If true, the index is split into individual pages for each letter. 204 | # 205 | # html_split_index = False 206 | 207 | # If true, links to the reST sources are added to the pages. 208 | # 209 | # html_show_sourcelink = True 210 | 211 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 212 | # 213 | # html_show_sphinx = True 214 | 215 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 216 | # 217 | # html_show_copyright = True 218 | 219 | # If true, an OpenSearch description file will be output, and all pages will 220 | # contain a tag referring to it. The value of this option must be the 221 | # base URL from which the finished HTML is served. 222 | # 223 | # html_use_opensearch = '' 224 | 225 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 226 | # html_file_suffix = None 227 | 228 | # Language to be used for generating the HTML full-text search index. 229 | # Sphinx supports the following languages: 230 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja' 231 | # 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh' 232 | # 233 | # html_search_language = 'en' 234 | 235 | # A dictionary with options for the search language support, empty by default. 236 | # 'ja' uses this config value. 237 | # 'zh' user can custom change `jieba` dictionary path. 238 | # 239 | # html_search_options = {'type': 'default'} 240 | 241 | # The name of a javascript file (relative to the configuration directory) that 242 | # implements a search results scorer. If empty, the default will be used. 243 | # 244 | # html_search_scorer = 'scorer.js' 245 | 246 | # Output file base name for HTML help builder. 247 | htmlhelp_basename = 'dottorrentdoc' 248 | 249 | # -- Options for LaTeX output --------------------------------------------- 250 | 251 | latex_elements = { 252 | # The paper size ('letterpaper' or 'a4paper'). 253 | # 254 | # 'papersize': 'letterpaper', 255 | 256 | # The font size ('10pt', '11pt' or '12pt'). 257 | # 258 | # 'pointsize': '10pt', 259 | 260 | # Additional stuff for the LaTeX preamble. 261 | # 262 | # 'preamble': '', 263 | 264 | # Latex figure (float) alignment 265 | # 266 | # 'figure_align': 'htbp', 267 | } 268 | 269 | # Grouping the document tree into LaTeX files. List of tuples 270 | # (source start file, target name, title, 271 | # author, documentclass [howto, manual, or own class]). 272 | latex_documents = [ 273 | (master_doc, 'dottorrent.tex', 'dottorrent Documentation', 274 | 'Kevin Zhang', 'manual'), 275 | ] 276 | 277 | # The name of an image file (relative to this directory) to place at the top of 278 | # the title page. 279 | # 280 | # latex_logo = None 281 | 282 | # For "manual" documents, if this is true, then toplevel headings are parts, 283 | # not chapters. 284 | # 285 | # latex_use_parts = False 286 | 287 | # If true, show page references after internal links. 288 | # 289 | # latex_show_pagerefs = False 290 | 291 | # If true, show URL addresses after external links. 292 | # 293 | # latex_show_urls = False 294 | 295 | # Documents to append as an appendix to all manuals. 296 | # 297 | # latex_appendices = [] 298 | 299 | # It false, will not define \strong, \code, itleref, \crossref ... but only 300 | # \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added 301 | # packages. 302 | # 303 | # latex_keep_old_macro_names = True 304 | 305 | # If false, no module index is generated. 306 | # 307 | # latex_domain_indices = True 308 | 309 | 310 | # -- Options for manual page output --------------------------------------- 311 | 312 | # One entry per manual page. List of tuples 313 | # (source start file, name, description, authors, manual section). 314 | man_pages = [ 315 | (master_doc, 'dottorrent', 'dottorrent Documentation', 316 | [author], 1) 317 | ] 318 | 319 | # If true, show URL addresses after external links. 320 | # 321 | # man_show_urls = False 322 | 323 | 324 | # -- Options for Texinfo output ------------------------------------------- 325 | 326 | # Grouping the document tree into Texinfo files. List of tuples 327 | # (source start file, target name, title, author, 328 | # dir menu entry, description, category) 329 | texinfo_documents = [ 330 | (master_doc, 'dottorrent', 'dottorrent Documentation', 331 | author, 'dottorrent', 'One line description of project.', 332 | 'Miscellaneous'), 333 | ] 334 | 335 | # Documents to append as an appendix to all manuals. 336 | # 337 | # texinfo_appendices = [] 338 | 339 | # If false, no module index is generated. 340 | # 341 | # texinfo_domain_indices = True 342 | 343 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 344 | # 345 | # texinfo_show_urls = 'footnote' 346 | 347 | # If true, do not generate a @detailmenu in the "Top" node's menu. 348 | # 349 | # texinfo_no_detailmenu = False 350 | -------------------------------------------------------------------------------- /dottorrent/__init__.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | 3 | # Copyright (c) 2016 Kevin Zhang 4 | 5 | # Permission is hereby granted, free of charge, to any person obtaining a copy 6 | # of this software and associated documentation files (the "Software"), to deal 7 | # in the Software without restriction, including without limitation the rights 8 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | # copies of the Software, and to permit persons to whom the Software is 10 | # furnished to do so, subject to the following conditions: 11 | 12 | # The above copyright notice and this permission notice shall be included in all 13 | # copies or substantial portions of the Software. 14 | 15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | # SOFTWARE. 22 | 23 | 24 | from base64 import b32encode 25 | from collections import OrderedDict 26 | from datetime import datetime 27 | from hashlib import sha1, md5 28 | import fnmatch 29 | import math 30 | import os 31 | import sys 32 | from urllib.parse import urlparse 33 | 34 | from bencoder import bencode 35 | 36 | from .version import __version__ 37 | from . import exceptions 38 | 39 | DEFAULT_CREATOR = "dottorrent/{} (https://github.com/kz26/dottorrent)".format( 40 | __version__) 41 | 42 | 43 | MIN_PIECE_SIZE = 2 ** 14 44 | MAX_PIECE_SIZE = 2 ** 26 45 | 46 | 47 | if sys.version_info >= (3, 5) and os.name == 'nt': 48 | import stat 49 | 50 | def is_hidden_file(path): 51 | fn = path.split(os.sep)[-1] 52 | return fn.startswith('.') or \ 53 | bool(os.stat(path).st_file_attributes & 54 | stat.FILE_ATTRIBUTE_HIDDEN) 55 | else: 56 | def is_hidden_file(path): 57 | fn = path.split(os.sep)[-1] 58 | return fn.startswith('.') 59 | 60 | 61 | def print_err(v): 62 | print(v, file=sys.stderr) 63 | 64 | 65 | class Torrent(object): 66 | 67 | def __init__(self, path, trackers=None, web_seeds=None, 68 | piece_size=None, private=False, source=None, 69 | creation_date=None, comment=None, created_by=None, 70 | include_md5=False, exclude=None): 71 | """ 72 | :param path: path to a file or directory from which to create the torrent 73 | :param trackers: list/iterable of tracker URLs 74 | :param web_seeds: list/iterable of HTTP/FTP seed URLs 75 | :param piece_size: Piece size in bytes. Must be >= 16 KB and a power of 2. 76 | If None, ``get_info()`` will be used to automatically select a piece size. 77 | :param private: The private flag. If True, DHT/PEX will be disabled. 78 | :param source: An optional source string for the torrent. 79 | :param exclude: A list of filename patterns that should be excluded from the torrent. 80 | :param creation_date: An optional datetime object representing the torrent creation date. 81 | :param comment: An optional comment string for the torrent. 82 | :param created_by: name/version of the program used to create the .torrent. 83 | If None, defaults to the value of ``DEFAULT_CREATOR``. 84 | :param include_md5: If True, also computes and stores MD5 hashes for each file. 85 | """ 86 | 87 | self.path = os.path.normpath(path) 88 | self.trackers = trackers 89 | self.web_seeds = web_seeds 90 | self.piece_size = piece_size 91 | self.private = private 92 | self.source = source 93 | self.exclude = [] if exclude is None else exclude 94 | self.creation_date = creation_date 95 | self.comment = comment 96 | self.created_by = created_by 97 | self.include_md5 = include_md5 98 | 99 | self._data = None 100 | 101 | @property 102 | def trackers(self): 103 | return self._trackers 104 | 105 | @trackers.setter 106 | def trackers(self, value): 107 | tl = [] 108 | if value: 109 | for t in value: 110 | pr = urlparse(t) 111 | if pr.scheme and pr.netloc: 112 | tl.append(t) 113 | else: 114 | raise exceptions.InvalidURLException(t) 115 | self._trackers = tl 116 | 117 | @property 118 | def web_seeds(self): 119 | return self._web_seeds 120 | 121 | @web_seeds.setter 122 | def web_seeds(self, value): 123 | tl = [] 124 | if value: 125 | for t in value: 126 | pr = urlparse(t) 127 | if pr.scheme and pr.netloc: 128 | tl.append(t) 129 | else: 130 | raise exceptions.InvalidURLException(t) 131 | self._web_seeds = tl 132 | 133 | @property 134 | def piece_size(self): 135 | return self._piece_size 136 | 137 | @piece_size.setter 138 | def piece_size(self, value): 139 | if value: 140 | value = int(value) 141 | if value > 0 and (value & (value-1) == 0): 142 | if value < MIN_PIECE_SIZE: 143 | raise exceptions.InvalidPieceSizeException( 144 | "Piece size should be at least 16 KiB") 145 | if value > MAX_PIECE_SIZE: 146 | print_err("Warning: piece size is greater than 64 MiB") 147 | self._piece_size = value 148 | else: 149 | raise exceptions.InvalidPieceSizeException( 150 | "Piece size must be a power of 2 bytes") 151 | else: 152 | self._piece_size = None 153 | 154 | def get_info(self): 155 | """ 156 | Scans the input path and automatically determines the optimal 157 | piece size based on ~1500 pieces (up to MAX_PIECE_SIZE) along 158 | with other basic info, including total size (in bytes), the 159 | total number of files, piece size (in bytes), and resulting 160 | number of pieces. If ``piece_size`` has already been set, the 161 | custom value will be used instead. 162 | 163 | :return: ``(total_size, total_files, piece_size, num_pieces)`` 164 | """ 165 | if os.path.isfile(self.path): 166 | total_size = os.path.getsize(self.path) 167 | total_files = 1 168 | elif os.path.exists(self.path): 169 | total_size = 0 170 | total_files = 0 171 | for x in os.walk(self.path): 172 | for fn in x[2]: 173 | fpath = os.path.normpath(os.path.join(x[0], fn)) 174 | rel_path = os.path.relpath(fpath, self.path) 175 | if any(fnmatch.fnmatch(rel_path, ext) for ext in self.exclude): 176 | continue 177 | fsize = os.path.getsize(fpath) 178 | if fsize and not is_hidden_file(fpath): 179 | total_size += fsize 180 | total_files += 1 181 | else: 182 | raise exceptions.InvalidInputException 183 | if not (total_files and total_size): 184 | raise exceptions.EmptyInputException 185 | if self.piece_size: 186 | ps = self.piece_size 187 | else: 188 | ps = 1 << max(0, math.ceil(math.log(total_size / 1500, 2))) 189 | if ps < MIN_PIECE_SIZE: 190 | ps = MIN_PIECE_SIZE 191 | if ps > MAX_PIECE_SIZE: 192 | ps = MAX_PIECE_SIZE 193 | return (total_size, total_files, ps, math.ceil(total_size / ps)) 194 | 195 | def generate(self, callback=None): 196 | """ 197 | Computes and stores piece data. Returns ``True`` on success, ``False`` 198 | otherwise. 199 | 200 | :param callback: progress/cancellation callable with method 201 | signature ``(filename, pieces_completed, pieces_total)``. 202 | Useful for reporting progress if dottorrent is used in a 203 | GUI/threaded context, and if torrent generation needs to be cancelled. 204 | The callable's return value should evaluate to ``True`` to trigger 205 | cancellation. 206 | """ 207 | files = [] 208 | single_file = os.path.isfile(self.path) 209 | if single_file: 210 | files.append((self.path, os.path.getsize(self.path), {})) 211 | elif os.path.exists(self.path): 212 | for x in os.walk(self.path): 213 | for fn in x[2]: 214 | fpath = os.path.normpath(os.path.join(x[0], fn)) 215 | rel_path = os.path.relpath(fpath, self.path) 216 | if any(fnmatch.fnmatch(rel_path, ext) for ext in self.exclude): 217 | continue 218 | fsize = os.path.getsize(fpath) 219 | if fsize and not is_hidden_file(fpath): 220 | files.append((fpath, fsize, {})) 221 | else: 222 | raise exceptions.InvalidInputException 223 | total_size = sum([x[1] for x in files]) 224 | if not (len(files) and total_size): 225 | raise exceptions.EmptyInputException 226 | # set piece size if not already set 227 | if self.piece_size is None: 228 | self.piece_size = self.get_info()[2] 229 | if files: 230 | self._pieces = bytearray() 231 | i = 0 232 | num_pieces = math.ceil(total_size / self.piece_size) 233 | pc = 0 234 | buf = bytearray() 235 | while i < len(files): 236 | fe = files[i] 237 | f = open(fe[0], 'rb') 238 | if self.include_md5: 239 | md5_hasher = md5() 240 | else: 241 | md5_hasher = None 242 | for chunk in iter(lambda: f.read(self.piece_size), b''): 243 | buf += chunk 244 | if len(buf) >= self.piece_size \ 245 | or i == len(files)-1: 246 | piece = buf[:self.piece_size] 247 | self._pieces += sha1(piece).digest() 248 | del buf[:self.piece_size] 249 | pc += 1 250 | if callback: 251 | cancel = callback(fe[0], pc, num_pieces) 252 | if cancel: 253 | f.close() 254 | return False 255 | if self.include_md5: 256 | md5_hasher.update(chunk) 257 | if self.include_md5: 258 | fe[2]['md5sum'] = md5_hasher.hexdigest() 259 | f.close() 260 | i += 1 261 | # Add pieces from any remaining data 262 | while len(buf): 263 | piece = buf[:self.piece_size] 264 | self._pieces += sha1(piece).digest() 265 | del buf[:self.piece_size] 266 | pc += 1 267 | if callback: 268 | cancel = callback(fe[0], pc, num_pieces) 269 | if cancel: 270 | return False 271 | 272 | # Create the torrent data structure 273 | data = OrderedDict() 274 | if len(self.trackers) > 0: 275 | data['announce'] = self.trackers[0].encode() 276 | if len(self.trackers) > 1: 277 | data['announce-list'] = [[x.encode()] for x in self.trackers] 278 | if self.comment: 279 | data['comment'] = self.comment.encode() 280 | if self.created_by: 281 | data['created by'] = self.created_by.encode() 282 | else: 283 | data['created by'] = DEFAULT_CREATOR.encode() 284 | if self.creation_date: 285 | data['creation date'] = int(self.creation_date.timestamp()) 286 | if self.web_seeds: 287 | data['url-list'] = [x.encode() for x in self.web_seeds] 288 | data['info'] = OrderedDict() 289 | if single_file: 290 | data['info']['length'] = files[0][1] 291 | if self.include_md5: 292 | data['info']['md5sum'] = files[0][2]['md5sum'] 293 | data['info']['name'] = files[0][0].split(os.sep)[-1].encode() 294 | else: 295 | data['info']['files'] = [] 296 | path_sp = self.path.split(os.sep) 297 | for x in files: 298 | fx = OrderedDict() 299 | fx['length'] = x[1] 300 | if self.include_md5: 301 | fx['md5sum'] = x[2]['md5sum'] 302 | fx['path'] = [y.encode() 303 | for y in x[0].split(os.sep)[len(path_sp):]] 304 | data['info']['files'].append(fx) 305 | data['info']['name'] = path_sp[-1].encode() 306 | data['info']['pieces'] = bytes(self._pieces) 307 | data['info']['piece length'] = self.piece_size 308 | data['info']['private'] = int(self.private) 309 | if self.source: 310 | data['info']['source'] = self.source.encode() 311 | 312 | self._data = data 313 | return True 314 | 315 | @property 316 | def data(self): 317 | """ 318 | Returns the data dictionary for the torrent. 319 | 320 | .. note:: ``generate()`` must be called first. 321 | """ 322 | 323 | if self._data: 324 | return self._data 325 | else: 326 | raise exceptions.TorrentNotGeneratedException 327 | 328 | @property 329 | def info_hash_base32(self): 330 | """ 331 | Returns the base32 info hash of the torrent. Useful for generating 332 | magnet links. 333 | 334 | .. note:: ``generate()`` must be called first. 335 | """ 336 | if getattr(self, '_data', None): 337 | return b32encode(sha1(bencode(self._data['info'])).digest()) 338 | else: 339 | raise exceptions.TorrentNotGeneratedException 340 | 341 | @property 342 | def info_hash(self): 343 | """ 344 | :return: The SHA-1 info hash of the torrent. Useful for generating 345 | magnet links. 346 | 347 | .. note:: ``generate()`` must be called first. 348 | """ 349 | if getattr(self, '_data', None): 350 | return sha1(bencode(self._data['info'])).hexdigest() 351 | else: 352 | raise exceptions.TorrentNotGeneratedException 353 | 354 | def dump(self): 355 | """ 356 | :return: The bencoded torrent data as a byte string. 357 | 358 | .. note:: ``generate()`` must be called first. 359 | """ 360 | if getattr(self, '_data', None): 361 | 362 | return bencode(self._data) 363 | else: 364 | raise exceptions.TorrentNotGeneratedException 365 | 366 | def save(self, fp): 367 | """ 368 | Saves the torrent to ``fp``, a file(-like) object 369 | opened in binary writing (``wb``) mode. 370 | 371 | .. note:: ``generate()`` must be called first. 372 | """ 373 | fp.write(self.dump()) 374 | --------------------------------------------------------------------------------