├── .gitignore ├── AUTHORS ├── CHANGELOG ├── LICENSE ├── MANIFEST.in ├── README.rst ├── dist ├── WebAPI-0.3.1-py2.7.egg ├── WebAPI-0.3.2-py2.7.egg ├── WebAPI-0.4.0-py3.6.egg └── WebAPI-0.4.0-py3.7.egg ├── docs ├── Makefile ├── build │ └── empty └── source │ ├── _static │ └── empty │ ├── _templates │ └── empty │ ├── conf.py │ ├── index.rst │ ├── quickstart.rst │ └── rst_guide.rst ├── init_dev.sh ├── setup.py └── webapi ├── __init__.py ├── common.py ├── core.py ├── data ├── config.ui └── webapi.js ├── gtk3ui.py ├── test.py └── webui.py /.gitignore: -------------------------------------------------------------------------------- 1 | .project 2 | .pydevproject 3 | .idea 4 | .tox 5 | __pycache__ 6 | *.pyc 7 | *.pyo 8 | *.egg-info 9 | build/ 10 | docs/_build/ 11 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | deluge-webapi authors 2 | ===================== 3 | 4 | Created by Igor `idle sign` Starikov. 5 | 6 | 7 | Contributors 8 | ------------ 9 | 10 | theonedemon 11 | Daniel Marcos 12 | Brandon Gillis 13 | Ivan Filippov 14 | griest024 15 | -------------------------------------------------------------------------------- /CHANGELOG: -------------------------------------------------------------------------------- 1 | deluge-webapi changelog 2 | ======================= 3 | 4 | v0.4.0 5 | ------ 6 | * Added support for Deluge 2 7 | * get_torrents will now accept a comma separated string in addition to accepting a list for field filters 8 | * Future support for Deluge 1.x is no longer possible, please use the older eggs 9 | 10 | v0.3.1 11 | ------ 12 | * Added CORS settings for WebUI. 13 | 14 | 15 | v0.3.0 16 | ------ 17 | * Add CORS support. 18 | * Added CORS settings for GTK. 19 | 20 | 21 | v0.2.1 22 | ------ 23 | * Fixed add_rorrent download_location not honored (see #8). 24 | 25 | 26 | v0.2.0 27 | ------ 28 | + Plugin updated to work with Deluge 1.3.15 29 | + `add_torrent` now returns torrent id (hash) (see #5). 30 | + `remove_torrent` now returns the result of core function instad of `True`. 31 | 32 | 33 | v0.1.0 34 | ------ 35 | + Basic functionality. 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014-2019 Igor `idle sign` Starikov 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, this 8 | list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the deluge-webapi nor the names of its 15 | contributors may be used to endorse or promote products derived from 16 | this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 22 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 23 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 24 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 25 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 26 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include AUTHORS 2 | include CHANGELOG 3 | include LICENSE 4 | include README.rst 5 | 6 | include docs/Makefile 7 | recursive-include docs *.rst 8 | recursive-include docs *.py 9 | 10 | recursive-exclude * __pycache__ 11 | recursive-exclude * *.py[co] 12 | recursive-exclude * empty 13 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | deluge-webapi 2 | ============= 3 | https://github.com/idlesign/deluge-webapi 4 | 5 | 6 | .. image:: https://img.shields.io/pypi/v/deluge-webapi.svg 7 | :target: https://pypi.python.org/pypi/deluge-webapi 8 | 9 | 10 | Description 11 | ----------- 12 | 13 | *Plugin for Deluge WebUI providing sane JSON API.* 14 | 15 | Exposes some sane JSON API through Deluge WebUI (missing out of the box or restyled) so that you can manipulate 16 | Deluge from your programs using HTTP requests. 17 | 18 | Supported methods: 19 | 20 | * ``get_torrents`` 21 | * ``add_torrent`` (magnet or file) 22 | * ``remove_torrent`` 23 | * ``get_api_version`` 24 | 25 | Deluge is a lightweight, Free Software, cross-platform BitTorrent client. Download it at http://deluge-torrent.org/ 26 | 27 | .. note:: Use egg version 0.4.0 or higher for Deluge 2 28 | .. note:: Use egg version 0.3.2 or lower for Deluge 1.x 29 | 30 | 31 | Installation 32 | ------------ 33 | 34 | 1. Get plugin egg file, from ``dist/`` (https://github.com/idlesign/deluge-webapi/tree/master/dist) directory. 35 | 36 | 2. Open Deluge Web UI, go to "Preferences -> Plugins -> Install plugin" and choose egg file. 37 | 38 | 3. Activate ``WebAPI`` plugin. 39 | 40 | 4. In case you use Client-Server setup, you'll need to install the plugin both on client and server, see - https://dev.deluge-torrent.org/wiki/Plugins#Client-ServerSetups 41 | 42 | 43 | .. note:: 44 | 45 | To build .egg file from source code yourself use ``python setup.py bdist_egg`` command in source code directory. 46 | 47 | 48 | Documentation 49 | ------------- 50 | 51 | http://deluge-webapi.readthedocs.org/ 52 | -------------------------------------------------------------------------------- /dist/WebAPI-0.3.1-py2.7.egg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/idlesign/deluge-webapi/114c39324c1297168ffafd0ee9b2b2726c65408c/dist/WebAPI-0.3.1-py2.7.egg -------------------------------------------------------------------------------- /dist/WebAPI-0.3.2-py2.7.egg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/idlesign/deluge-webapi/114c39324c1297168ffafd0ee9b2b2726c65408c/dist/WebAPI-0.3.2-py2.7.egg -------------------------------------------------------------------------------- /dist/WebAPI-0.4.0-py3.6.egg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/idlesign/deluge-webapi/114c39324c1297168ffafd0ee9b2b2726c65408c/dist/WebAPI-0.4.0-py3.6.egg -------------------------------------------------------------------------------- /dist/WebAPI-0.4.0-py3.7.egg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/idlesign/deluge-webapi/114c39324c1297168ffafd0ee9b2b2726c65408c/dist/WebAPI-0.4.0-py3.7.egg -------------------------------------------------------------------------------- /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) source 14 | 15 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest 16 | 17 | help: 18 | @echo "Please use \`make ' where is one of" 19 | @echo " html to make standalone HTML files" 20 | @echo " dirhtml to make HTML files named index.html in directories" 21 | @echo " singlehtml to make a single large HTML file" 22 | @echo " pickle to make pickle files" 23 | @echo " json to make JSON files" 24 | @echo " htmlhelp to make HTML files and a HTML help project" 25 | @echo " qthelp to make HTML files and a qthelp project" 26 | @echo " devhelp to make HTML files and a Devhelp project" 27 | @echo " epub to make an epub" 28 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 29 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 30 | @echo " text to make text files" 31 | @echo " man to make manual pages" 32 | @echo " changes to make an overview of all changed/added/deprecated items" 33 | @echo " linkcheck to check all external links for integrity" 34 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 35 | 36 | clean: 37 | -rm -rf $(BUILDDIR)/* 38 | 39 | html: 40 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 41 | @echo 42 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 43 | 44 | dirhtml: 45 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 46 | @echo 47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 48 | 49 | singlehtml: 50 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 51 | @echo 52 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 53 | 54 | pickle: 55 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 56 | @echo 57 | @echo "Build finished; now you can process the pickle files." 58 | 59 | json: 60 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 61 | @echo 62 | @echo "Build finished; now you can process the JSON files." 63 | 64 | htmlhelp: 65 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 66 | @echo 67 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 68 | ".hhp project file in $(BUILDDIR)/htmlhelp." 69 | 70 | qthelp: 71 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 72 | @echo 73 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 74 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 75 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/deluge-webapi.qhcp" 76 | @echo "To view the help file:" 77 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/deluge-webapi.qhc" 78 | 79 | devhelp: 80 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 81 | @echo 82 | @echo "Build finished." 83 | @echo "To view the help file:" 84 | @echo "# mkdir -p $$HOME/.local/share/devhelp/deluge-webapi" 85 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/deluge-webapi" 86 | @echo "# devhelp" 87 | 88 | epub: 89 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 90 | @echo 91 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 92 | 93 | latex: 94 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 95 | @echo 96 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 97 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 98 | "(use \`make latexpdf' here to do that automatically)." 99 | 100 | latexpdf: 101 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 102 | @echo "Running LaTeX files through pdflatex..." 103 | make -C $(BUILDDIR)/latex all-pdf 104 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 105 | 106 | text: 107 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 108 | @echo 109 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 110 | 111 | man: 112 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 113 | @echo 114 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 115 | 116 | changes: 117 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 118 | @echo 119 | @echo "The overview file is in $(BUILDDIR)/changes." 120 | 121 | linkcheck: 122 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 123 | @echo 124 | @echo "Link check complete; look for any errors in the above output " \ 125 | "or in $(BUILDDIR)/linkcheck/output.txt." 126 | 127 | doctest: 128 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 129 | @echo "Testing of doctests in the sources finished, look at the " \ 130 | "results in $(BUILDDIR)/doctest/output.txt." 131 | -------------------------------------------------------------------------------- /docs/build/empty: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/idlesign/deluge-webapi/114c39324c1297168ffafd0ee9b2b2726c65408c/docs/build/empty -------------------------------------------------------------------------------- /docs/source/_static/empty: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/idlesign/deluge-webapi/114c39324c1297168ffafd0ee9b2b2726c65408c/docs/source/_static/empty -------------------------------------------------------------------------------- /docs/source/_templates/empty: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/idlesign/deluge-webapi/114c39324c1297168ffafd0ee9b2b2726c65408c/docs/source/_templates/empty -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # deluge-webapi documentation build configuration file. 4 | # 5 | # This file is execfile()d with the current directory set to its containing dir. 6 | # 7 | # Note that not all possible configuration values are present in this 8 | # autogenerated file. 9 | # 10 | # All configuration values have a default; values that are commented out 11 | # serve to show the default. 12 | 13 | import sys, os 14 | 15 | # If extensions (or modules to document with autodoc) are in another directory, 16 | # add these directories to sys.path here. If the directory is relative to the 17 | # documentation root, use os.path.abspath to make it absolute, like shown here. 18 | sys.path.insert(0, os.path.abspath('../../')) 19 | from webapi import VERSION 20 | 21 | # -- General configuration ----------------------------------------------------- 22 | 23 | # If your documentation needs a minimal Sphinx version, state it here. 24 | #needs_sphinx = '1.0' 25 | 26 | # Add any Sphinx extension module names here, as strings. They can be extensions 27 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 28 | extensions = ['sphinx.ext.autodoc'] 29 | 30 | # Add any paths that contain templates here, relative to this directory. 31 | templates_path = ['_templates'] 32 | 33 | # The suffix of source filenames. 34 | source_suffix = '.rst' 35 | 36 | # The encoding of source files. 37 | #source_encoding = 'utf-8-sig' 38 | 39 | # The master toctree document. 40 | master_doc = 'index' 41 | 42 | # General information about the project. 43 | project = u'deluge-webapi' 44 | copyright = u'2014-2019, Igor `idle sign` Starikov' 45 | 46 | # The version info for the project you're documenting, acts as replacement for 47 | # |version| and |release|, also used in various other places throughout the 48 | # built documents. 49 | # 50 | # The short X.Y version. 51 | version = '.'.join(map(str, VERSION)) 52 | # The full version, including alpha/beta/rc tags. 53 | release = '.'.join(map(str, VERSION)) 54 | 55 | # The language for content autogenerated by Sphinx. Refer to documentation 56 | # for a list of supported languages. 57 | #language = None 58 | 59 | # There are two options for replacing |today|: either, you set today to some 60 | # non-false value, then it is used: 61 | #today = '' 62 | # Else, today_fmt is used as the format for a strftime call. 63 | #today_fmt = '%B %d, %Y' 64 | 65 | # List of patterns, relative to source directory, that match files and 66 | # directories to ignore when looking for source files. 67 | exclude_patterns = [] 68 | 69 | # The reST default role (used for this markup: `text`) to use for all documents. 70 | #default_role = None 71 | 72 | # If true, '()' will be appended to :func: etc. cross-reference text. 73 | #add_function_parentheses = True 74 | 75 | # If true, the current module name will be prepended to all description 76 | # unit titles (such as .. function::). 77 | #add_module_names = True 78 | 79 | # If true, sectionauthor and moduleauthor directives will be shown in the 80 | # output. They are ignored by default. 81 | #show_authors = False 82 | 83 | # The name of the Pygments (syntax highlighting) style to use. 84 | pygments_style = 'sphinx' 85 | 86 | # A list of ignored prefixes for module index sorting. 87 | #modindex_common_prefix = [] 88 | 89 | 90 | # -- Options for HTML output --------------------------------------------------- 91 | 92 | # The theme to use for HTML and HTML Help pages. See the documentation for 93 | # a list of builtin themes. 94 | html_theme = 'default' 95 | 96 | # Theme options are theme-specific and customize the look and feel of a theme 97 | # further. For a list of options available for each theme, see the 98 | # documentation. 99 | #html_theme_options = {} 100 | 101 | # Add any paths that contain custom themes here, relative to this directory. 102 | #html_theme_path = [] 103 | 104 | # The name for this set of Sphinx documents. If None, it defaults to 105 | # " v documentation". 106 | #html_title = None 107 | 108 | # A shorter title for the navigation bar. Default is the same as html_title. 109 | #html_short_title = None 110 | 111 | # The name of an image file (relative to this directory) to place at the top 112 | # of the sidebar. 113 | #html_logo = None 114 | 115 | # The name of an image file (within the static path) to use as favicon of the 116 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 117 | # pixels large. 118 | #html_favicon = None 119 | 120 | # Add any paths that contain custom static files (such as style sheets) here, 121 | # relative to this directory. They are copied after the builtin static files, 122 | # so a file named "default.css" will overwrite the builtin "default.css". 123 | html_static_path = ['_static'] 124 | 125 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 126 | # using the given strftime format. 127 | #html_last_updated_fmt = '%b %d, %Y' 128 | 129 | # If true, SmartyPants will be used to convert quotes and dashes to 130 | # typographically correct entities. 131 | #html_use_smartypants = True 132 | 133 | # Custom sidebar templates, maps document names to template names. 134 | #html_sidebars = {} 135 | 136 | # Additional templates that should be rendered to pages, maps page names to 137 | # template names. 138 | #html_additional_pages = {} 139 | 140 | # If false, no module index is generated. 141 | #html_domain_indices = True 142 | 143 | # If false, no index is generated. 144 | #html_use_index = True 145 | 146 | # If true, the index is split into individual pages for each letter. 147 | #html_split_index = False 148 | 149 | # If true, links to the reST sources are added to the pages. 150 | #html_show_sourcelink = True 151 | 152 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 153 | #html_show_sphinx = True 154 | 155 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 156 | #html_show_copyright = True 157 | 158 | # If true, an OpenSearch description file will be output, and all pages will 159 | # contain a tag referring to it. The value of this option must be the 160 | # base URL from which the finished HTML is served. 161 | #html_use_opensearch = '' 162 | 163 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 164 | #html_file_suffix = None 165 | 166 | # Output file base name for HTML help builder. 167 | htmlhelp_basename = 'deluge-webapidoc' 168 | 169 | 170 | # -- Options for LaTeX output -------------------------------------------------- 171 | 172 | # The paper size ('letter' or 'a4'). 173 | #latex_paper_size = 'letter' 174 | 175 | # The font size ('10pt', '11pt' or '12pt'). 176 | #latex_font_size = '10pt' 177 | 178 | # Grouping the document tree into LaTeX files. List of tuples 179 | # (source start file, target name, title, author, documentclass [howto/manual]). 180 | latex_documents = [ 181 | ('index', 'deluge-webapi.tex', u'deluge-webapi Documentation', 182 | u'Igor `idle sign` Starikov', 'manual'), 183 | ] 184 | 185 | # The name of an image file (relative to this directory) to place at the top of 186 | # the title page. 187 | #latex_logo = None 188 | 189 | # For "manual" documents, if this is true, then toplevel headings are parts, 190 | # not chapters. 191 | #latex_use_parts = False 192 | 193 | # If true, show page references after internal links. 194 | #latex_show_pagerefs = False 195 | 196 | # If true, show URL addresses after external links. 197 | #latex_show_urls = False 198 | 199 | # Additional stuff for the LaTeX preamble. 200 | #latex_preamble = '' 201 | 202 | # Documents to append as an appendix to all manuals. 203 | #latex_appendices = [] 204 | 205 | # If false, no module index is generated. 206 | #latex_domain_indices = True 207 | 208 | 209 | # -- Options for manual page output -------------------------------------------- 210 | 211 | # One entry per manual page. List of tuples 212 | # (source start file, name, description, authors, manual section). 213 | man_pages = [ 214 | ('index', 'deluge-webapi', u'deluge-webapi Documentation', 215 | [u'Igor `idle sign` Starikov'], 1) 216 | ] 217 | -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | deluge-webapi documentation 2 | =========================== 3 | https://github.com/idlesign/deluge-webapi 4 | 5 | 6 | 7 | Description 8 | ----------- 9 | 10 | *Plugin for Deluge WebUI providing sane JSON API.* 11 | 12 | Exposes some sane JSON API through Deluge WebUI (missing out of the box or restyled) so that you can manipulate 13 | Deluge from your programs using HTTP requests. 14 | 15 | 16 | Requirements 17 | ------------ 18 | 19 | 1. Python 2.7+ 20 | 2. Deluge 1.3.15+ 21 | 22 | 23 | Installation 24 | ------------ 25 | 26 | * Get plugin egg file, from ``dist/`` (https://github.com/idlesign/deluge-webapi/tree/master/dist) directory. 27 | 28 | * Open Deluge Web UI, go to "Preferences -> Plugins -> Install plugin" and choose egg file. 29 | 30 | .. note:: 31 | 32 | To build .egg file from source code yourself use `python setup.py bdist_egg` command in source code directory. 33 | 34 | * Activate `WebAPI` plugin. 35 | 36 | * You're ready. 37 | 38 | 39 | Table of Contents 40 | ----------------- 41 | 42 | .. toctree:: 43 | :maxdepth: 2 44 | 45 | quickstart 46 | 47 | 48 | Get involved into deluge-webapi 49 | ------------------------------- 50 | 51 | **Submit issues.** If you spotted something weird in application behavior or want to propose a feature you can do that at https://github.com/idlesign/deluge-webapi/issues 52 | 53 | **Write code.** If you are eager to participate in application development, fork it at https://github.com/idlesign/deluge-webapi, write your code, whether it should be a bugfix or a feature implementation, and make a pull request right from the forked project page. 54 | 55 | **Spread the word.** If you have some tips and tricks or any other words in mind that you think might be of interest for the others — publish it. 56 | 57 | 58 | More things 59 | ----------- 60 | 61 | * You might be interested in considering other Deluge plugins at http://dev.deluge-torrent.org/wiki/Plugins/ 62 | * Or you might be interested in a PHP Deluge API wrapper: https://github.com/kaysond/deluge-php 63 | 64 | -------------------------------------------------------------------------------- /docs/source/quickstart.rst: -------------------------------------------------------------------------------- 1 | Quick Reference 2 | =============== 3 | 4 | .. note:: 5 | 6 | First make sure you're using WebUI and ``WebAPI`` plugin is active under "Preferences -> Plugins". 7 | 8 | 9 | Hints 10 | ----- 11 | 12 | 1. WebAPI exists alongside with Deluge built-in JSON API, so all HTTP requests should proceed to 13 | 14 | ``http://localhost:8112/json`` (or what ever you've got instead of ``localhost``) 15 | 16 | 2. Use POST method for HTTP requests. 17 | 18 | 3. Make requests with valid JSON (including ``Accept: application/json`` and ``Content-Type: application/json`` HTTP headers). 19 | 20 | 4. JSON must include the following fields: 21 | 22 | ``id`` - message number for identity (could be any, increment it freely) 23 | 24 | ``method`` - API method name. E.g.: ``auth.login``, ``webapi.get_torrents`` 25 | 26 | ``params`` - API method parameters (depend on method) 27 | 28 | 5. Login beforehand. 29 | 30 | * Send ``{"id": 1, "method": "auth.login", "params": ["your_password_here"]}`` and receive cookies with auth information. 31 | 32 | * Use those cookies for every request. 33 | 34 | 6. API answers with an error with the following JSON: 35 | 36 | ``{"error": {"message": "Some error description."}, "id": 1, "result": False}`` 37 | 38 | Check responses for ``error`` field. 39 | 40 | 7. Make sure Deluge WebUI is connected to Deluge daemon that makes actual torrent processing. 41 | 42 | * Send ``{"id": 1, "method": "auth.check_session", "params": []}`` and verify no error. 43 | 44 | 8. WebAPI method names start with ``webapi.``. (E.g.: ``webapi.add_torrent`` to call ``add_torrent`` function). 45 | 46 | 9. See https://github.com/idlesign/deluge-webapi/blob/master/webapi/test.py for code sample. Run it for basic debug. 47 | 48 | 49 | Debug 50 | ----- 51 | 52 | If you have problems with plugin activation, you can get log with useful information (look for string containing ``webapi``). 53 | 54 | For ``deluged``: 55 | 56 | .. code-block:: bash 57 | 58 | $ deluged -d -L info 59 | 60 | 61 | For ``deluged-web``: 62 | 63 | .. code-block:: bash 64 | 65 | $ deluge-web -L info 66 | 67 | 68 | You can run https://github.com/idlesign/deluge-webapi/blob/master/webapi/test.py for basic test. 69 | 70 | 71 | 72 | API Methods 73 | ----------- 74 | 75 | 76 | .. note:: 77 | 78 | WebAPI uses torrent hashes to identify torrents, so torrent ID is the same as hash. 79 | 80 | 81 | Get torrents info 82 | ~~~~~~~~~~~~~~~~~ 83 | 84 | ``get_torrents(ids=None, params=None)`` 85 | 86 | Returns information about all or a definite torrent. 87 | Returned information can be filtered by supplying wanted parameter names. 88 | 89 | .. code-block:: 90 | 91 | {"id": 1, "method": "webapi.get_torrents", "params": [["torrent_hash1", "torrent_hash2"], ["name", "comment"]]} 92 | 93 | 94 | Add torrent 95 | ~~~~~~~~~~~ 96 | 97 | ``add_torrent(metainfo, options=None)`` 98 | 99 | Adds a torrent with the given options. 100 | `metainfo` could either be base64 torrent data or a magnet link. 101 | 102 | .. code-block:: 103 | 104 | {"id": 1, "method": "webapi.add_torrent", "params": ["base64_encoded_torrent_file_contents", {"download_location": "/home/idle/downloads/"}]} 105 | 106 | 107 | Remove torrent 108 | ~~~~~~~~~~~~~~ 109 | 110 | ``remove_torrent(torrent_id, remove_data=False)`` 111 | 112 | Removes a given torrent. Optionally can remove data. 113 | 114 | .. code-block:: 115 | 116 | {"id": 1, "method": "webapi.remove_torrent", "params": ["torrent_hash3", True]} 117 | 118 | 119 | Get API version 120 | ~~~~~~~~~~~~~~~ 121 | 122 | ``get_api_version()`` 123 | 124 | Returns WebAPI plugin version. 125 | 126 | .. code-block:: 127 | 128 | {"id": 1, "method": "webapi.get_api_version", "params": []} 129 | 130 | -------------------------------------------------------------------------------- /docs/source/rst_guide.rst: -------------------------------------------------------------------------------- 1 | RST Quick guide 2 | =============== 3 | 4 | Online reStructuredText editor - http://rst.ninjs.org/ 5 | 6 | 7 | Main heading 8 | ============ 9 | 10 | 11 | Secondary heading 12 | ----------------- 13 | 14 | 15 | 16 | Typography 17 | ---------- 18 | 19 | **Bold** 20 | 21 | `Italic` 22 | 23 | ``Accent`` 24 | 25 | 26 | 27 | Blocks 28 | ------ 29 | 30 | Double colon to consider the following paragraphs preformatted:: 31 | 32 | This text is preformated. Can be used for code samples. 33 | 34 | 35 | .. code-block:: python 36 | 37 | # code-block accepts language name to highlight code 38 | # E.g.: python, html 39 | import this 40 | 41 | 42 | .. note:: 43 | 44 | This text will be rendered as a note block (usually green). 45 | 46 | 47 | .. warning:: 48 | 49 | This text will be rendered as a warning block (usually red). 50 | 51 | 52 | 53 | Lists 54 | ----- 55 | 56 | 1. Ordered item 1. 57 | 58 | Indent paragraph to make in belong to the above list item. 59 | 60 | 2. Ordered item 2. 61 | 62 | 63 | + Unordered item 1. 64 | + Unordered item . 65 | 66 | 67 | 68 | Links 69 | ----- 70 | 71 | :ref:`Documentation inner link label ` 72 | 73 | .. _some-marker: 74 | 75 | 76 | `Outer link label `_ 77 | 78 | Inline URLs are converted to links automatically: http://github.com/idlesign/makeapp/ 79 | 80 | 81 | 82 | Automation 83 | ---------- 84 | 85 | http://sphinx-doc.org/ext/autodoc.html 86 | 87 | .. automodule:: my_module 88 | :members: 89 | 90 | .. autoclass:: my_module.MyClass 91 | :members: do_this, do_that 92 | :inherited-members: 93 | -------------------------------------------------------------------------------- /init_dev.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Exposes the plugin (in it sources) to Deluge for development purposes. 4 | mkdir temp 5 | 6 | export PYTHONPATH=./temp 7 | python setup.py build develop --install-dir ./temp 8 | cp ./temp/WebAPI.egg-link ~/.config/deluge/plugins 9 | rm -fr ./temp -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | from setuptools import setup 3 | from webapi import VERSION 4 | 5 | 6 | PATH_BASE = os.path.dirname(__file__) 7 | PATH_BIN = os.path.join(PATH_BASE, 'bin') 8 | 9 | SCRIPTS = None 10 | if os.path.exists(PATH_BIN): 11 | SCRIPTS = [os.path.join('bin', f) for f in os.listdir(PATH_BIN) if os.path.join(PATH_BIN, f)] 12 | 13 | f = open(os.path.join(PATH_BASE, 'README.rst')) 14 | README = f.read() 15 | f.close() 16 | 17 | __plugin_name__ = 'WebAPI' 18 | __version__ = '.'.join(map(str, VERSION)) 19 | __description__ = 'Plugin for Deluge WebUI providing sane JSON API.' 20 | __long_description__ = __description__ 21 | __author__ = 'Igor `idle sign` Starikov' 22 | __author_email__ = 'idlesign@yandex.ru' 23 | __license__ = 'BSD 3-Clause License' 24 | __url__ = 'https://github.com/idlesign/deluge-webapi' 25 | 26 | 27 | __pkg_data__ = {__plugin_name__.lower(): ['data/*']} 28 | 29 | setup( 30 | name=__plugin_name__, 31 | version=__version__, 32 | url=__url__, 33 | 34 | description=__description__, 35 | long_description=README, 36 | license=__license__, 37 | 38 | author=__author__, 39 | author_email=__author_email__, 40 | 41 | packages=['webapi'], 42 | include_package_data=True, 43 | zip_safe=False, 44 | package_data = __pkg_data__, 45 | 46 | install_requires=[], 47 | scripts=SCRIPTS, 48 | 49 | classifiers=[ 50 | # As in https://pypi.python.org/pypi?:action=list_classifiers 51 | 'Development Status :: 4 - Beta', 52 | 'Operating System :: OS Independent', 53 | 'Programming Language :: Python', 54 | 'Programming Language :: Python :: 3', 55 | 'Programming Language :: Python :: 3.5', 56 | 'Programming Language :: Python :: 3.6', 57 | 'Programming Language :: Python :: 3.7', 58 | 'License :: OSI Approved :: BSD License', 59 | 'Environment :: Plugins', 60 | 'Intended Audience :: End Users/Desktop', 61 | ], 62 | 63 | entry_points=""" 64 | [deluge.plugin.core] 65 | %s = %s:CorePlugin 66 | [deluge.plugin.gtk3ui] 67 | %s = %s:Gtk3UIPlugin 68 | [deluge.plugin.web] 69 | %s = %s:WebUIPlugin 70 | """ % ((__plugin_name__, __plugin_name__.lower())*3) 71 | ) 72 | -------------------------------------------------------------------------------- /webapi/__init__.py: -------------------------------------------------------------------------------- 1 | VERSION = (0, 4, 0) 2 | 3 | 4 | try: 5 | from deluge.plugins.init import PluginInitBase 6 | 7 | class CorePlugin(PluginInitBase): 8 | def __init__(self, plugin_name): 9 | from .core import Core as _plugin_cls 10 | self._plugin_cls = _plugin_cls 11 | super(CorePlugin, self).__init__(plugin_name) 12 | 13 | class Gtk3UIPlugin(PluginInitBase): 14 | def __init__(self, plugin_name): 15 | from .gtk3ui import Gtk3UI as _plugin_cls 16 | self._plugin_cls = _plugin_cls 17 | super(Gtk3UIPlugin, self).__init__(plugin_name) 18 | 19 | class WebUIPlugin(PluginInitBase): 20 | def __init__(self, plugin_name): 21 | from .webui import WebUI as _plugin_cls 22 | self._plugin_cls = _plugin_cls 23 | super(WebUIPlugin, self).__init__(plugin_name) 24 | 25 | 26 | except ImportError: 27 | # That's what we do when this import prevents docs from being built. 28 | pass 29 | -------------------------------------------------------------------------------- /webapi/common.py: -------------------------------------------------------------------------------- 1 | import pkg_resources, os 2 | 3 | def get_resource(filename): 4 | return pkg_resources.resource_filename('webapi', os.path.join('data', filename)) 5 | -------------------------------------------------------------------------------- /webapi/core.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import deluge.configmanager 4 | from deluge import component 5 | from deluge.common import get_version 6 | from deluge.core.rpcserver import export 7 | from deluge.plugins.pluginbase import CorePluginBase 8 | from twisted.web import http, server 9 | from packaging import version 10 | 11 | LOGGER = logging.getLogger(__name__) 12 | 13 | DEFAULT_PREFS = { 14 | 'enable_cors': False, 15 | 'allowed_origin': [], 16 | } 17 | 18 | # twisted uses byte strings in deluge version 2.1.0 onward 19 | use_bytes = version.parse(get_version()) >= version.parse('2.1.0') 20 | 21 | class Core(CorePluginBase): 22 | 23 | def enable(self): 24 | LOGGER.info('Enabling WebAPI plugin CORE ...') 25 | 26 | self.patched = False 27 | self.config = deluge.configmanager.ConfigManager('webapi.conf', DEFAULT_PREFS) 28 | 29 | if self.config['enable_cors']: 30 | self.patch_web_ui() 31 | 32 | def disable(self): 33 | LOGGER.info('Disabling WebAPI plugin CORE ...') 34 | 35 | self.config.save() 36 | 37 | @export 38 | def set_config(self, config): 39 | """sets the config dictionary""" 40 | 41 | for key in config.keys(): 42 | self.config[key] = config[key] 43 | 44 | self.config.save() 45 | 46 | if self.config['enable_cors']: 47 | self.patch_web_ui() 48 | 49 | elif not self.config['enable_cors']: 50 | self.unpatch_web_ui() 51 | 52 | @export 53 | def get_config(self): 54 | return self.config.config 55 | 56 | def patch_web_ui(self): 57 | 58 | if self.patched: 59 | return 60 | 61 | LOGGER.info('Patching webui for CORS...') 62 | 63 | cmp_json = component.get('JSON') 64 | 65 | self.old_render = cmp_json.render 66 | self.old_send_request = cmp_json._send_response 67 | cmp_json.render = self.render_patch 68 | cmp_json._send_response = self._send_response_patch 69 | 70 | self.patched = True 71 | 72 | def unpatch_web_ui(self): 73 | 74 | if not self.patched: 75 | return 76 | 77 | LOGGER.info('Unpatching webui for CORS...') 78 | 79 | cmp_json = component.get('JSON') 80 | cmp_json.render = self.old_render 81 | cmp_json._send_response = self.old_send_request 82 | 83 | self.patched = False 84 | 85 | def render_patch(self, request): 86 | 87 | if request.method != (b'OPTIONS' if use_bytes else 'OPTIONS'): 88 | return self.old_render(request) 89 | 90 | request.setResponseCode(http.OK) 91 | origin = request.getHeader('Origin') 92 | 93 | if origin in self.config['allowed_origin']: 94 | request.setHeader('Access-Control-Allow-Origin', origin) 95 | request.setHeader('Access-Control-Allow-Headers', 'content-type') 96 | request.setHeader('Access-Control-Allow-Methods', 'POST') 97 | request.setHeader('Access-Control-Allow-Credentials', 'true') 98 | 99 | request.write(b'' if use_bytes else '') 100 | request.finish() 101 | return server.NOT_DONE_YET 102 | 103 | def _send_response_patch(self, request, response): 104 | 105 | if request._disconnected: 106 | return '' 107 | 108 | origin = request.getHeader('Origin') 109 | 110 | if origin in self.config['allowed_origin']: 111 | request.setHeader('Access-Control-Allow-Origin', origin) 112 | request.setHeader('Access-Control-Allow-Credentials', 'true') 113 | 114 | return self.old_send_request(request, response) 115 | -------------------------------------------------------------------------------- /webapi/data/config.ui: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | False 7 | 8 | 9 | True 10 | False 11 | 12 | 13 | True 14 | False 15 | 16 | 17 | enable CORS (cross-origin request) 18 | 247 19 | 80 20 | True 21 | True 22 | False 23 | False 24 | True 25 | 26 | 27 | 18 28 | 29 | 30 | 31 | 32 | 152 33 | 21 34 | True 35 | False 36 | 0 37 | 0 38 | Allowed domain name : 39 | 40 | 41 | 19 42 | 60 43 | 44 | 45 | 46 | 47 | 153 48 | 27 49 | True 50 | True 51 | 52 | False 53 | False 54 | True 55 | True 56 | 57 | 58 | 67 59 | 286 60 | 61 | 62 | 63 | 64 | Add 65 | 49 66 | 27 67 | True 68 | True 69 | True 70 | False 71 | 72 | 73 | 16 74 | 286 75 | 76 | 77 | 78 | 79 | 263 80 | 194 81 | True 82 | True 83 | 84 | 85 | 16 86 | 84 87 | 88 | 89 | 90 | 91 | 356 92 | 197 93 | True 94 | True 95 | automatic 96 | automatic 97 | 98 | 99 | 100 | 101 | 102 | 16 103 | 81 104 | 105 | 106 | 107 | 108 | Remove 109 | 69 110 | 27 111 | True 112 | True 113 | True 114 | False 115 | 116 | 117 | 221 118 | 286 119 | 120 | 121 | 122 | 123 | Remove all 124 | 82 125 | 27 126 | True 127 | True 128 | True 129 | False 130 | 131 | 132 | 290 133 | 286 134 | 135 | 136 | 137 | 138 | True 139 | True 140 | 0 141 | 142 | 143 | 144 | 145 | 146 | 147 | -------------------------------------------------------------------------------- /webapi/data/webapi.js: -------------------------------------------------------------------------------- 1 | 2 | WebApiPanel = Ext.extend(Ext.form.FormPanel, { 3 | 4 | 5 | constructor: function(config) { 6 | 7 | config = Ext.apply({ 8 | title: _('WebAPI'), 9 | border: false, 10 | labelWidth: 10, 11 | autoHeight: true 12 | }, config); 13 | 14 | WebApiPanel.superclass.constructor.call(this, config); 15 | }, 16 | initComponent: function() { 17 | WebApiPanel.superclass.initComponent.call(this); 18 | this.opts = new Deluge.OptionsManager(); 19 | 20 | var fieldset = this.add({ 21 | xtype: 'fieldset', 22 | title: _('WebAPI Settings'), 23 | defaultType: 'checkbox', 24 | autoHeight: true 25 | }); 26 | 27 | this.opts.bind('enable_cors', fieldset.add({ 28 | name: 'enable_cors', 29 | id: 'enable_cors', 30 | height: 22, 31 | fieldLabel: '', 32 | labelSeparator: '', 33 | boxLabel: _('Enable CORS (cross-origin request)') 34 | })); 35 | 36 | this.list = this.add({ 37 | xtype: 'listview', 38 | height: 150, 39 | store: new Ext.data.ArrayStore({ 40 | fields: [ 41 | { name: 'domain', mapping: 0 } 42 | ] 43 | }), 44 | columns: [{ 45 | id: 'domain', 46 | header: _('Allowed domain'), 47 | width: 1, 48 | sortable: true, 49 | dataIndex: 'domain' 50 | }], 51 | singleSelect: true, 52 | autoExpandColumn: 'domain', 53 | listeners: { 54 | selectionchange: { fn: this.onDomainSelect, scope: this } 55 | } 56 | }); 57 | 58 | this.panel = this.add({ 59 | region: 'center', 60 | autoScroll: true, 61 | items: [this.list] 62 | }); 63 | 64 | this.domain_name = this.opts.bind('domain_name', fieldset.add({ 65 | fieldLabel: '', 66 | xtype: 'textfield', 67 | anchor: '50%', 68 | name: 'domain_name', 69 | id: 'domain_name', 70 | autoWidth: true, 71 | value: '' 72 | })); 73 | 74 | this.toolbar = this.add({ 75 | fieldLabel: _(''), 76 | name: 'list_toolbar', 77 | xtype: 'container', 78 | layout: 'hbox', 79 | items: [ 80 | { 81 | xtype: 'button', 82 | text: 'Add' 83 | }, 84 | this.domain_name, 85 | { 86 | xtype: 'button', 87 | text: 'Remove' 88 | }, 89 | { 90 | xtype: 'button', 91 | text: 'Remove all' 92 | } 93 | ] 94 | }); 95 | 96 | this.toolbar.getComponent(0).setHandler(this.addDomain, this); 97 | this.toolbar.getComponent(2).setHandler(this.removeDomain, this); 98 | this.toolbar.getComponent(3).setHandler(this.removeAllDomain, this); 99 | 100 | deluge.preferences.on('show', this.onPreferencesShow, this); 101 | }, 102 | 103 | removeDomain: function() { 104 | if (!this.selectedDomain) return; 105 | var index = this.list.getStore().find('domain', this.selectedDomain); 106 | if (index == -1) return; 107 | this.list.getStore().removeAt(index); 108 | index = this.allowedDomains.indexOf(this.selectedDomain); 109 | if (index !== -1) this.allowedDomains.splice(index, 1); 110 | this.selectedDomain = false; 111 | }, 112 | 113 | removeAllDomain: function() { 114 | this.list.getStore().removeAll(); 115 | this.allowedDomains = []; 116 | this.selectedDomain = false; 117 | }, 118 | 119 | onDomainSelect: function (dv, selections) { 120 | if (selections.length === 0) return; 121 | var r = dv.getRecords(selections)[0]; 122 | this.selectedDomain = r.get('domain'); 123 | }, 124 | 125 | addDomain: function() { 126 | var changed = this.opts.getDirty(); 127 | if (!Ext.isObjectEmpty(changed)) { 128 | if (!Ext.isEmpty(changed['domain_name'])) { 129 | changed['domain_name'] = changed['domain_name']; 130 | this.allowedDomains.push(changed['domain_name']); 131 | this.updateDomainsGrid(); 132 | } 133 | } 134 | }, 135 | 136 | updateDomainsGrid: function () { 137 | var Domains = []; 138 | Ext.each(this.allowedDomains, function (domain) { 139 | Domains.push([domain]); 140 | }, this); 141 | this.list.getStore().loadData(Domains); 142 | }, 143 | 144 | onPreferencesShow: function () { 145 | deluge.client.webapi.get_config({ 146 | success: function (config) { 147 | if (!Ext.isEmpty(config['enable_cors'])) { 148 | config['enable_cors'] = config['enable_cors']; 149 | } 150 | if (!Ext.isEmpty(config['allowed_origin'])) { 151 | config['allowed_origin'] = config['allowed_origin']; 152 | } 153 | this.allowedDomains = config['allowed_origin']; 154 | this.updateDomainsGrid(); 155 | this.opts.set(config); 156 | }, 157 | scope: this 158 | }); 159 | }, 160 | 161 | onApply: function(e) { 162 | var changed = this.opts.getDirty(); 163 | if (!Ext.isObjectEmpty(changed)) { 164 | if (!Ext.isEmpty(changed['enable_cors'])) { 165 | changed['enable_cors'] = changed['enable_cors']; 166 | } 167 | deluge.client.webapi.set_config(changed, { 168 | success: this.onSetConfig, 169 | scope: this 170 | }); 171 | } 172 | var config = {}; 173 | config['allowed_origin'] = this.allowedDomains; 174 | console.log(config); 175 | deluge.client.webapi.set_config(config); 176 | }, 177 | 178 | onSetConfig: function() { 179 | this.opts.commit(); 180 | } 181 | 182 | }); 183 | 184 | 185 | WebApiPlugin = Ext.extend(Deluge.Plugin, { 186 | 187 | name: 'WebAPI', 188 | 189 | onDisable: function() { 190 | deluge.preferences.removePage(this.prefsPage); 191 | }, 192 | 193 | onEnable: function() { 194 | this.prefsPage = deluge.preferences.addPage(new WebApiPanel()); 195 | } 196 | }); 197 | 198 | Deluge.registerPlugin('WebAPI', WebApiPlugin); -------------------------------------------------------------------------------- /webapi/gtk3ui.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from gi.repository import Gtk 4 | from deluge import component 5 | from deluge.plugins.pluginbase import Gtk3PluginBase 6 | from deluge.ui.client import client 7 | 8 | from .common import get_resource 9 | 10 | LOGGER = logging.getLogger(__name__) 11 | 12 | 13 | class Gtk3UI(Gtk3PluginBase): 14 | 15 | plugin_id = 'WebAPI' 16 | 17 | def enable(self): 18 | """Triggers when plugin is enabled.""" 19 | LOGGER.info('Enabling WebAPI plugin GTK ...') 20 | 21 | self.builder = Gtk.Builder.new_from_file(get_resource("config.ui")) 22 | 23 | component.get('Preferences').add_page('WebAPI', self.builder.get_object('prefs_box')) 24 | component.get('PluginManager').register_hook('on_apply_prefs', self.on_apply_prefs) 25 | component.get('PluginManager').register_hook('on_show_prefs', self.on_show_prefs) 26 | 27 | self.builder.get_object('add_button').connect('clicked', self.add_domain) 28 | self.builder.get_object('remove_button').connect('clicked', self.remove_domain) 29 | self.builder.get_object('remove_all_button').connect('clicked', self.remove_all_domain) 30 | self.create_listview() 31 | 32 | def disable(self): 33 | """Triggers when plugin is disabled.""" 34 | LOGGER.info('Disabling WebAPI plugin GTK ...') 35 | 36 | component.get('Preferences').remove_page('WebAPI') 37 | component.get('PluginManager').deregister_hook('on_apply_prefs', self.on_apply_prefs) 38 | component.get('PluginManager').deregister_hook('on_show_prefs', self.on_show_prefs) 39 | 40 | def on_apply_prefs(self): 41 | """Triggers when plugin prefs are apply.""" 42 | config = {} 43 | if self.builder.get_object('enable_cors').get_active(): 44 | config['enable_cors'] = True 45 | else: 46 | config['enable_cors'] = False 47 | 48 | config['allowed_origin'] = [] 49 | for i, value in enumerate(self.model): 50 | item = self.model.get_iter(i) 51 | config['allowed_origin'].append(self.model[item][0]) 52 | 53 | client.webapi.set_config(config) 54 | 55 | def on_show_prefs(self): 56 | """Triggers when plugin prefs are show.""" 57 | client.webapi.get_config().addCallback(self.cb_get_config) 58 | 59 | def cb_get_config(self, config): 60 | """callback for on show_prefs""" 61 | self.builder.get_object('enable_cors').set_active(config['enable_cors']) 62 | self.remove_all_domain() 63 | for domain in config['allowed_origin']: 64 | self.model.append([domain]) 65 | 66 | def create_listview(self): 67 | self.model = Gtk.ListStore(str) 68 | self.list = self.builder.get_object('listview_allowed_domains') 69 | self.list.set_model(self.model) 70 | 71 | parent = self.list.get_parent() 72 | parent.remove(self.list) 73 | self.scrollTree = self.builder.get_object('scrolledwindow_allowed_domains') 74 | self.scrollTree.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC) 75 | self.scrollTree.add(self.list) 76 | 77 | column = Gtk.TreeViewColumn('domain', Gtk.CellRendererText(), text=0) 78 | column.set_clickable(True) 79 | column.set_resizable(True) 80 | self.list.append_column(column) 81 | 82 | self.selection = self.list.get_selection() 83 | 84 | def add_domain(self, button): 85 | domain = self.builder.get_object('new_domain').get_text() 86 | self.model.append([domain]) 87 | 88 | def remove_domain(self, button): 89 | # if there is still an entry in the model 90 | if len(self.model) != 0: 91 | # get the selection 92 | (model, item) = self.selection.get_selected() 93 | if item is not None: 94 | self.model.remove(item) 95 | 96 | def remove_all_domain(self, button=None): 97 | for i, value in enumerate(self.model): 98 | item = self.model.get_iter(0) 99 | self.model.remove(item) 100 | -------------------------------------------------------------------------------- /webapi/test.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from os import environ 3 | 4 | PASSWORD = environ.get('WEBAPI_PASSWORD', '*****') 5 | COOKIES = None 6 | REQUEST_ID = 0 7 | 8 | 9 | def send_request(method, params=None): 10 | global REQUEST_ID 11 | global COOKIES 12 | REQUEST_ID += 1 13 | 14 | try: 15 | 16 | response = requests.post( 17 | 'http://localhost:8112/json', 18 | json={'id': REQUEST_ID, 'method': method, 'params': params or []}, 19 | cookies=COOKIES) 20 | 21 | except requests.exceptions.ConnectionError: 22 | raise Exception('WebUI seems to be unavailable. Run deluge-web or enable WebUI plugin using other thin client.') 23 | 24 | data = response.json() 25 | 26 | error = data.get('error') 27 | 28 | if error: 29 | msg = error['message'] 30 | 31 | if msg == 'Unknown method': 32 | msg += '. Check WebAPI is enabled.' 33 | 34 | raise Exception('API response: %s' % msg) 35 | 36 | COOKIES = response.cookies 37 | 38 | return data['result'] 39 | 40 | 41 | assert send_request('auth.login', [PASSWORD]), 'Unable to log in. Check password.' 42 | 43 | version_number = send_request('webapi.get_api_version') 44 | assert version_number 45 | 46 | print('WebAPI version: %s' % version_number) 47 | 48 | print('Success') 49 | -------------------------------------------------------------------------------- /webapi/webui.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from deluge import component, common 4 | from deluge.plugins.pluginbase import WebPluginBase 5 | from deluge.ui.client import client 6 | from deluge.ui.web.json_api import export as export_api 7 | from twisted.internet.defer import Deferred 8 | 9 | from .common import get_resource 10 | 11 | LOGGER = logging.getLogger(__name__) 12 | 13 | 14 | class WebUI(WebPluginBase): 15 | 16 | scripts = [get_resource('webapi.js')] 17 | 18 | def enable(self): 19 | """Triggers when plugin is enabled.""" 20 | LOGGER.info('Enabling WebAPI plugin WEB ...') 21 | 22 | def disable(self): 23 | """Triggers when plugin is disabled.""" 24 | LOGGER.info('Disabling WebAPI plugin WEB ...') 25 | 26 | @export_api 27 | def get_torrents(self, ids=None, params=None): 28 | """Returns information about all or a definite torrent. 29 | Returned information can be filtered by supplying wanted parameter names. 30 | 31 | """ 32 | 33 | if params is None: 34 | filter_fields = ['name', 'comment', 'hash', 'save_path'] 35 | else: 36 | if isinstance(params, list): 37 | filter_fields = params 38 | else: 39 | filter_fields = params.replace(" ","").split(",") 40 | 41 | proxy = component.get('SessionProxy') 42 | 43 | filter_dict = {} 44 | if ids is not None: 45 | filter_dict['id'] = set(ids).intersection(set(proxy.torrents.keys())) 46 | 47 | document = { 48 | 'torrents': [] 49 | } 50 | response = Deferred() 51 | 52 | deffered_torrents = proxy.get_torrents_status(filter_dict, filter_fields) 53 | 54 | def on_complete(torrents_dict): 55 | document['torrents'] = list(torrents_dict.values()) 56 | response.callback(document) 57 | deffered_torrents.addCallback(on_complete) 58 | 59 | return response 60 | 61 | @export_api 62 | def add_torrent(self, metainfo, options=None): 63 | """Adds a torrent with the given options. 64 | metainfo could either be base64 torrent data or a magnet link. 65 | 66 | Returns `torrent_id` string or None. 67 | 68 | Available options are listed in deluge.core.torrent.TorrentOptions. 69 | 70 | :rtype: None|str 71 | """ 72 | if options is None: 73 | options = {} 74 | 75 | coreconfig = component.get('CoreConfig') 76 | 77 | if 'download_location' not in options.keys(): 78 | options.update({'download_location': coreconfig.get("download_location")}) 79 | 80 | if common.is_magnet(metainfo): 81 | LOGGER.info('Adding torrent from magnet URI `%s` using options `%s` ...', metainfo, options) 82 | result = client.core.add_torrent_magnet(metainfo, options) 83 | 84 | else: 85 | LOGGER.info('Adding torrent from base64 string using options `%s` ...', options) 86 | result = client.core.add_torrent_file(None, metainfo, options) 87 | 88 | return result 89 | 90 | @export_api 91 | def remove_torrent(self, torrent_id, remove_data=False): 92 | """Removes a given torrent. Optionally can remove data.""" 93 | return client.core.remove_torrent(torrent_id, remove_data) 94 | 95 | @export_api 96 | def get_api_version(self): 97 | """Returns WebAPI plugin version.""" 98 | from webapi import VERSION 99 | return '.'.join(map(str, VERSION)) 100 | --------------------------------------------------------------------------------