├── .gitignore ├── LICENSE ├── README.rst ├── docs ├── Makefile ├── conf.py └── index.rst ├── requirements.txt ├── setup.py ├── tests ├── __init__.py └── tests.py └── ttrss ├── __init__.py ├── auth.py ├── client.py └── exceptions.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | test_data.py 3 | 4 | dist/ 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2013 Markus Wiik 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | 21 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ttrss-python - A Tiny Tiny RSS client library 2 | ============================================= 3 | 4 | Have you ever wanted to write a python application to interface with your Tiny Tiny RSS server? Read on! 5 | 6 | At a glance 7 | =========== 8 | Now with Python 3 support! 9 | 10 | Getting started is easy! Just type ``pip install ttrss-python`` in the virtualenv of your choice. 11 | 12 | Usage example: 13 | 14 | :: 15 | 16 | from ttrss.client import TTRClient 17 | client = TTRClient('http://url-to-rss-installation', 'username', 'super-secret-password', auto_login=True) 18 | cats = client.get_categories() 19 | cat = cats[0] 20 | cat.title 21 | u'News' 22 | feeds = cat.feeds() 23 | feed = feeds[0] 24 | feed.title 25 | u'MacRumors: Mac News and Rumors - All Stories' 26 | headlines = feed.headlines() 27 | # etc... 28 | 29 | More detailed documentation can be found at https://ttrss-python.readthedocs.org/en/latest/ 30 | 31 | Development 32 | =========== 33 | ttrss-python is still in early development and not yet feature complete. If there's a specific feature 34 | you'd like me to prioritize, feel free to submit an issue or a pull request. 35 | 36 | The source code is available at https://github.com/Vassius/ttrss-python 37 | 38 | Author 39 | ====== 40 | ttrss-python is written and maintained by Markus Wiik . 41 | 42 | Contribution & feedback 43 | ======================= 44 | Contributions are welcome! Submit a pull request, file a bug report or write some docs if you'd like. 45 | Feature requests and other kinds of feedback are also appreciated. 46 | 47 | License 48 | ======= 49 | ttrss-python is MIT licensed. See LICENSE for details. 50 | 51 | -------------------------------------------------------------------------------- /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 clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 18 | 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 " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 31 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 32 | @echo " text to make text files" 33 | @echo " man to make manual pages" 34 | @echo " texinfo to make Texinfo files" 35 | @echo " info to make Texinfo files and run them through makeinfo" 36 | @echo " gettext to make PO message catalogs" 37 | @echo " changes to make an overview of all changed/added/deprecated items" 38 | @echo " linkcheck to check all external links for integrity" 39 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 40 | 41 | clean: 42 | -rm -rf $(BUILDDIR)/* 43 | 44 | html: 45 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 46 | @echo 47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 48 | 49 | dirhtml: 50 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 51 | @echo 52 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 53 | 54 | singlehtml: 55 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 56 | @echo 57 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 58 | 59 | pickle: 60 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 61 | @echo 62 | @echo "Build finished; now you can process the pickle files." 63 | 64 | json: 65 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 66 | @echo 67 | @echo "Build finished; now you can process the JSON files." 68 | 69 | htmlhelp: 70 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 71 | @echo 72 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 73 | ".hhp project file in $(BUILDDIR)/htmlhelp." 74 | 75 | qthelp: 76 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 77 | @echo 78 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 79 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 80 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/ttrss-python.qhcp" 81 | @echo "To view the help file:" 82 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/ttrss-python.qhc" 83 | 84 | devhelp: 85 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 86 | @echo 87 | @echo "Build finished." 88 | @echo "To view the help file:" 89 | @echo "# mkdir -p $$HOME/.local/share/devhelp/ttrss-python" 90 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/ttrss-python" 91 | @echo "# devhelp" 92 | 93 | epub: 94 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 95 | @echo 96 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 97 | 98 | latex: 99 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 100 | @echo 101 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 102 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 103 | "(use \`make latexpdf' here to do that automatically)." 104 | 105 | latexpdf: 106 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 107 | @echo "Running LaTeX files through pdflatex..." 108 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 109 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 110 | 111 | text: 112 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 113 | @echo 114 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 115 | 116 | man: 117 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 118 | @echo 119 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 120 | 121 | texinfo: 122 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 123 | @echo 124 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 125 | @echo "Run \`make' in that directory to run these through makeinfo" \ 126 | "(use \`make info' here to do that automatically)." 127 | 128 | info: 129 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 130 | @echo "Running Texinfo files through makeinfo..." 131 | make -C $(BUILDDIR)/texinfo info 132 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 133 | 134 | gettext: 135 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 136 | @echo 137 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 138 | 139 | changes: 140 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 141 | @echo 142 | @echo "The overview file is in $(BUILDDIR)/changes." 143 | 144 | linkcheck: 145 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 146 | @echo 147 | @echo "Link check complete; look for any errors in the above output " \ 148 | "or in $(BUILDDIR)/linkcheck/output.txt." 149 | 150 | doctest: 151 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 152 | @echo "Testing of doctests in the sources finished, look at the " \ 153 | "results in $(BUILDDIR)/doctest/output.txt." 154 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # ttrss-python documentation build configuration file, created by 4 | # sphinx-quickstart on Wed Mar 27 09:06:50 2013. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os 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 | sys.path.insert(0, os.path.abspath('..')) 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', 'sphinx.ext.ifconfig'] 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'ttrss-python' 44 | copyright = u'2013, Markus Wiik' 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 = '0.4' 52 | # The full version, including alpha/beta/rc tags. 53 | release = '0.4' 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 = ['_build'] 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 = 'ttrss-pythondoc' 168 | 169 | 170 | # -- Options for LaTeX output -------------------------------------------------- 171 | 172 | latex_elements = { 173 | # The paper size ('letterpaper' or 'a4paper'). 174 | #'papersize': 'letterpaper', 175 | 176 | # The font size ('10pt', '11pt' or '12pt'). 177 | #'pointsize': '10pt', 178 | 179 | # Additional stuff for the LaTeX preamble. 180 | #'preamble': '', 181 | } 182 | 183 | # Grouping the document tree into LaTeX files. List of tuples 184 | # (source start file, target name, title, author, documentclass [howto/manual]). 185 | latex_documents = [ 186 | ('index', 'ttrss-python.tex', u'ttrss-python Documentation', 187 | u'Markus Wiik', 'manual'), 188 | ] 189 | 190 | # The name of an image file (relative to this directory) to place at the top of 191 | # the title page. 192 | #latex_logo = None 193 | 194 | # For "manual" documents, if this is true, then toplevel headings are parts, 195 | # not chapters. 196 | #latex_use_parts = False 197 | 198 | # If true, show page references after internal links. 199 | #latex_show_pagerefs = False 200 | 201 | # If true, show URL addresses after external links. 202 | #latex_show_urls = False 203 | 204 | # Documents to append as an appendix to all manuals. 205 | #latex_appendices = [] 206 | 207 | # If false, no module index is generated. 208 | #latex_domain_indices = True 209 | 210 | 211 | # -- Options for manual page output -------------------------------------------- 212 | 213 | # One entry per manual page. List of tuples 214 | # (source start file, name, description, authors, manual section). 215 | man_pages = [ 216 | ('index', 'ttrss-python', u'ttrss-python Documentation', 217 | [u'Markus Wiik'], 1) 218 | ] 219 | 220 | # If true, show URL addresses after external links. 221 | #man_show_urls = False 222 | 223 | 224 | # -- Options for Texinfo output ------------------------------------------------ 225 | 226 | # Grouping the document tree into Texinfo files. List of tuples 227 | # (source start file, target name, title, author, 228 | # dir menu entry, description, category) 229 | texinfo_documents = [ 230 | ('index', 'ttrss-python', u'ttrss-python Documentation', 231 | u'Markus Wiik', 'ttrss-python', 'One line description of project.', 232 | 'Miscellaneous'), 233 | ] 234 | 235 | # Documents to append as an appendix to all manuals. 236 | #texinfo_appendices = [] 237 | 238 | # If false, no module index is generated. 239 | #texinfo_domain_indices = True 240 | 241 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 242 | #texinfo_show_urls = 'footnote' 243 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. ttrss-python documentation master file, created by 2 | sphinx-quickstart on Wed Mar 27 09:06:50 2013. 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 ttrss-python's documentation! 7 | ======================================== 8 | 9 | .. toctree:: 10 | :maxdepth: 2 11 | 12 | ttrss-python is a light-weight client library for the JSON API of Tiny Tiny RSS. 13 | Handling JSON in Python can be quite a pain, so this library abstracts all that 14 | away to deliver Python object representations of categories, feeds and articles. 15 | Also, the specific calls and POST data sent to the server is handled automatically, 16 | so that you can focus on the stuff that matters to your frontend application. 17 | 18 | Sounds good so far? Great, let's get started! 19 | 20 | Installation 21 | ============ 22 | This package is available at PyPI, so the easiest way to install is by doing a 23 | ``pip install ttrss-python``. This will install the latest released version, as 24 | well as all dependencies. Currently, the only dependency is the awesome Python 25 | ``requests`` library for handling all the http requests. 26 | 27 | If you for some reason can't or don't want to use ``pip``, just download the 28 | tarball and run ``python setup.py install`` manually. 29 | 30 | It's highly recommended to use ``virtualenv`` for this (and any other for that 31 | matter!) installation. 32 | 33 | Basic usage 34 | =========== 35 | The first thing you need to do is instantiate a ``TTRClient``. The constructor 36 | requires three arguments; URL, your username and your password:: 37 | 38 | >>> from ttrss.client import TTRClient 39 | >>> client = TTRClient('http://url-to-tiny-tiny', 'username', 'super-secret-password') 40 | >>> client.login() 41 | 42 | If you want the client to login automatically, as well as automatically refresh an expired 43 | session cookie, you may supply the optional keyword argument ``auto_login=True``. Note 44 | that this may affect performance in a high-traffic client application, since it uses a 45 | response hook to check every server response for a ``NOT_LOGGED_IN`` message:: 46 | 47 | >>> client = TTRClient('http://url-to-tiny-tiny', 'username', 'super-secret-password', auto_login=True) 48 | 49 | If the URL has http authentication on top of ttrss authentication, it can be specified using the ``http_auth`` parameter:: 50 | 51 | >>> client = TTRClient('http://url-to-tiny-tiny', 'username', 'super-secret-password', http_auth=('http_username', 'http_password')) 52 | 53 | Refer to the API docs for details on how to retrieve objects from the server. 54 | 55 | Categories 56 | ---------- 57 | Category objects contain attributes describing the category, as well as a method to retrieve feeds 58 | contained in it. Assuming a category object called ``cat``:: 59 | 60 | >>> cat.title 61 | u'Example category' 62 | >>> cat.unread 63 | 20 64 | >>> cat.id 65 | 2 66 | 67 | To retrieve a list of feeds belonging to this category, simply type:: 68 | 69 | >>> cat.feeds() 70 | [, ] 71 | 72 | The ``feeds`` method accepts parameters as well. Please refer to the API docs for details. 73 | 74 | Feeds 75 | ===== 76 | Like category objects, feed objects contain metadata and a method to retrieve headlines:: 77 | 78 | >>> feed.title 79 | u'MacRumors: Mac News and Rumors - All Stories' 80 | >>> feed.last_updated 81 | datetime.datetime(2013, 3, 24, 21, 18, 29) 82 | >>> feed.unread 83 | 24 84 | >>> feed.feed_url 85 | u'http://feeds.macrumors.com/MacRumors-All' 86 | >>> feed.id 87 | 5 88 | >>> feed.headlines() 89 | [, ...] 90 | 91 | Headlines 92 | ========= 93 | Headlines are short versions of articles. They too include all useful metadata:: 94 | 95 | >>> headline.title 96 | u'Apple Acquires Indoor Mobile Location Positioning Firm WifiSLAM for $20 Million' 97 | >>> headline.excerpt 98 | u'The Wall Street Journal reports that Apple has acquired indoor location company WifiSLAM, paying aro…' 99 | >>> headline.link 100 | u'http://www.macrumors.com/2013/03/23/apple-acquires-indoor-mobile-location-positioning-firm-wifislam-for-20-million/' 101 | >>> headline.updated 102 | datetime.datetime(2013, 3, 24, 21, 18, 29) 103 | >>> headline.unread 104 | True 105 | >>> headline.tags 106 | [u'front page'] 107 | >>> headline.published 108 | True 109 | >>> headline.labels 110 | [] 111 | >>> headline.id 112 | 1 113 | >>> headline.feed_id 114 | u'5' 115 | 116 | To get the full article, simply type:: 117 | 118 | >>> headline.full_article() 119 | 120 | 121 | Articles 122 | ======== 123 | Article objects include all the useful information:: 124 | 125 | >>> article.link 126 | u'http://www.macrumors.com/2013/03/23/apple-acquires-indoor-mobile-location-positioning-firm-wifislam-for-20-million/' 127 | >>> article.title 128 | u'Apple Acquires Indoor Mobile Location Positioning Firm WifiSLAM for $20 Million' 129 | >>> article.updated 130 | datetime.datetime(2013, 3, 24, 21, 18, 29) 131 | >>> article.comments 132 | u'' 133 | >>> article.author 134 | u'Eric Slivka' 135 | >>> article.id 136 | 1 137 | >>> article.unread 138 | True 139 | >>> article.content 140 | u"Lots of text... " 141 | 142 | Article objects also include some useful methods for interaction:: 143 | 144 | >>> article.publish() # Publish to shared 145 | >>> article.toggle_unread() # Toggle unread status 146 | 147 | You may also refresh the information about an article with fresh data from the server. This is useful if 148 | you have a long-running script and interact with the server by other means while it's running:: 149 | 150 | >>> article.unread 151 | True 152 | # Mark the article as read in the web interface or some other client... 153 | >>> article.refresh_status() 154 | >>> article.unread 155 | False 156 | 157 | Development 158 | =========== 159 | This project is open source and MIT licensed. The source code is available at https://github.com/Vassius/ttrss-python 160 | 161 | Contributions 162 | ------------- 163 | Bugreports, feature requests and other feedback is very much appreciated, and best submitted in the GitHub project mentioned above. 164 | If you're a doer and want to patch something yourself - Awesome! Just fork my repo and submit a pull request. 165 | 166 | Author 167 | ------ 168 | ``ttrss-python`` is written and maintained by Markus Wiik 169 | 170 | API Documentation 171 | ================= 172 | 173 | This section will become more detailed over time as I add docstrings to the source code. 174 | 175 | :mod:`client` module 176 | -------------------- 177 | 178 | .. automodule:: ttrss.client 179 | :members: 180 | :undoc-members: 181 | :show-inheritance: 182 | 183 | 184 | Indices and tables 185 | ================== 186 | 187 | * :ref:`genindex` 188 | * :ref:`modindex` 189 | * :ref:`search` 190 | 191 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Jinja2==2.6 2 | Pygments==1.6 3 | Sphinx==1.1.3 4 | docutils==0.10 5 | pep8==1.4.5 6 | requests==1.1.0 7 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | with open('README.rst') as f: 4 | long_desc = f.read() 5 | 6 | setup( 7 | name='ttrss-python', 8 | version='0.5', 9 | description='A client library for the Tiny Tiny RSS web API', 10 | long_description=long_desc, 11 | url='https://github.com/Vassius/ttrss-python', 12 | author='Markus Wiik', 13 | author_email='vassius@gmail.com', 14 | packages=['ttrss'], 15 | package_data={'': ['README.rst']}, 16 | include_package_data=True, 17 | install_requires=['requests>=1.1.0'], 18 | provides=['ttrss'], 19 | classifiers=[ 20 | 'Development Status :: 4 - Beta', 21 | 'Intended Audience :: Developers', 22 | 'Intended Audience :: System Administrators', 23 | 'License :: OSI Approved :: MIT License', 24 | 'Operating System :: OS Independent', 25 | 'Programming Language :: Python :: 2.7', 26 | 'Topic :: Internet :: WWW/HTTP', 27 | ], 28 | ) 29 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vassius/ttrss-python/3d2d26dd3b74ee65bce190d15801aae755b1e2db/tests/__init__.py -------------------------------------------------------------------------------- /tests/tests.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | import time 3 | import unittest 4 | import requests 5 | import json 6 | import sys 7 | sys.path.insert(0, './') 8 | from ttrss.client import TTRClient, Category, Feed, Headline, Article 9 | from ttrss.exceptions import TTRNotLoggedIn, TTRAuthFailure 10 | 11 | from test_data import TTR_URL, TTR_USER, TTR_PASSWORD 12 | 13 | def get_ttr_client(): 14 | return TTRClient(TTR_URL, user=TTR_USER, password=TTR_PASSWORD, auto_login=True) 15 | 16 | def get_ttr_client_nologin(): 17 | s = TTRClient(TTR_URL) 18 | s.user = TTR_USER 19 | s.password = TTR_PASSWORD 20 | return s 21 | 22 | class TestRSSService(unittest.TestCase): 23 | 24 | def setUp(self): 25 | self.s = get_ttr_client_nologin() 26 | 27 | def test_session_existence(self): 28 | self.assertIsNotNone(self.s) 29 | 30 | def test_valid_url(self): 31 | r = requests.get(self.s.url) 32 | self.assertTrue(r.status_code == 200) 33 | 34 | def test_login(self): 35 | self.s.user 36 | self.s.password 37 | r = requests.post(self.s.url, data=json.dumps({'op': 'login', 'user': self.s.user, 'password': self.s.password})) 38 | data = json.loads(r.text) 39 | self.assertTrue(data['status'] == 0) 40 | 41 | class TestApi(unittest.TestCase): 42 | def setUp(self): 43 | self.ttr = get_ttr_client() 44 | 45 | def test_auto_login(self): 46 | r = self.ttr._get_json({'op': 'getVersion'}) 47 | self.assertTrue(r['status'] == 0) 48 | r = self.ttr._get_json({'op': 'isLoggedIn'}) 49 | self.assertIsInstance(r, dict) 50 | self.assertTrue(r['content']['status']) 51 | 52 | def test_logout(self): 53 | self.ttr.logout() 54 | r = self.ttr.logged_in() 55 | self.assertFalse(r) 56 | r = self.ttr._get_json({'op': 'isLoggedIn'}) 57 | self.assertIsInstance(r, dict) 58 | self.assertFalse(r['status']) 59 | self.assertRaises(TTRNotLoggedIn, self.ttr._get_json, {'op': 'getVersion'}) 60 | 61 | def test_manual_login(self): 62 | if self.ttr.logged_in(): 63 | self.ttr.logout() 64 | self.ttr.login() 65 | r = self.ttr._get_json({'op': 'getVersion'}) 66 | self.assertIsInstance(r, dict) 67 | self.assertTrue(r['status'] == 0) 68 | 69 | def test_login_error(self): 70 | user = self.ttr.user 71 | self.ttr.user = '' 72 | self.assertRaises(TTRAuthFailure, self.ttr.login) 73 | self.ttr.user = user 74 | 75 | def test_unread_count(self): 76 | r = self.ttr.get_unread_count() 77 | self.assertIsInstance(r, int) 78 | 79 | def test_update_daemon_running(self): 80 | r = self.ttr.update_daemon_running() 81 | self.assertTrue(r) 82 | 83 | class TestCategories(unittest.TestCase): 84 | def setUp(self): 85 | self.ttr = get_ttr_client_nologin() 86 | self.ttr.login() 87 | self.cat = self.ttr.get_categories() 88 | 89 | def test_get_categories(self): 90 | self.assertIsInstance(self.cat, list) 91 | self.assertTrue(len(self.cat) > 0) 92 | 93 | def test_category_object(self): 94 | c = self.cat[0] 95 | self.assertIsInstance(c, Category) 96 | self.assertTrue(c.unread > 0) 97 | c.title 98 | c.id 99 | 100 | def test_category_methods(self): 101 | c = self.cat[0] 102 | f = c.feeds() 103 | self.assertIsInstance(f, list) 104 | self.assertIsInstance(f[0], Feed) 105 | 106 | class TestFeeds(unittest.TestCase): 107 | def setUp(self): 108 | self.ttr = get_ttr_client_nologin() 109 | self.ttr.login() 110 | cat = self.ttr.get_categories()[-1] 111 | feeds = self.ttr.get_feeds(cat.id) 112 | self.feed = feeds[0] 113 | 114 | def test_get_feeds(self): 115 | feed = self.feed 116 | feed.id 117 | feed.title 118 | feed.unread 119 | self.assertIsInstance(feed.last_updated, datetime) 120 | 121 | def test_get_headlines(self): 122 | h = self.feed.headlines() 123 | self.assertIsInstance(h, list) 124 | self.assertTrue(len(h) > 1) 125 | self.assertIsInstance(h[0], Headline) 126 | h_limited = self.feed.headlines(limit=len(h)-1) 127 | self.assertEqual(1, len(h) - len(h_limited)) 128 | 129 | def test_get_feed_count(self): 130 | f = self.ttr.get_feed_count() 131 | self.assertIsInstance(f, int) 132 | 133 | def test_feed_catchup(self): 134 | self.assertTrue(self.feed.unread > 0) 135 | self.feed.catchup() 136 | cat = self.ttr.get_categories()[-1] 137 | feed = self.ttr.get_feeds(cat.id)[0] 138 | self.assertTrue(feed.unread == 0) 139 | 140 | def test_get_num_feeds(self): 141 | n = self.ttr.get_feed_count() 142 | self.assertTrue(n > 0) 143 | 144 | def test_subscribe_unsubscribe(self): 145 | f = self.ttr.get_feeds(cat_id=0) 146 | self.assertFalse(u'https://github.com/Vassius.atom' in [feed.feed_url for feed in f]) 147 | self.ttr.subscribe(u'https://github.com/Vassius.atom') 148 | f = self.ttr.get_feeds(cat_id=0) 149 | self.assertTrue(u'https://github.com/Vassius.atom' in [feed.feed_url for feed in f]) 150 | unsubscribe_id = None 151 | for feed in f: 152 | if feed.feed_url == u'https://github.com/Vassius.atom': 153 | unsubscribe_id = feed.id 154 | break 155 | self.ttr.unsubscribe(unsubscribe_id) 156 | f = self.ttr.get_feeds(cat_id=0) 157 | self.assertFalse(u'https://github.com/Vassius.atom' in [feed.feed_url for feed in f]) 158 | 159 | def tearDown(self): 160 | h = self.feed.headlines()[-1] 161 | self.ttr.mark_unread(h.id) 162 | 163 | 164 | class TestHeadlines(unittest.TestCase): 165 | def setUp(self): 166 | self.ttr = get_ttr_client_nologin() 167 | self.ttr.login() 168 | cat = self.ttr.get_categories()[-1] 169 | self.feed = self.ttr.get_feeds(cat.id)[0] 170 | self.h = self.ttr.get_headlines(self.feed.id) 171 | 172 | def test_get_headlines(self): 173 | self.assertIsInstance(self.h, list) 174 | h = self.h[0] 175 | self.assertIsInstance(h, Headline) 176 | self.assertTrue(len(self.h) > 1) 177 | limited_h = self.ttr.get_headlines(self.feed.id, limit=len(self.h)-1) 178 | self.assertEqual(len(self.h) - len(limited_h), 1) 179 | h.title 180 | 181 | def test_get_article(self): 182 | h = self.h[0] 183 | a = h.full_article() 184 | self.assertIsInstance(a, Article) 185 | self.assertEqual(a.id, h.id) 186 | 187 | 188 | class TestArticles(unittest.TestCase): 189 | def setUp(self): 190 | self.ttr = get_ttr_client_nologin() 191 | self.ttr.login() 192 | cat = self.ttr.get_categories()[-1] 193 | feed = self.ttr.get_feeds(cat.id)[0] 194 | self.headlines = feed.headlines() 195 | self.h = self.headlines[0] 196 | self.assertIsInstance(self.h, Headline) 197 | self.a = self.ttr.get_articles(self.h.id) 198 | 199 | def test_get_article(self): 200 | self.assertIsInstance(self.a, list) 201 | a = self.a[0] 202 | self.assertIsInstance(a, Article) 203 | self.assertEqual(a.id, self.h.id) 204 | 205 | def test_get_multiple_articles(self): 206 | h = self.headlines[-2:] 207 | a = self.ttr.get_articles("{0},{1}".format(h[0].id, h[1].id)) 208 | a2 = self.ttr.get_articles([h[0].id, h[1].id]) 209 | self.assertTrue(len(a) == 2) 210 | self.assertTrue(len(a2) == 2) 211 | 212 | def test_publish(self): 213 | self.assertIsInstance(self.a, list) 214 | a = self.a[0] 215 | a.publish() 216 | h = self.ttr.get_headlines(feed_id=-2) 217 | l = [headline.link for headline in h] 218 | self.assertIn(a.link, l) 219 | 220 | def test_toggle_unread(self): 221 | a = self.a[0] 222 | unread = a.unread 223 | a.toggle_unread() 224 | a.refresh_status() 225 | self.assertFalse(unread == a.unread) 226 | a.toggle_unread() 227 | a.refresh_status() 228 | self.assertTrue(unread == a.unread) 229 | 230 | def test_updated_timestamp(self): 231 | a = self.a[0] 232 | self.assertIsInstance(a.updated, datetime) 233 | 234 | 235 | class TestShare(unittest.TestCase): 236 | def setUp(self): 237 | self.ttr = get_ttr_client_nologin() 238 | self.ttr.login() 239 | 240 | def test_get_shared(self): 241 | h = self.ttr.get_headlines(feed_id=-2) 242 | self.assertIsInstance(h, list) 243 | self.assertIsInstance(h[0], Headline) 244 | 245 | def test_share_article(self): 246 | title = 'Testing publish' 247 | url = 'http://{0}.com'.format(time.time()) 248 | content = 'Test content' 249 | self.ttr.share_to_published(title, url, content) 250 | h = self.ttr.get_headlines(feed_id=-2) 251 | l = [headline.link for headline in h] 252 | self.assertIn(url, l) 253 | 254 | class TestUpdate(unittest.TestCase): 255 | def setUp(self): 256 | self.ttr = get_ttr_client_nologin() 257 | self.ttr.login() 258 | cat = self.ttr.get_categories()[1] 259 | feed = cat.feeds()[-1] 260 | self.article = feed.headlines()[-1].full_article() 261 | # self.article = self.ttr.get_articles()[-1] 262 | 263 | def test_mark_unread(self): 264 | if self.article.unread: 265 | self.ttr.mark_read(self.article.id) 266 | a = self.ttr.get_articles(self.article.id)[0] 267 | self.assertFalse(a.unread) 268 | else: 269 | self.ttr.mark_unread(self.article.id) 270 | a = self.ttr.get_articles(self.article.id)[0] 271 | self.assertTrue(a.unread) 272 | 273 | def test_toggle_unread(self): 274 | a = self.ttr.get_articles(self.article.id)[0] 275 | unread = a.unread 276 | self.ttr.toggle_unread(a.id) 277 | a.refresh_status() 278 | self.assertFalse(a.unread == unread) 279 | 280 | 281 | if __name__ == '__main__': 282 | unittest.main() 283 | 284 | 285 | -------------------------------------------------------------------------------- /ttrss/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vassius/ttrss-python/3d2d26dd3b74ee65bce190d15801aae755b1e2db/ttrss/__init__.py -------------------------------------------------------------------------------- /ttrss/auth.py: -------------------------------------------------------------------------------- 1 | from requests.auth import AuthBase 2 | import requests 3 | import json 4 | from ttrss.exceptions import raise_on_error 5 | 6 | 7 | class TTRAuth(AuthBase): 8 | def __init__(self, user, password, http_auth): 9 | self.user = user 10 | self.password = password 11 | self.http_auth = http_auth 12 | self.sid = None 13 | 14 | def response_hook(self, r, **kwargs): 15 | j = json.loads(r.text) 16 | if int(j['status']) == 0: 17 | return r 18 | 19 | self.sid = self._get_sid(r.request.url) 20 | 21 | r.request.deregister_hook('response', self.response_hook) 22 | j = json.loads(r.request.body) 23 | j.update({'sid': self.sid}) 24 | req = requests.Request('POST', r.request.url, auth=self.http_auth) 25 | req.data = json.dumps(j) 26 | _r = requests.Session().send(req.prepare()) 27 | raise_on_error(_r) 28 | 29 | return _r 30 | 31 | def __call__(self, r): 32 | r.register_hook('response', self.response_hook) 33 | 34 | data = json.loads(r.body) 35 | if 'sid' not in data: 36 | if self.sid is None: 37 | self.sid = self._get_sid(r.url) 38 | data.update({'sid': self.sid}) 39 | req = requests.Request('POST', r.url, auth=self.http_auth) 40 | req.data = json.dumps(data) 41 | return req.prepare() 42 | else: 43 | self.sid = data['sid'] 44 | return r 45 | 46 | def _get_sid(self, url): 47 | res = requests.post(url, auth=self.http_auth, data=json.dumps({ 48 | 'op': 'login', 49 | 'user': self.user, 50 | 'password': self.password 51 | })) 52 | raise_on_error(res) 53 | j = json.loads(res.text) 54 | return j['content']['session_id'] 55 | -------------------------------------------------------------------------------- /ttrss/client.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | import requests 3 | import json 4 | from ttrss.auth import TTRAuth 5 | from ttrss.exceptions import raise_on_error 6 | 7 | 8 | class TTRClient(object): 9 | """ 10 | This is the actual client interface to Tiny Tiny RSS. 11 | 12 | This object retains a http session with the needed session cookies. From 13 | the client you can fetch categories, feeds, headlines and articles, all 14 | represented by Python objects. You can also update modify articles and 15 | feeds on the server. 16 | """ 17 | def __init__(self, url, user=None, password=None, auto_login=False, http_auth=()): 18 | """ 19 | Instantiate a new client. 20 | 21 | :param url: The full URL to the Tiny Tiny RSS server, *without* the 22 | /api/ suffix. 23 | :param user: The username to use when logging in. 24 | :param password: The password for the user. 25 | :param auto_login: *Optional* Automatically login upon instantiation, 26 | and re-login 27 | when a session cookie expires. 28 | """ 29 | self.sid = None 30 | self.url = url + '/api/' 31 | self.user = user 32 | self.password = password 33 | self.http_auth = http_auth 34 | 35 | self._session = requests.Session() 36 | 37 | if auto_login: 38 | auth = TTRAuth(user, password, http_auth) 39 | self._session.auth = auth 40 | 41 | def login(self): 42 | """ 43 | Manually log in (i.e. request a session cookie) 44 | 45 | This method must be used if the client was not instantiated with 46 | ``auto_login=True`` 47 | """ 48 | r = self._get_json({ 49 | 'op': 'login', 50 | 'user': self.user, 51 | 'password': self.password 52 | }) 53 | self.sid = r['content']['session_id'] 54 | 55 | def logout(self): 56 | """ 57 | Log out. 58 | 59 | After logging out, ``login()`` must be used to gain a valid session 60 | again. Please note that logging out invalidates any automatic 61 | re-login even after logging back in. 62 | """ 63 | self._get_json({'op': 'logout'}) 64 | self._session.auth = None 65 | 66 | def logged_in(self): 67 | r = self._get_json({'op': 'isLoggedIn'}) 68 | return r['content']['status'] 69 | 70 | def _get_json(self, post_data): 71 | if post_data['op'] == 'login': 72 | data = {} 73 | else: 74 | data = {'sid': self.sid} 75 | data.update(post_data) 76 | r = self._session.post(self.url, auth=self.http_auth, data=json.dumps(data)) 77 | raise_on_error(r) 78 | return json.loads(r.text) 79 | 80 | def get_unread_count(self): 81 | """Get total number of unread articles""" 82 | r = self._get_json({'op': 'getUnread'}) 83 | return int(r['content']['unread']) 84 | 85 | def get_feed_count(self): 86 | """Get total number of subscribed feeds.""" 87 | r = self._get_json({'op': 'getCounters'}) 88 | for c in r['content']: 89 | if c['id'] == 'subscribed-feeds': 90 | return int(c['counter']) 91 | return None 92 | 93 | def get_categories( 94 | self, 95 | unread_only=False, 96 | enable_nested=False, 97 | include_empty=False): 98 | """ 99 | Get a list of all available categories 100 | 101 | :param unread_only: Only return categories containing unread articles. 102 | Defaults to ``False``. 103 | :param enable_nested: When enabled, traverse through sub-categories 104 | and return only the **topmost** categories in a flat list. 105 | Defaults to ``False``. 106 | :param include_empty: Include categories not containing any feeds. 107 | Defaults to ``False``. *Requires server version 1.7.6* 108 | """ 109 | r = self._get_json({ 110 | 'op': 'getCategories', 111 | 'unread_only': unread_only, 112 | 'enable_nested': enable_nested, 113 | 'include_empty': include_empty 114 | }) 115 | return [Category(cat, self) for cat in r['content']] 116 | 117 | def get_feeds( 118 | self, 119 | cat_id=-1, 120 | unread_only=False, 121 | limit=0, 122 | offset=0, 123 | include_nested=False): 124 | """ 125 | Get a list of feeds in a category. 126 | 127 | :param cat_id: Category id. This is available as the ``id`` property 128 | of a Category object. 129 | :param unread_only: *Optional* Include only feeds containing unread 130 | articles. Default is ``False``. 131 | :param limit: *Optional* Limit number of included feeds to ``limit``. 132 | Default is 0 (unlimited). 133 | :param offset: *Optional* Skip this number of feeds. Useful for 134 | pagination. Default is 0. 135 | :param include_nested: *Optional* Include child categories. Default 136 | is ``False``. 137 | """ 138 | r = self._get_json({ 139 | 'op': 'getFeeds', 140 | 'cat_id': cat_id, 141 | 'unread_only': unread_only, 142 | 'limit': limit, 143 | 'offset': offset, 144 | 'include_nested': include_nested 145 | }) 146 | return [Feed(feed, self) for feed in r['content']] 147 | 148 | def get_feed_tree(self, include_empty=False): 149 | """ 150 | Get entire feed tree as decoded json data. 151 | 152 | :param include_empty: *Optional* Include empty categories. Default is 153 | ``False``. 154 | """ 155 | r = self._get_json({ 156 | 'op': 'getFeedTree', 157 | 'include_empty': include_empty, 158 | }) 159 | return r['content'] 160 | 161 | def get_labels(self): 162 | """Get a list of configured labels""" 163 | r = self._get_json({'op': 'getLabels'}) 164 | return [Label(label, self) for label in r['content']] 165 | 166 | def get_headlines_for_label(self, label_id, **kwargs): 167 | """ 168 | Get headlines for specified label id. Supports the same kwargs 169 | as ``get_headlines``, except for ``feed_id`` of course. 170 | """ 171 | feed_id = -11 - int(label_id) 172 | return self.get_headlines(feed_id=feed_id, **kwargs) 173 | 174 | def get_headlines( 175 | self, 176 | feed_id=-4, 177 | limit=0, 178 | skip=0, 179 | is_cat=False, 180 | show_excerpt=True, 181 | show_content=False, 182 | view_mode=None, 183 | include_attachments=False, 184 | since_id=None, 185 | include_nested=True, 186 | order_by=None, 187 | excerpt_length=200): 188 | 189 | """ 190 | Get a list of headlines from a specified feed. 191 | 192 | :param feed_id: Feed id. This is available as the ``id`` property of 193 | a Feed object. Default is ``-4`` (all feeds). 194 | :param limit: Return no more than this number of headlines. Default is 195 | ``0`` (unlimited, though the server limits to 60). 196 | :param skip: Skip this number of headlines. Useful for pagination. 197 | Default is ``0``. 198 | :param is_cat: The feed_id is a category. Defaults to ``False``. 199 | :param show_excerpt: Include a short excerpt of the article. Defaults 200 | to ``True``. 201 | :param show_content: Include full article content. Defaults to 202 | ``False``. 203 | :param view_mode: (string = all_articles, unread, adaptive, marked, 204 | updated) 205 | :param include_attachments: include article attachments. Defaults to 206 | ``False``. 207 | :param since_id: Only include headlines newer than ``since_id``. 208 | :param include_nested: Include articles from child categories. 209 | Defaults to ``True``. 210 | :param order_by: Change the sort order. The default (``None``) sorts 211 | the newest items first. Alternative values are `"date_reverse"`, 212 | oldest first, and `"feed_dates"`, newest first ordered by feed date. 213 | :excerpt_length: Length of the except in character. 214 | Defaults is ``200``. 215 | """ 216 | r = self._get_json({ 217 | 'op': 'getHeadlines', 218 | 'feed_id': feed_id, 219 | 'limit': limit, 220 | 'skip': skip, 221 | 'is_cat': is_cat, 222 | 'show_excerpt': show_excerpt, 223 | 'show_content': show_content, 224 | 'view_mode': view_mode, 225 | 'include_attachments': include_attachments, 226 | 'since_id': since_id, 227 | 'include_nested': include_nested, 228 | 'order_by': order_by, 229 | 'excerpt_length': excerpt_length, 230 | }) 231 | return [Headline(hl, self) for hl in r['content']] 232 | 233 | def get_articles(self, article_id): 234 | """ 235 | Get a list of articles from article ids. 236 | 237 | :param article_id: A comma separated string or list of article ids to 238 | fetch, 239 | """ 240 | if isinstance(article_id, list): 241 | article_id = ",".join([str(i) for i in article_id]) 242 | r = self._get_json({'op': 'getArticle', 'article_id': article_id}) 243 | return [Article(article, self) for article in r['content']] 244 | 245 | def refresh_article(self, article): 246 | """ 247 | Update all properties of an article object with fresh information from 248 | the server. 249 | 250 | Please note that this method alters the original object and does not 251 | return a new one. 252 | 253 | :param article: The article to refresh. 254 | """ 255 | r = self._get_json({'op': 'getArticle', 'article_id': article.id}) 256 | article.__init__(r['content'][0], client=self) 257 | 258 | def share_to_published(self, title, url, content): 259 | """ 260 | Share an article to the *published* feed. 261 | 262 | :param title: Article title. 263 | :param url: Article url. 264 | :param content: Article content. 265 | """ 266 | r = self._get_json({ 267 | 'op': 'shareToPublished', 268 | 'title': title, 269 | 'url': url, 270 | 'content': content 271 | }) 272 | 273 | def assign_label(self, article_id, label_id): 274 | """ 275 | Assign an existing label to an article. 276 | 277 | :param article_id: Article ID. 278 | :param label_id: Label ID. 279 | """ 280 | if isinstance(article_id, list): 281 | article_id = ",".join([str(i) for i in article_id]) 282 | r = self._get_json({ 283 | 'op': 'setArticleLabel', 284 | 'article_ids': article_id, 285 | 'label_id': label_id, 286 | 'assign': 'true', 287 | }) 288 | 289 | def mark_unread(self, article_id): 290 | """ 291 | Mark an article as unread. 292 | 293 | :param article_id: List or comma separated string of IDs of articles 294 | to mark as unread. 295 | """ 296 | if isinstance(article_id, list): 297 | article_id = ",".join([str(i) for i in article_id]) 298 | r = self._get_json({ 299 | 'op': 'updateArticle', 300 | 'article_ids': article_id, 301 | 'mode': 1, 302 | 'field': 2 303 | }) 304 | 305 | def mark_read(self, article_id): 306 | """ 307 | Mark an article as read. 308 | 309 | :param article_id: List or comma separated string of IDs of articles 310 | to mark as read. 311 | """ 312 | if isinstance(article_id, list): 313 | article_id = ",".join([str(i) for i in article_id]) 314 | r = self._get_json({ 315 | 'op': 'updateArticle', 316 | 'article_ids': article_id, 317 | 'mode': 0, 318 | 'field': 2 319 | }) 320 | pass 321 | 322 | def set_note(self, article_id, note): 323 | """ 324 | Set the note text of an article. 325 | 326 | :param article_id: List or comma-separated string of IDs of articles 327 | to set the note text of. 328 | :param note: The text of the note 329 | """ 330 | if isinstance(article_id, list): 331 | article_id = ",".join([str(i) for i in article_id]) 332 | r = self._get_json({ 333 | 'op': 'updateArticle', 334 | 'article_ids': article_id, 335 | 'mode': 1, 336 | 'field': 3, 337 | 'data': note, 338 | }) 339 | 340 | def set_score(self, article_id, score): 341 | """ 342 | Set the score of an article. 343 | 344 | :param article_id: List or comma-separated string of IDs of articles 345 | of which the score is set. 346 | :param score: The numeric value of the score 347 | """ 348 | if isinstance(article_id, list): 349 | article_id = ",".join([str(i) for i in article_id]) 350 | r = self._get_json({ 351 | 'op': 'updateArticle', 352 | 'article_ids': article_id, 353 | 'mode': 1, 354 | 'field': 4, 355 | 'data': score, 356 | }) 357 | 358 | def mark_starred(self, article_id): 359 | """ 360 | Mark the article as starred. 361 | 362 | :param article_id: List or comma-separated string of IDs of articles 363 | to mark as starred. 364 | """ 365 | if isinstance(article_id, list): 366 | article_id = ",".join([str(i) for i in article_id]) 367 | r = self._get_json({ 368 | 'op': 'updateArticle', 369 | 'article_ids': article_id, 370 | 'mode': 1, 371 | 'field': 0, 372 | }) 373 | 374 | def toggle_starred(self, article_id): 375 | """ 376 | Toggle the starred status of an article. 377 | 378 | :param article_id: List or comma separated string of IDs of articles 379 | to toggle starred status. 380 | """ 381 | r= self._get_json({ 382 | 'op': 'updateArticle', 383 | 'article_ids': article_id, 384 | 'mode': 2, 385 | 'field': 0}) 386 | 387 | 388 | def toggle_unread(self, article_id): 389 | """ 390 | Toggle the unread status of an article. 391 | 392 | :param article_id: List or comma separated string of IDs of articles 393 | to toggle unread. 394 | """ 395 | if isinstance(article_id, list): 396 | article_id = ",".join([str(i) for i in article_id]) 397 | r = self._get_json({ 398 | 'op': 'updateArticle', 399 | 'article_ids': article_id, 400 | 'mode': 2, 401 | 'field': 2 402 | }) 403 | 404 | def catchup_feed(self, feed_id, is_cat=False): 405 | """ 406 | Attempt to mark all articles in specified feed as read. 407 | 408 | :param feed_id: id of the feed to catchup. 409 | :param is_cat: Specified feed is a category. Default is False. 410 | """ 411 | r = self._get_json({ 412 | 'op': 'catchupFeed', 413 | 'feed_id': feed_id, 414 | 'is_cat': is_cat 415 | }) 416 | 417 | def get_feed_count(self): 418 | """Return total number of feeds""" 419 | r = self._get_json({'op': 'getConfig'}) 420 | return int(r['content']['num_feeds']) 421 | 422 | def update_daemon_running(self): 423 | """Return ``True`` if update daemon is running, ``False`` otherwise.""" 424 | r = self._get_json({'op': 'getConfig'}) 425 | return r['content']['daemon_is_running'] 426 | 427 | def update_feed(self, feed_id): 428 | """ 429 | Update specified feed 430 | :param feed_id: id of the feed to update. 431 | 432 | """ 433 | r = self._get_json({ 434 | 'op': 'updateFeed', 435 | 'feed_id': feed_id 436 | }) 437 | 438 | def subscribe(self, feed_url, category_id=0, login=None, password=None): 439 | """Subscribe to specified feed. 440 | 441 | :param feed_url: URL to the feed to subscribe to. 442 | :param category_id: Place feed in the category with this ID. 443 | :param login: Login name for the feed, if any. 444 | :param password: Password for the feed, if any. 445 | """ 446 | 447 | r = self._get_json({ 448 | 'op': 'subscribeToFeed', 449 | 'feed_url': feed_url, 450 | 'category_id': category_id, 451 | 'login': login, 452 | 'password': password 453 | }) 454 | 455 | def unsubscribe(self, feed_id): 456 | """Unsubscribe to specified feed 457 | 458 | :param feed_id: ID of feed to unsubscribe. 459 | """ 460 | 461 | r = self._get_json({'op': 'unsubscribeFeed', 'feed_id': feed_id}) 462 | 463 | def get_pref(self, pref_name): 464 | """ 465 | Return preference value of the specified key. 466 | 467 | :param pref_name: Name of the preference 468 | """ 469 | r = self._get_json({'op': 'getPref', 'pref_name': pref_name}) 470 | return r['content']['value'] 471 | 472 | 473 | class RemoteObject(object): 474 | """ 475 | This is the base class for representing remote resources as Python objects. 476 | """ 477 | def __init__(self, attr, client=None): 478 | self._client = client 479 | for key, value in attr.items(): 480 | if key == 'id': 481 | value = int(value) 482 | self.__setattr__(key, value) 483 | 484 | 485 | class Category(RemoteObject): 486 | def feeds(self, **kwargs): 487 | """ 488 | Get a list of feeds for this category. 489 | 490 | :param unread_only: *Optional* Include only feeds containing unread 491 | articles. Default is ``False``. 492 | :param limit: *Optional* Limit number of included feeds to ``limit``. 493 | Default is 0 (unlimited). 494 | :param offset: *Optional* Skip this number of feeds. Useful for 495 | pagination. Default is 0. 496 | :param include_nested: *Optional* Include child categories. Default 497 | is ``False``. 498 | """ 499 | return self._client.get_feeds(cat_id=self.id, **kwargs) 500 | 501 | 502 | class Feed(RemoteObject): 503 | def __init__(self, attr, client): 504 | super(Feed, self).__init__(attr, client) 505 | try: 506 | self.last_updated = datetime.fromtimestamp(self.last_updated) 507 | except AttributeError: 508 | pass 509 | 510 | def catchup(self): 511 | """Mark this feed as read""" 512 | self._client.catchup_feed(self.id) 513 | 514 | def headlines(self, **kwargs): 515 | """ 516 | Get a list of headlines from a this feed. 517 | 518 | :param limit: Return no more than this number of headlines. Default is 519 | ``0`` (unlimited, though the server limits to 60). 520 | :param skip: Skip this number of headlines. Useful for pagination. 521 | Default is ``0``. 522 | :param show_excerpt: Include a short excerpt of the article. Defaults 523 | to ``True``. 524 | :param show_content: Include full article content. Defaults to 525 | ``False``. 526 | :param view_mode: (string = all_articles, unread, adaptive, marked, 527 | updated) 528 | :param include_attachments: include article attachments. Defaults to 529 | ``False``. 530 | :param since_id: Only include headlines newer than ``since_id``. 531 | :param include_nested: Include articles from child categories. 532 | Defaults to ``True``. 533 | """ 534 | return self._client.get_headlines(feed_id=self.id, **kwargs) 535 | 536 | 537 | class Label(RemoteObject): 538 | def __init__(self, attr, client): 539 | super(Label, self).__init__(attr, client) 540 | 541 | def headlines(self, **kwargs): 542 | """ 543 | Get a list of headlines for this label. Supports the same kwargs as 544 | ``Feed.headlines()`` 545 | """ 546 | return self._client.get_headlines_for_label(self.id) 547 | 548 | 549 | class Headline(RemoteObject): 550 | """This class represents Headline objects. A headline is a short version 551 | of an article. 552 | """ 553 | def __init__(self, attr, client): 554 | super(Headline, self).__init__(attr, client) 555 | try: 556 | self.updated = datetime.fromtimestamp(self.updated) 557 | except AttributeError: 558 | pass 559 | 560 | def full_article(self): 561 | """Get the full article corresponding to this headline""" 562 | r = self._client.get_articles(self.id) 563 | return r[0] 564 | 565 | 566 | class Article(RemoteObject): 567 | def __init__(self, attr, client): 568 | super(Article, self).__init__(attr, client) 569 | try: 570 | self.updated = datetime.fromtimestamp(self.updated) 571 | except AttributeError: 572 | pass 573 | 574 | def publish(self): 575 | """Share this article to published feed""" 576 | self._client.share_to_published(self.title, self.link, self.content) 577 | 578 | def refresh_status(self): 579 | """Refresh this object with new data fetched from the server.""" 580 | self._client.refresh_article(self) 581 | 582 | def toggle_unread(self): 583 | """Toggle unread status of this article""" 584 | self._client.toggle_unread(self.id) 585 | -------------------------------------------------------------------------------- /ttrss/exceptions.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | 4 | class TTRAuthFailure(Exception): 5 | pass 6 | 7 | 8 | class TTRNotLoggedIn(Exception): 9 | pass 10 | 11 | 12 | class TTRApiDisabled(Exception): 13 | pass 14 | 15 | 16 | def raise_on_error(r): 17 | j = json.loads(r.text) 18 | if int(j['status']) == 0: 19 | return 20 | 21 | error = j['content']['error'] 22 | 23 | if error == 'NOT_LOGGED_IN': 24 | raise TTRNotLoggedIn 25 | 26 | if error == 'LOGIN_ERROR': 27 | raise TTRAuthFailure 28 | 29 | if error == 'API_DISABLED': 30 | raise TTRApiDisabled 31 | --------------------------------------------------------------------------------