pax_global_header00006660000000000000000000000064142551205250014513gustar00rootroot0000000000000052 comment=79f6676cf2b760bf020acbeddcd94dc5a3e64fb9 mygpoclient-1.9/000077500000000000000000000000001425512052500137165ustar00rootroot00000000000000mygpoclient-1.9/.github/000077500000000000000000000000001425512052500152565ustar00rootroot00000000000000mygpoclient-1.9/.github/workflows/000077500000000000000000000000001425512052500173135ustar00rootroot00000000000000mygpoclient-1.9/.github/workflows/publish.yml000066400000000000000000000041121425512052500215020ustar00rootroot00000000000000--- name: test and publish on: [push, pull_request] jobs: test: name: run unit tests runs-on: ubuntu-latest if: >- github.event_name == 'push' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name strategy: matrix: python-version: ['2.7', '3.6', '3.8', '3.9', '3.10'] steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | pip install -r requirements-test.txt - name: Test run: make test distpublish: name: create sdist and wheel and publish runs-on: ubuntu-latest needs: test if: >- github.repository == 'gpodder/mygpoclient' && github.event_name == 'push' && ( startsWith(github.ref, 'refs/tags') || github.ref == 'refs/heads/master') steps: - uses: actions/checkout@v3 - name: Set up Python uses: actions/setup-python@v4 with: python-version: '3.10' - name: Install dependencies run: | python -m pip install --upgrade pip pip install build twine - name: patch unique version if: "!startsWith(github.ref, 'refs/tags')" run: | sed -i "s/\(__version__ = .*\)'/\1-dev${{ github.run_number }}'/" mygpoclient/__init__.py - name: dist run: | python3 -m build --sdist --wheel twine check dist/* - name: Publish package to TestPyPI uses: pypa/gh-action-pypi-publish@v1.5.0 with: print_hash: true user: __token__ password: ${{ secrets.TEST_PYPI_API_TOKEN }} repository_url: https://test.pypi.org/legacy/ - name: Publish package to PyPI if: startsWith(github.ref, 'refs/tags') uses: pypa/gh-action-pypi-publish@v1.5.0 with: print_hash: true user: __token__ password: ${{ secrets.PYPI_API_TOKEN }} mygpoclient-1.9/.gitignore000066400000000000000000000000651425512052500157070ustar00rootroot00000000000000/doc/_build __pycache__ *.pyc docs/ *~ *# /.coverage mygpoclient-1.9/AUTHORS000066400000000000000000000002151425512052500147640ustar00rootroot00000000000000Thomas Perl Stefan Kögl David Sepashvili Stefan Derkits mygpoclient-1.9/CONTRIBUTING.md000066400000000000000000000011131425512052500161430ustar00rootroot00000000000000# HARD DEPENDENCIES If you have a Python version lower than Python 2.6 (which already includes simplejson as the "json" module), you will need to install simplejson from - [simplejson](https://github.com/simplejson/simplejson) # OPTIONAL DEPENDENCIES If you want to run the UNIT TESTS ("make test"), you also need - [Nose](http://readthedocs.org/docs/nose/) - [MiniMock](http://pypi.python.org/pypi/MiniMock) - [Coverage](http://coverage.readthedocs.io/en/latest/) If you want to generate the API DOCS ("make docs"), you also need - [Epydoc](http://epydoc.sourceforge.net/) mygpoclient-1.9/COPYING000066400000000000000000001045131425512052500147550ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . mygpoclient-1.9/MANIFEST.in000066400000000000000000000001261425512052500154530ustar00rootroot00000000000000include AUTHORS include COPYING include CONTRIBUTING.md include NEWS include makefile mygpoclient-1.9/NEWS000066400000000000000000000023001425512052500144100ustar00rootroot00000000000000Sun, 25 Apr 2010 23:51:38 +0200 ------------------------------- You can use the "require_version" function in mygpoclient to require a minimum version of the mygpoclient library. The "require_version" function has been added in version 1.3, so you have to check (e.g. with hasattr) if mygpoclient has got a "require_version" attribute. You can then do the version check like this: if not hasattr(mygpoclient, 'require_version') or \ not mygpoclient.require_version('1.3'): # Show error message and tell user to upgrade to version 1.3 Fri, 23 Apr 2010 17:43:03 +0200 ------------------------------- The parameter signature for the EpisodeAction constructor has been updated. It now contains not only the optional "position" argument, but two new arguments as well. The order of these parameters is: started position total If one of "started" or "total" is set, "position" becomes mandatory. This means that the following combinations are now possible: None position position and started position and total position and started and total Also, the format has been changed. Instead of having a "HH:MM:SS" timestamp format, we now only accept integer values (the number of seconds). mygpoclient-1.9/README.md000066400000000000000000000013411425512052500151740ustar00rootroot00000000000000# The gpodder.net Client Library This library provides an easy and structured way to access the gpodder.net web services. In addition to subscription list synchronization and storage, the advanced API support allows to upload and download episode status changes. The source of this library is managed in a Git repository at - https://github.com/gpodder/mygpoclient Documentation can be read online at http://mygpoclient.readthedocs.io/ If you have any questions, please don't hesitate to contact the gPodder developers mailing list at - gpodder@freelists.org You can report bugs and problems that you find on GitHub at - https://github.com/gpodder/gpodder/issues Thank you for your interest in the mygpoclient library! mygpoclient-1.9/appveyor.yml000066400000000000000000000031561425512052500163130ustar00rootroot00000000000000environment: matrix: # For Python versions available on Appveyor, see # http://www.appveyor.com/docs/installed-software#python # The list here is complete (excluding Python 2.6, which # isn't covered by this document) at the time of writing. - PYTHON: "C:\\Python27" - PYTHON: "C:\\Python36" - PYTHON: "C:\\Python37" APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 - PYTHON: "C:\\Python38" APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 - PYTHON: "C:\\Python39" APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 - PYTHON: "C:\\Python310" APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 - PYTHON: "C:\\Python27-x64" DISTUTILS_USE_SDK: "1" - PYTHON: "C:\\Python36-x64" - PYTHON: "C:\\Python37-x64" APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 - PYTHON: "C:\\Python38-x64" APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 - PYTHON: "C:\\Python39-x64" APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 install: # Install dependencies - "%PYTHON%\\python.exe -m pip install -r requirements-test.txt" build: off test_script: # Put your test command here. # If you don't need to build C extensions on 64-bit Python 3.3 or 3.4, # you can remove "build.cmd" from the front of the command, as it's # only needed to support those cases. # Note that you must use the environment variable %PYTHON% to refer to # the interpreter you're using - Appveyor does not do anything special # to put the Python evrsion you want to use on PATH. - "%PYTHON%\\python.exe -m pytest" after_test: # Do coverage report. # - "coverall" mygpoclient-1.9/bin/000077500000000000000000000000001425512052500144665ustar00rootroot00000000000000mygpoclient-1.9/bin/mygpo-bpsync000077500000000000000000000047061425512052500170520ustar00rootroot00000000000000#!/usr/bin/python # BashPodder <-> gpodder.net sync client # Copyright (c) 2010-04-02 Thomas Perl # Licensed under the same terms as the "mygpoclient" library # See: http://thp.io/2010/mygpoclient/ from __future__ import print_function import mygpoclient from mygpoclient import simple import os import sys class BPSync(object): def __init__(self, filename, root_url=mygpoclient.ROOT_URL, device='bp'): self.filename = filename self.device = device username = os.environ['MYGPO_USERNAME'] password = os.environ['MYGPO_PASSWORD'] root_url = os.environ.get('MYGPO_HOSTNAME', root_url) self.client = simple.SimpleClient(username, password, root_url) def put(self): lines = open(self.filename).read().strip().splitlines() podcasts = [line.strip() for line in lines if line.strip()] self.client.put_subscriptions(self.device, podcasts) def get(self): podcasts = self.client.get_subscriptions(self.device) open(self.filename, 'w').write('\n'.join(podcasts + [''])) def usage(s=None): print(""" Usage: %s (put|get) [device-id] e.g %s put ........ Upload bp.conf as device "bp" %s get ........ Download subscriptions for device "bp" %s get mydev .. Download subscriptions for device "mydev" The following environment variables need to be set: MYGPO_USERNAME .. Username for the web service MYGPO_PASSWORD .. Password for the web service The following environment variables are optional: BPSYNC_BP_CONF .. Path to your bp.conf file MYGPO_HOSTNAME .. Host or URL of the web service to use """ % ((os.path.basename(sys.argv[0]),) * 4), file=sys.stderr) if s is not None: print(s, file=sys.stderr) sys.exit(1) if __name__ == '__main__': if len(sys.argv) not in (2, 3): usage('Wrong parameter count') if 'MYGPO_USERNAME' not in os.environ or \ 'MYGPO_PASSWORD' not in os.environ: usage('MYGPO_USERNAME or MYGPO_PASSWORD not set!') filename = os.environ.get('BPSYNC_BP_CONF', 'bp.conf') if not os.path.exists(filename): usage('File not found: ' + filename) command = sys.argv[1] if len(sys.argv) == 3: client = BPSync(filename, device=sys.argv[2]) else: client = BPSync(filename) if command == 'put': client.put() elif command == 'get': client.get() else: usage('Unknown command') mygpoclient-1.9/bin/mygpo-list-devices000077500000000000000000000033161425512052500201430ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- # gpodder.net API Client # Copyright (C) 2009-2013 Thomas Perl and the gPodder Team # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from __future__ import print_function import sys import getpass import mygpoclient from mygpoclient import api def usage(): print(""" Usage: python %s {username} [host_or_url] """ % (sys.argv[0],), file=sys.stderr) sys.exit(1) if __name__ == '__main__': # Use the default url if not specified if len(sys.argv) == 2: sys.argv.append(mygpoclient.ROOT_URL) # Check for valid arguments if len(sys.argv) != 3: usage() # Split arguments in local variables progname, username, root_url = sys.argv # Read password from the terminal password = getpass.getpass("%s@%s's password: " % (username, root_url)) # Create the client object with username/password/root_url set client = api.MygPodderClient(username, password, root_url) for device in client.get_devices(): print(device) for podcast in client.get_subscriptions(device): print(' ' + podcast) print('-' * 50) mygpoclient-1.9/bin/mygpo-simple-client000077500000000000000000000042771425512052500203240ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- # gpodder.net API Client # Copyright (C) 2009-2013 Thomas Perl and the gPodder Team # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from __future__ import print_function import sys import getpass import mygpoclient from mygpoclient import simple def usage(): print(""" Usage: python %s {get|put} {username} {device_id} [host_or_url] """ % (sys.argv[0],), file=sys.stderr) sys.exit(1) if __name__ == '__main__': # Use the default url if not specified if len(sys.argv) == 4: sys.argv.append(mygpoclient.ROOT_URL) # Check for valid arguments if len(sys.argv) != 5: usage() # Split arguments in local variables progname, subcommand, username, device_id, root_url = sys.argv # Check for valid subcommand if subcommand not in ('get', 'put'): usage() # Read password from the terminal password = getpass.getpass("%s@%s's password: " % (username, root_url)) # Create the client object with username/password/root_url set client = simple.SimpleClient(username, password, root_url) if subcommand == 'get': # Get the URL list and print it, one per line print('\n'.join(client.get_subscriptions(device_id))) elif subcommand == 'put': # Read the URL list from standard input and upload it print('Enter podcast URLs, one per line.', file=sys.stderr) urls = sys.stdin.read().splitlines() if client.put_subscriptions(device_id, urls): print('Upload successful.', file=sys.stderr) else: print('Could not upload list.', file=sys.stderr) mygpoclient-1.9/doc/000077500000000000000000000000001425512052500144635ustar00rootroot00000000000000mygpoclient-1.9/doc/Makefile000066400000000000000000000011431425512052500161220ustar00rootroot00000000000000# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = python -msphinx SPHINXPROJ = mygpoclient SOURCEDIR = . BUILDDIR = _build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)mygpoclient-1.9/doc/conf.py000066400000000000000000000121311425512052500157600ustar00rootroot00000000000000#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # mygpoclient documentation build configuration file, created by # sphinx-quickstart on Wed Jul 19 18:38:58 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys sys.path.insert(0, os.path.abspath('..')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. project = 'mygpoclient' copyright = '2017, gPodder Team' author = 'gPodder Team' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.7' # The full version, including alpha/beta/rc tags. release = '1.7' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # This is required for the alabaster theme # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars html_sidebars = { '**': [ 'about.html', 'navigation.html', 'relations.html', # needs 'show_related': True theme option to display 'searchbox.html', 'donate.html', ] } # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = 'mygpoclientdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'mygpoclient.tex', 'mygpoclient Documentation', 'gPodder Team', 'manual'), ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'mygpoclient', 'mygpoclient Documentation', [author], 1) ] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'mygpoclient', 'mygpoclient Documentation', author, 'mygpoclient', 'One line description of project.', 'Miscellaneous'), ] mygpoclient-1.9/doc/index.rst000066400000000000000000000012701425512052500163240ustar00rootroot00000000000000 mygpoclient =========== A gpodder.net client in Python ------------------------------ This reference manual describes how to utilize the mygpoclient API Client Library to interface with the gpodder.net web service. The client library provides a well-tested implementation that adheres to the. This reference manual describes how to utilize the ``mygpoclient`` API Client Library to interface with the gpodder.net web service. The client library provides a well-tested implementation that adheres to the. .. toctree:: :maxdepth: 2 :caption: Contents: installation manual mygpoclient Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` mygpoclient-1.9/doc/installation.rst000066400000000000000000000043731425512052500177250ustar00rootroot00000000000000 Installation ============ This section describes how to obtain the source code and carry out basic tests to make sure your system has been set up correctly and all dependencies are fulfilled. Getting the code ---------------- The code for the client library is hosted at https://github.com/gpodder/mygpoclient/. You can download the latest version of the code by using the command: .. code-block:: bash git clone https://github.com/gpodder/mygpoclient.git or install it with ``pip``: .. code-block:: bash pip install mygpoclient Running Unit tests ------------------ To make sure that the library is working and all dependencies are installed, please install the dependencies listed in the `DEPENDENCIES `_ file. After that, you can easily run the unit tests that come with the library: .. code-block:: bash make test This will run all unit tests and doctests in the library. After the tests have been completed, you should get a summary with the test and code coverage statistics. The output should look like the following example if everything works (please note that the statement count could be different as development of the library continues): .. code-block:: bash Name Stmts Exec Cover Missing --------------------------------------------------- mygpoclient 5 5 100% mygpoclient.api 155 155 100% mygpoclient.http 52 52 100% mygpoclient.json 22 22 100% mygpoclient.locator 52 52 100% mygpoclient.simple 16 16 100% mygpoclient.util 20 20 100% --------------------------------------------------- TOTAL 322 322 100% --------------------------------------------------- Ran 81 tests in 4.987s Reading the module documentation -------------------------------- You can use the ``pydoc`` utility to read the documentation for the library. You probably want to use the following commands: .. code-block:: bash pydoc mygpoclient.simple pydoc mygpoclient.api If you want, you can let Epydoc create the API documentation in the source tree: .. code-block:: bash make docs The resulting documentation will be created in the ``docs/`` subdirectory. mygpoclient-1.9/doc/manual.rst000066400000000000000000000167171425512052500165060ustar00rootroot00000000000000Tutorial ======== This section gives a short how-to on how to use the library to interact with the web service. The Simple API client (``mygpoclient.simple.SimpleClient``) ----------------------------------------------------------- The :class:`.SimpleClient` class is the most basic way of interacting with the gpodder.net web service. You can use it to provide quick integration of an existing application or in cases where your client code has to be stateless. Please use the Advanced API client (which has a superset of :class:`.SimpleClient`'s features) for more advanced use cases. Importing the module ^^^^^^^^^^^^^^^^^^^^ Make sure that the :mod:`mygpoclient` package is in your ``sys.path``. You can set the ``PYTHONPATH`` environment variable to the Git checkout folder or add it to the ``sys.path`` list in Python. After that, you can import the ``simple`` module of the ``mygpoclient`` package: .. code-block:: python from mygpoclient import simple Creating a ``SimpleClient`` instance ------------------------------------ The client provides access to user-specific data, so you need to have the username and password of the user you want to authenticate as ready. Also, as gpodder.net is open source, and can potentially run on hosts different from gpodder.net, you can optionally provide the hostname. Let's suppose we want to authenticate as user ``john`` and the password ``secret`` to the default web service (that's '''gpodder.net'''). To create a client object, we would use the following code: .. code-block:: python client = simple.SimpleClient('john', 'secret') If you have the web service running on another host (for example on port ``1337`` on the local host or ``localhost``), you can specify the host and port as third argument to the :class:`.SimpleClient` constructor (but you still need to provide username and password in this case): .. code-block:: python client = simple.SimpleClient('john', 'secret', 'localhost:1337') Downloading subscription lists ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ You can download a list of podcast subscriptions with `SimpleClient.get_subscriptions(device_id)`. The given `device_id` has to exist for the logged-in user. If the device does not exist, a :class:`mygpoclient.http.NotFound` exception is raised. To download the subscription list of the device ``legacy``, use: .. code-block:: python subscriptions = client.get_subscriptions('legacy') The resulting list contains URLs of all the subscribed podcasts for this device: .. code-block:: python for url in subscriptions: print 'Subscribed to:', url Uploading subscription lists ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ As with the download function, you can also upload subscriptions. For this, you need to use the ``SimpleClient.put_subscriptions(device_id, urls)`` function. The function returns ``True`` if the upload operation was successful, or False otherwise. An example usage would be like this: .. code-block:: python subscriptions = [] subscriptions.append('http://example.org/episodes.rss') subscriptions.append('http://example.com/feeds/podcast.xml') client.put_subscriptions('gpodder-example-device', subscriptions) The existing list of subscriptions is always overwritten, and the user's subscription history will mark all podcasts that have been in the list before but have been removed from the uploaded subscription list as unsubscribed. Putting it all together (complete example) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Now that we have discussed the basics, we can write a simple but feature-complete command-line application for downloading and uploading subscription lists (this code can also be found in the source tree as `simple-client `_: .. literalinclude:: ../bin/mygpo-simple-client :language: python :linenos: The Advanced API client (``mygpoclient.api.MygPodderClient``) ------------------------------------------------------------- The :class:`.MygPodderClient` class inherits from :class:`.SimpleClient`, so you can use both the Simple API and Advanced API functionality with this class. Working with subscription lists ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Given a device ID, you can update the list of subscriptions via the :meth:`.update_subscriptions` method. You need to pass a device_id and two lists (one for the URLs that have been added and one for the URLs that have been removed) to update the subscriptions on the server, for example: .. code-block:: python from mygpoclient import api client = api.MygPodderClient('myusername', 'S3cr3tPassw0rd') to_add = ['http://lugradio.org/episodes.rss'] to_remove = ['http://example.org/episodes.rss', 'http://example.com/feed.xml'] result = client.update_subscriptions('abcdevice', to_add, to_remove) You can use empty lists if you just add or remove items. As you can see in the code example, the function (if successful) returns a UpdateResult object. The UpdateResult object contains a `update_urls` attribute that is a list of `(old_url, new_url)` tuples in case the server has re-written URLs. According to the API documentation, the client application must update the old_url values with new_url values (these have been sanitized). The `since` attribute of the result object can be used for requesting changes since the last upload, like this: .. code-block:: python updates = client.pull_subscriptions('abcdevice', result.since) The `updates` return value here is a :class:`.SubscriptionChanges` object that contains a new ``since`` attribute (that can be used for subsequent requests) and two lists (``add`` and ``remove``) of URLs that should be processed by the client by creating and removing subscriptions. Synchronizing episode actions ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ''TODO'' Enumerating and modifying devices ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The :class:`.MygPodderClient` class provides two methods for dealing with devices: :meth:`.get_devices` (which returns a list of :class:`PodcastDevice` objects) and :meth:`.update_device_settings` for modifying the device-specific settings on the server side. Here is an example script to use both functions to rename all users's device to "My Device" on the server: .. code-block:: python client = api.MygPodderClient('john', '53cr3t') for device in client.get_devices(): print 'Changing name of', device.device_id client.update_device_settings(device.device_id, caption='My Device') The Public API client (``mygpoclient.public.PublicClient``) ----------------------------------------------------------- This client does not need authentication and can be used to query and retrieve public data from the web service. Toplist retrieval ^^^^^^^^^^^^^^^^^ You can use the :meth:`.get_toplist` method on a :class:`.PublicClient` instance to retrieve a list of podcast toplist entries: .. code-block:: python from mygpoclient import public client = public.PublicClient() toplist = client.get_toplist() for index, entry in enumerate(toplist): print '%4d. %s (%d)' % (index+1, entry.title, entry.subscribers) Searching for podcasts ^^^^^^^^^^^^^^^^^^^^^^ Searching is done using :meth:`.search_podcasts` method of :class:`.PublicClient` like this: .. code-block:: python from mygpoclient import public client = public.PublicClient() search_results = client.search_podcasts('outlaws') for result in search_results: print result.title print result.url print '-'*50 mygpoclient-1.9/doc/mygpoclient.rst000066400000000000000000000027331425512052500175540ustar00rootroot00000000000000The mygpoclient package ======================= Submodules ---------- mygpoclient\.api module ----------------------- .. automodule:: mygpoclient.api :members: :undoc-members: :show-inheritance: mygpoclient\.feeds module ------------------------- .. automodule:: mygpoclient.feeds :members: :undoc-members: :show-inheritance: mygpoclient\.http module ------------------------ .. automodule:: mygpoclient.http :members: :undoc-members: :show-inheritance: mygpoclient\.json module ------------------------ .. automodule:: mygpoclient.json :members: :undoc-members: :show-inheritance: mygpoclient\.locator module --------------------------- .. automodule:: mygpoclient.locator :members: :undoc-members: :show-inheritance: mygpoclient\.public module -------------------------- .. automodule:: mygpoclient.public :members: :undoc-members: :show-inheritance: mygpoclient\.simple module -------------------------- .. automodule:: mygpoclient.simple :members: :undoc-members: :show-inheritance: mygpoclient\.testing module --------------------------- .. automodule:: mygpoclient.testing :members: :undoc-members: :show-inheritance: mygpoclient\.util module ------------------------ .. automodule:: mygpoclient.util :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: mygpoclient :members: :undoc-members: :show-inheritance: mygpoclient-1.9/doc/requirements-doc.txt000066400000000000000000000000201425512052500205020ustar00rootroot00000000000000sphinx minimock mygpoclient-1.9/makefile000066400000000000000000000024431425512052500154210ustar00rootroot00000000000000# gpodder.net API Client # Copyright (C) 2009-2013 Thomas Perl and the gPodder Team # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . PACKAGE := mygpoclient PYTHON ?= python FIND ?= find PYTEST ?= $(PYTHON) -m pytest help: @echo "" @echo "$(MAKE) test ......... Run unit tests" @echo "$(MAKE) clean ........ Clean build directory" @echo "$(MAKE) distclean .... $(MAKE) clean + remove 'dist/'" @echo "" test: $(PYTEST) docs: epydoc -n 'gpodder.net API Client Library' -o docs/ mygpoclient -v --exclude='.*_test' clean: $(FIND) . -name '*.pyc' -o -name __pycache__ -exec $(RM) -r '{}' + $(RM) -r build $(RM) .coverage MANIFEST distclean: clean $(RM) -r dist .PHONY: help test docs clean distclean .DEFAULT: help mygpoclient-1.9/man/000077500000000000000000000000001425512052500144715ustar00rootroot00000000000000mygpoclient-1.9/man/mygpo-bpsync.1000066400000000000000000000034321425512052500172040ustar00rootroot00000000000000.TH BPSYNC "1" "February 2013" "mygpoclient 1.7" "User Commands" .SH NAME mygpo-bpsync \- Synchronize BashPodder subscriptions with gpodder.net .SH SYNOPSIS .B mygpo-bpsync (\fIput|get\fR) [\fIdevice-id\fR] .SH DESCRIPTION .PP bpsync is a simple gpodder.net client application for syncing a BashPodder (\fIhttp://lincgeek.org/bashpodder/\fR) subscription list from and to the web service. As BashPodder uses a simple one-URL-per-line subscription list format, this script can be used with other applications, too (or to simply backup gpodder.net subscription URLs as plain text file). .PP If you have added a subscription on gpodder.net, you can use the \fBget\fR sub-command to overwrite the local subscription list with the list stored on gpodder.net. If you have added a subscription locally, you can use the \fBput\fR sub-command to overwrite the list on gpodder.net with the list stored in the BashPodder subscription list. .SH ENVIRONMENT VARIABLES .PP The following environment variables must be set for .B mygpo-bpsync to work: .PP .B MYGPO_USERNAME .RS 4 Username for the web service .RE .PP .B MYGPO_PASSWORD .RS 4 Password for the web service .RE .PP The following environment variables are optional: .PP .B BPSYNC_BP_CONF .RS 4 Path to your bp.conf file (default: \fIbp.conf\fR) .RE .PP .B MYGPO_HOSTNAME .RS 4 Host or URL of the webservice to use (default: \fIhttp://gpodder.net\fR) .RE .SH EXAMPLES .PP .B mygpo-bpsync put .RS 4 Upload bp.conf as device "bp" .RE .PP .B mygpo-bpsync get .RS 4 Download subscriptions for device "bp" .RE .PP .B mygpo-bpsync get mydev .RS 4 Download subscriptions for device "mydev" .RE .SH SEE ALSO .PP gpodder(1) .SH REPORTING BUGS .PP \fIhttps://bugs.gpodder.org/enter_bug.cgi?product=mygpoclient\fR .SH WEBSITE .PP \fIhttp://thp.io/2010/mygpoclient/\fR mygpoclient-1.9/mygpoclient/000077500000000000000000000000001425512052500162505ustar00rootroot00000000000000mygpoclient-1.9/mygpoclient/__init__.py000066400000000000000000000036251425512052500203670ustar00rootroot00000000000000# -*- coding: utf-8 -*- # gpodder.net API Client # Copyright (C) 2009-2013 Thomas Perl and the gPodder Team # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """gpodder.net API Client Library This is mygpoclient, the gpodder.net API Client Library for Python. """ __author__ = 'Thomas Perl ' __version__ = '1.9' __website__ = 'http://gpodder.org/mygpoclient/' __license__ = 'GNU General Public License v3 or later' # Default settings for the API client (server root url and API version) ROOT_URL = 'http://gpodder.net' VERSION = 2 TOPLIST_DEFAULT = 50 # You can overwrite this value from your application if you want user_agent = 'mygpoclient/%s (+%s)' % (__version__, __website__) # Version checking def require_version(minimum_required): """Require a minimum version of the library Returns True if the minimum library version constraint is satisfied, False otherwise. Use this to check for newer API methods and changes in the public API as described in NEWS. >>> require_version('1.0') True >>> require_version('1.2') True >>> require_version(__version__) True >>> require_version('99.99') False """ this_version = [int(x) for x in __version__.split('.')] minimum_required = [int(x) for x in minimum_required.split('.')] return minimum_required <= this_version mygpoclient-1.9/mygpoclient/api.py000066400000000000000000000407751425512052500174100ustar00rootroot00000000000000# -*- coding: utf-8 -*- # gpodder.net API Client # Copyright (C) 2009-2013 Thomas Perl and the gPodder Team # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . try: # Python 2 str = unicode except BaseException: # Python 3 pass from mygpoclient import util from mygpoclient import simple from mygpoclient import public # Additional error types for the advanced API client class InvalidResponse(Exception): pass class UpdateResult(object): """Container for subscription update results Attributes: update_urls - A list of (old_url, new_url) tuples since - A timestamp value for use in future requests """ def __init__(self, update_urls, since): self.update_urls = update_urls self.since = since class SubscriptionChanges(object): """Container for subscription changes Attributes: add - A list of URLs that have been added remove - A list of URLs that have been removed since - A timestamp value for use in future requests """ def __init__(self, add, remove, since): self.add = add self.remove = remove self.since = since class EpisodeActionChanges(object): """Container for added episode actions Attributes: actions - A list of EpisodeAction objects since - A timestamp value for use in future requests """ def __init__(self, actions, since): self.actions = actions self.since = since class PodcastDevice(object): """This class encapsulates a podcast device Attributes: device_id - The ID used to refer to this device caption - A user-defined "name" for this device type - A valid type of podcast device (see VALID_TYPES) subscriptions - The number of podcasts this device is subscribed to """ VALID_TYPES = ('desktop', 'laptop', 'mobile', 'server', 'other') def __init__(self, device_id, caption, type, subscriptions): # Check if the device type is valid if type not in self.VALID_TYPES: raise ValueError( 'Invalid device type "%s" (see VALID_TYPES)' % type) # Check if subscriptions is a numeric value try: int(subscriptions) except BaseException: raise ValueError( 'Subscription must be a numeric value but was %s' % subscriptions) self.device_id = device_id self.caption = caption self.type = type self.subscriptions = int(subscriptions) def __str__(self): """String representation of this device >>> device = PodcastDevice('mygpo', 'My Device', 'mobile', 10) >>> print(device) PodcastDevice('mygpo', 'My Device', 'mobile', 10) """ return '%s(%r, %r, %r, %r)' % (self.__class__.__name__, self.device_id, self.caption, self.type, self.subscriptions) @classmethod def from_dictionary(cls, d): return cls(d['id'], d['caption'], d['type'], d['subscriptions']) class EpisodeAction(object): """This class encapsulates an episode action The mandatory attributes are: podcast - The feed URL of the podcast episode - The enclosure URL or GUID of the episode action - One of 'download', 'play', 'delete' or 'new' The optional attributes are: device - The device_id on which the action has taken place timestamp - When the action took place (in XML time format) started - The start time of a play event in seconds position - The current position of a play event in seconds total - The total time of the episode (for play events) The attribute "position" is only valid for "play" action types. """ VALID_ACTIONS = ('download', 'play', 'delete', 'new', 'flattr') def __init__(self, podcast, episode, action, device=None, timestamp=None, started=None, position=None, total=None): # Check if the action is valid if action not in self.VALID_ACTIONS: raise ValueError( 'Invalid action type "%s" (see VALID_ACTIONS)' % action) # Disallow play-only attributes for non-play actions if action != 'play': if started is not None: raise ValueError( 'Started can only be set for the "play" action') elif position is not None: raise ValueError( 'Position can only be set for the "play" action') elif total is not None: raise ValueError('Total can only be set for the "play" action') # Check the format of the timestamp value if timestamp is not None: if util.iso8601_to_datetime(timestamp) is None: raise ValueError( 'Timestamp has to be in ISO 8601 format but was %s' % timestamp) # Check if we have a "position" value if we have started or total if position is None and (started is not None or total is not None): raise ValueError('Started or total set, but no position given') # Check that "started" is a number if it's set if started is not None: try: started = int(started) except ValueError: raise ValueError( 'Started must be an integer value (seconds) but was %s' % started) # Check that "position" is a number if it's set if position is not None: try: position = int(position) except ValueError: raise ValueError( 'Position must be an integer value (seconds) but was %s' % position) # Check that "total" is a number if it's set if total is not None: try: total = int(total) except ValueError: raise ValueError( 'Total must be an integer value (seconds) but was %s' % total) self.podcast = podcast self.episode = episode self.action = action self.device = device self.timestamp = timestamp self.started = started self.position = position self.total = total @classmethod def from_dictionary(cls, d): return cls(d['podcast'], d['episode'], d['action'], d.get('device'), d.get('timestamp'), d.get('started'), d.get('position'), d.get('total')) def to_dictionary(self): d = {} for mandatory in ('podcast', 'episode', 'action'): value = getattr(self, mandatory) d[mandatory] = value for optional in ('device', 'timestamp', 'started', 'position', 'total'): value = getattr(self, optional) if value is not None: d[optional] = value return d class MygPodderClient(simple.SimpleClient): """gpodder.net API Client This is the API client that implements both the Simple and Advanced API of gpodder.net. See the SimpleClient class for a smaller class that only implements the Simple API. """ @simple.needs_credentials def get_subscriptions(self, device): # Overloaded to accept PodcastDevice objects as arguments device = getattr(device, 'device_id', device) return simple.SimpleClient.get_subscriptions(self, device) @simple.needs_credentials def put_subscriptions(self, device, urls): # Overloaded to accept PodcastDevice objects as arguments device = getattr(device, 'device_id', device) return simple.SimpleClient.put_subscriptions(self, device, urls) @simple.needs_credentials def update_subscriptions(self, device_id, add_urls=[], remove_urls=[]): """Update the subscription list for a given device. Returns a UpdateResult object that contains a list of (sanitized) URLs and a "since" value that can be used for future calls to pull_subscriptions. For every (old_url, new_url) tuple in the updated_urls list of the resulting object, the client should rewrite the URL in its subscription list so that new_url is used instead of old_url. """ uri = self._locator.add_remove_subscriptions_uri(device_id) if not all(isinstance(x, str) for x in add_urls): raise ValueError( 'add_urls must be a list of strings but was %s' % add_urls) if not all(isinstance(x, str) for x in remove_urls): raise ValueError( 'remove_urls must be a list of strings but was %s' % remove_urls) data = {'add': add_urls, 'remove': remove_urls} response = self._client.POST(uri, data) if response is None: raise InvalidResponse('Got empty response') if 'timestamp' not in response: raise InvalidResponse('Response does not contain timestamp') try: since = int(response['timestamp']) except ValueError: raise InvalidResponse( 'Invalid value %s for timestamp in response' % response['timestamp']) if 'update_urls' not in response: raise InvalidResponse('Response does not contain update_urls') try: update_urls = [(a, b) for a, b in response['update_urls']] except BaseException: raise InvalidResponse( 'Invalid format of update_urls in response: %s' % response['update_urls']) if not all(isinstance(a, str) and isinstance(b, str) for a, b in update_urls): raise InvalidResponse( 'Invalid format of update_urls in response: %s' % update_urls) return UpdateResult(update_urls, since) @simple.needs_credentials def pull_subscriptions(self, device_id, since=None): """Downloads subscriptions since the time of the last update The "since" parameter should be a timestamp that has been retrieved previously by a call to update_subscriptions or pull_subscriptions. Returns a SubscriptionChanges object with two lists (one for added and one for removed podcast URLs) and a "since" value that can be used for future calls to this method. """ uri = self._locator.subscription_updates_uri(device_id, since) data = self._client.GET(uri) if data is None: raise InvalidResponse('Got empty response') if 'add' not in data: raise InvalidResponse('List of added podcasts not in response') if 'remove' not in data: raise InvalidResponse('List of removed podcasts not in response') if 'timestamp' not in data: raise InvalidResponse('Timestamp missing from response') if not all(isinstance(x, str) for x in data['add']): raise InvalidResponse( 'Invalid value(s) in list of added podcasts: %s' % data['add']) if not all(isinstance(x, str) for x in data['remove']): raise InvalidResponse( 'Invalid value(s) in list of removed podcasts: %s' % data['remove']) try: since = int(data['timestamp']) except ValueError: raise InvalidResponse( 'Timestamp has invalid format in response: %s' % data['timestamp']) return SubscriptionChanges(data['add'], data['remove'], since) @simple.needs_credentials def upload_episode_actions(self, actions=[]): """Uploads a list of EpisodeAction objects to the server Returns the timestamp that can be used for retrieving changes. """ uri = self._locator.upload_episode_actions_uri() actions = [action.to_dictionary() for action in actions] response = self._client.POST(uri, actions) if response is None: raise InvalidResponse('Got empty response') if 'timestamp' not in response: raise InvalidResponse('Response does not contain timestamp') try: since = int(response['timestamp']) except ValueError: raise InvalidResponse( 'Invalid value %s for timestamp in response' % response['timestamp']) return since @simple.needs_credentials def download_episode_actions(self, since=None, podcast=None, device_id=None): """Downloads a list of EpisodeAction objects from the server Returns a EpisodeActionChanges object with the list of new actions and a "since" timestamp that can be used for future calls to this method when retrieving episodes. """ uri = self._locator.download_episode_actions_uri(since, podcast, device_id) data = self._client.GET(uri) if data is None: raise InvalidResponse('Got empty response') if 'actions' not in data: raise InvalidResponse('Response does not contain actions') if 'timestamp' not in data: raise InvalidResponse('Response does not contain timestamp') try: since = int(data['timestamp']) except ValueError: raise InvalidResponse('Invalid value for timestamp: ' + data['timestamp']) dicts = data['actions'] try: actions = [EpisodeAction.from_dictionary(d) for d in dicts] except KeyError: raise InvalidResponse('Missing keys in action list response') return EpisodeActionChanges(actions, since) @simple.needs_credentials def update_device_settings(self, device_id, caption=None, type=None): """Update the description of a device on the server This changes the caption and/or type of a given device on the server. If the device does not exist, it is created with the given settings. The parameters caption and type are both optional and when set to a value other than None will be used to update the device settings. Returns True if the request succeeded, False otherwise. """ uri = self._locator.device_settings_uri(device_id) data = {} if caption is not None: data['caption'] = caption if type is not None: data['type'] = type return self._client.POST(uri, data) is None @simple.needs_credentials def get_devices(self): """Returns a list of this user's PodcastDevice objects The resulting list can be used to display a selection list to the user or to determine device IDs to pull the subscription list from. """ uri = self._locator.device_list_uri() dicts = self._client.GET(uri) if dicts is None: raise InvalidResponse('No response received') try: return [PodcastDevice.from_dictionary(d) for d in dicts] except KeyError: raise InvalidResponse('Missing keys in device list response') def get_favorite_episodes(self): """Returns a List of Episode Objects containing the Users favorite Episodes""" uri = self._locator.favorite_episodes_uri() return [public.Episode.from_dict(d) for d in self._client.GET(uri)] def get_settings(self, type, scope_param1=None, scope_param2=None): """Returns a Dictionary with the set settings for the type & specified scope""" uri = self._locator.settings_uri(type, scope_param1, scope_param2) return self._client.GET(uri) def set_settings(self, type, scope_param1, scope_param2, set={}, remove=[]): """Returns a Dictionary with the set settings for the type & specified scope""" uri = self._locator.settings_uri(type, scope_param1, scope_param2) data = {"set": set, "remove": remove} return self._client.POST(uri, data) mygpoclient-1.9/mygpoclient/api_test.py000066400000000000000000000667361425512052500204540ustar00rootroot00000000000000# -*- coding: utf-8 -*- # gpodder.net API Client # Copyright (C) 2009-2013 Thomas Perl and the gPodder Team # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from mygpoclient import api from mygpoclient import testing import unittest # Example data for testing purposes FEED_URL_1 = u'http://example.com/test.rss' FEED_URL_2 = u'http://feeds.example.org/1/feed.atom' FEED_URL_3 = u'http://example.co.uk/episodes.xml' FEED_URL_4 = u'http://pod.cast/test.xml' EPISODE_URL_1 = u'http://dl.example.net/episodes/one.mp3' EPISODE_URL_2 = u'http://pod.cast.invalid/downloads/s02e04.ogg' EPISODE_URL_3 = u'http://example.org/05-skylarking.m4v' EPISODE_URL_4 = u'http://www.example.com/test/me_now.avi' DEVICE_ID_1 = u'gpodder.on.my.phone' DEVICE_ID_2 = u'95dce59cf340123fa' class Test_SubscriptionChanges(unittest.TestCase): ADD = [ FEED_URL_1, FEED_URL_3, ] REMOVE = [ FEED_URL_2, FEED_URL_4, ] SINCE = 1262101867 def test_initSetsCorrectAttributes(self): changes = api.SubscriptionChanges(self.ADD, self.REMOVE, self.SINCE) self.assertEquals(changes.add, self.ADD) self.assertEquals(changes.remove, self.REMOVE) self.assertEquals(changes.since, self.SINCE) class Test_EpisodeActionChanges(unittest.TestCase): ACTIONS = [ api.EpisodeAction(FEED_URL_1, EPISODE_URL_1, 'download'), api.EpisodeAction(FEED_URL_2, EPISODE_URL_3, 'play'), api.EpisodeAction(FEED_URL_2, EPISODE_URL_4, 'delete'), ] SINCE = 1262102013 def test_initSetsCorrectAttributes(self): changes = api.EpisodeActionChanges(self.ACTIONS, self.SINCE) self.assertEquals(changes.actions, self.ACTIONS) self.assertEquals(changes.since, self.SINCE) class Test_PodcastDevice(unittest.TestCase): CAPTION = 'My Nice Device' def test_initSetsCorrectAttributes(self): device = api.PodcastDevice(DEVICE_ID_1, self.CAPTION, 'mobile', 42) self.assertEquals(device.device_id, DEVICE_ID_1) self.assertEquals(device.caption, self.CAPTION) self.assertEquals(device.type, 'mobile') self.assertEquals(device.subscriptions, 42) def test_invalidDeviceType_raisesValueError(self): self.assertRaises(ValueError, api.PodcastDevice, DEVICE_ID_2, self.CAPTION, 'does-not-exist', 1337) def test_nonNumericSubscriptions_raisesValueError(self): self.assertRaises(ValueError, api.PodcastDevice, DEVICE_ID_1, self.CAPTION, 'laptop', 'notanumber') class Test_EpisodeAction(unittest.TestCase): XML_TIMESTAMP = '2009-12-12T09:00:00' VALID_STARTED = 100 VALID_POSITION = 123 VALID_TOTAL = 321 def test_initSetsCorrectAttributes(self): action = api.EpisodeAction(FEED_URL_1, EPISODE_URL_1, 'play', DEVICE_ID_1, self.XML_TIMESTAMP, self.VALID_STARTED, self.VALID_POSITION, self.VALID_TOTAL) self.assertEquals(action.podcast, FEED_URL_1) self.assertEquals(action.episode, EPISODE_URL_1) self.assertEquals(action.action, 'play') self.assertEquals(action.device, DEVICE_ID_1) self.assertEquals(action.timestamp, self.XML_TIMESTAMP) self.assertEquals(action.started, self.VALID_STARTED) self.assertEquals(action.position, self.VALID_POSITION) self.assertEquals(action.total, self.VALID_TOTAL) def test_invalidAction_raisesValueError(self): self.assertRaises(ValueError, api.EpisodeAction, FEED_URL_2, EPISODE_URL_3, 'invalidaction', DEVICE_ID_2, self.XML_TIMESTAMP) def test_startedIsSetWithNoPlayAction_raisesValueError(self): self.assertRaises(ValueError, api.EpisodeAction, FEED_URL_4, EPISODE_URL_2, 'download', DEVICE_ID_1, self.XML_TIMESTAMP, self.VALID_STARTED) def test_positionIsSetWithNoPlayAction_raisesValueError(self): self.assertRaises(ValueError, api.EpisodeAction, FEED_URL_4, EPISODE_URL_2, 'download', DEVICE_ID_1, self.XML_TIMESTAMP, None, self.VALID_POSITION) def test_totalIsSetWithNoPlayAction_raisesValueError(self): self.assertRaises(ValueError, api.EpisodeAction, FEED_URL_4, EPISODE_URL_2, 'download', DEVICE_ID_1, self.XML_TIMESTAMP, None, None, self.VALID_TOTAL) def test_invalidTimestampFormat_raisesValueError(self): self.assertRaises(ValueError, api.EpisodeAction, FEED_URL_3, EPISODE_URL_3, 'delete', DEVICE_ID_2, 'today') def test_onlyStartedSet_raisesValueError(self): self.assertRaises(ValueError, api.EpisodeAction, FEED_URL_1, EPISODE_URL_4, 'play', DEVICE_ID_1, self.XML_TIMESTAMP, self.VALID_STARTED) def test_invalidStartedFormat_raisesValueError(self): self.assertRaises(ValueError, api.EpisodeAction, FEED_URL_1, EPISODE_URL_4, 'play', DEVICE_ID_1, self.XML_TIMESTAMP, '10 minutes into the show', self.VALID_POSITION) def test_invalidPositionFormat_raisesValueError(self): self.assertRaises(ValueError, api.EpisodeAction, FEED_URL_1, EPISODE_URL_4, 'play', DEVICE_ID_1, self.XML_TIMESTAMP, self.VALID_STARTED, '15 minutes later') def test_invalidTotalFormat_raisesValueError(self): self.assertRaises(ValueError, api.EpisodeAction, FEED_URL_1, EPISODE_URL_4, 'play', DEVICE_ID_1, self.XML_TIMESTAMP, None, self.VALID_POSITION, '30 minutes total') def test_toDictionary_containsMandatoryAttributes(self): action = api.EpisodeAction(FEED_URL_1, EPISODE_URL_1, 'play') dictionary = action.to_dictionary() self.assertEquals(len(list(dictionary.keys())), 3) self.assert_('podcast' in dictionary) self.assert_('episode' in dictionary) self.assert_('action' in dictionary) self.assertEquals(dictionary['podcast'], FEED_URL_1) self.assertEquals(dictionary['episode'], EPISODE_URL_1) self.assertEquals(dictionary['action'], 'play') def test_toDictionary_containsAllAttributes(self): action = api.EpisodeAction(FEED_URL_3, EPISODE_URL_4, 'play', DEVICE_ID_1, self.XML_TIMESTAMP, self.VALID_STARTED, self.VALID_POSITION, self.VALID_TOTAL) dictionary = action.to_dictionary() self.assertEquals(len(list(dictionary.keys())), 8) self.assert_('podcast' in dictionary) self.assert_('episode' in dictionary) self.assert_('action' in dictionary) self.assert_('device' in dictionary) self.assert_('timestamp' in dictionary) self.assert_('started' in dictionary) self.assert_('position' in dictionary) self.assert_('total' in dictionary) self.assertEquals(dictionary['podcast'], FEED_URL_3) self.assertEquals(dictionary['episode'], EPISODE_URL_4) self.assertEquals(dictionary['action'], 'play') self.assertEquals(dictionary['device'], DEVICE_ID_1) self.assertEquals(dictionary['timestamp'], self.XML_TIMESTAMP) self.assertEquals(dictionary['started'], self.VALID_STARTED) self.assertEquals(dictionary['position'], self.VALID_POSITION) self.assertEquals(dictionary['total'], self.VALID_TOTAL) class Test_MygPodderClient(unittest.TestCase): ADD = [ FEED_URL_1, FEED_URL_3, ] REMOVE = [ FEED_URL_2, FEED_URL_4, ] ADD_REMOVE_AS_JSON_UPLOAD = { 'add': [FEED_URL_1, FEED_URL_3], 'remove': [FEED_URL_2, FEED_URL_4], } ACTIONS = [ api.EpisodeAction(FEED_URL_1, EPISODE_URL_1, 'download'), api.EpisodeAction(FEED_URL_2, EPISODE_URL_3, 'play'), api.EpisodeAction(FEED_URL_2, EPISODE_URL_4, 'delete'), ] ACTIONS_AS_JSON_UPLOAD = [ {'podcast': FEED_URL_1, 'episode': EPISODE_URL_1, 'action': 'download'}, {'podcast': FEED_URL_2, 'episode': EPISODE_URL_3, 'action': 'play'}, {'podcast': FEED_URL_2, 'episode': EPISODE_URL_4, 'action': 'delete'}, ] USERNAME = 'user01' PASSWORD = 's3cret' SINCE = 1262103016 def setUp(self): self.fake_client = testing.FakeJsonClient() self.client = api.MygPodderClient(self.USERNAME, self.PASSWORD, client_class=self.fake_client) def set_http_response_value(self, value): self.fake_client.response_value = value def assert_http_request_count(self, count): self.assertEquals(len(self.fake_client.requests), count) def has_put_json_data(self, data, required_method='PUT'): """Returns True if the FakeJsonClient has received the given data""" for method, uri, sent in self.fake_client.requests: if method == required_method: self.assertEquals(sent, data) return True return False def has_posted_json_data(self, data): """Same as has_put_json_data, but require a POST request""" return self.has_put_json_data(data, required_method='POST') def test_getSubscriptions_withPodcastDevice(self): self.set_http_response_value(b'[]') device = api.PodcastDevice('manatee', 'My Device', 'mobile', 20) self.assertEquals(self.client.get_subscriptions(device), []) self.assert_http_request_count(1) def test_putSubscriptions_withPodcastDevice(self): self.set_http_response_value(b'') device = api.PodcastDevice('manatee', 'My Device', 'mobile', 20) self.assertEquals( self.client.put_subscriptions( device, self.ADD), True) self.assert_http_request_count(1) self.assert_(self.has_put_json_data(self.ADD)) def test_updateSubscriptions_raisesValueError_onInvalidAddList(self): self.assertRaises(ValueError, self.client.update_subscriptions, DEVICE_ID_2, [FEED_URL_1, 123, FEED_URL_3], self.REMOVE) def test_updateSubscriptions_raisesValueError_onInvalidRemoveList(self): self.assertRaises(ValueError, self.client.update_subscriptions, DEVICE_ID_2, self.ADD, [FEED_URL_2, FEED_URL_4, [1, 2, 3]]) def test_updateSubscriptions_raisesInvalidResponse_onEmptyResponse(self): self.set_http_response_value(b'') self.assertRaises(api.InvalidResponse, self.client.update_subscriptions, DEVICE_ID_1, self.ADD, self.REMOVE) def test_updateSubscriptions_raisesInvalidResponse_onMissingTimestamp( self): self.set_http_response_value(b'{}') self.assertRaises(api.InvalidResponse, self.client.update_subscriptions, DEVICE_ID_1, self.ADD, self.REMOVE) def test_updateSubscriptions_raisesInvalidResponse_onInvalidTimestamp( self): self.set_http_response_value(b""" {"timestamp": "not gonna happen"} """) self.assertRaises(api.InvalidResponse, self.client.update_subscriptions, DEVICE_ID_1, self.ADD, self.REMOVE) def test_updateSubscriptions_raisesInvalidResponse_withoutUpdateUrls(self): self.set_http_response_value(b""" {"timestamp": 1262103016} """) self.assertRaises(api.InvalidResponse, self.client.update_subscriptions, DEVICE_ID_1, self.ADD, self.REMOVE) def test_updateSubscriptions_raisesInvalidResponse_withNonStringList(self): self.set_http_response_value(b""" {"timestamp": 1262103016, "update_urls": [ ["http://example.com/", 2], [56, "http://example.org/"] ]} """) self.assertRaises(api.InvalidResponse, self.client.update_subscriptions, DEVICE_ID_2, self.ADD, self.REMOVE) def test_updateSubscriptions_raisesInvalidResponse_withInvalidList(self): self.set_http_response_value(b""" {"timestamp": 1262103016, "update_urls": [ ["test", "test2", "test3"], ["test", "test2"] ]} """) self.assertRaises(api.InvalidResponse, self.client.update_subscriptions, DEVICE_ID_2, self.ADD, self.REMOVE) def test_updateSubscriptions_returnsUpdateResult(self): self.set_http_response_value(b""" {"timestamp": 1262103016, "update_urls": [ ["http://test2.invalid/feed.rss", "http://test2.invalid/feed.rss"], ["http://x.invalid/episodes.xml?format=2", "http://x.invalid/episodes.xml"] ]} """) update_urls_expected = [ ('http://test2.invalid/feed.rss', 'http://test2.invalid/feed.rss'), ('http://x.invalid/episodes.xml?format=2', 'http://x.invalid/episodes.xml'), ] result = self.client.update_subscriptions(DEVICE_ID_1, self.ADD, self.REMOVE) # result is a UpdateResult object self.assert_(hasattr(result, 'since')) self.assert_(hasattr(result, 'update_urls')) self.assertEquals(result.since, self.SINCE) self.assertEquals(result.update_urls, update_urls_expected) self.assert_http_request_count(1) self.assert_(self.has_posted_json_data(self.ADD_REMOVE_AS_JSON_UPLOAD)) def test_pullSubscriptions_raisesInvalidResponse_onEmptyResponse(self): self.set_http_response_value(b'') self.assertRaises(api.InvalidResponse, self.client.pull_subscriptions, DEVICE_ID_2) def test_pullSubscriptions_raisesInvalidResponse_onMissingTimestamp(self): self.set_http_response_value(b""" {"add": [ "http://example.com/test.rss", "http://feeds.example.org/1/feed.atom" ], "remove": [ "http://example.co.uk/episodes.xml", "http://pod.cast/test.xml" ]} """) self.assertRaises(api.InvalidResponse, self.client.pull_subscriptions, DEVICE_ID_2) def test_pullSubscriptions_raisesInvalidResponse_onMissingAddList(self): self.set_http_response_value(b""" {"remove": [ "http://example.co.uk/episodes.xml", "http://pod.cast/test.xml" ], "timestamp": 1262103016} """) self.assertRaises(api.InvalidResponse, self.client.pull_subscriptions, DEVICE_ID_2) def test_pullSubscriptions_raisesInvalidResponse_onMissingRemoveList(self): self.set_http_response_value(b""" {"add": [ "http://example.com/test.rss", "http://feeds.example.org/1/feed.atom" ], "timestamp": 1262103016} """) self.assertRaises(api.InvalidResponse, self.client.pull_subscriptions, DEVICE_ID_2) def test_pullSubscriptions_raisesInvalidResponse_onInvalidTimestamp(self): self.set_http_response_value(b""" {"add": [ "http://example.com/test.rss", "http://feeds.example.org/1/feed.atom" ], "remove": [ "http://example.co.uk/episodes.xml", "http://pod.cast/test.xml" ], "timestamp": "should not work"} """) self.assertRaises(api.InvalidResponse, self.client.pull_subscriptions, DEVICE_ID_2) def test_pullSubscriptions_raisesInvalidResponse_onInvalidAddList(self): self.set_http_response_value(b""" {"add": [ "http://example.com/test.rss", 1234, "http://feeds.example.org/1/feed.atom" ], "remove": [ "http://example.co.uk/episodes.xml", "http://pod.cast/test.xml" ], "timestamp": 1262103016} """) self.assertRaises(api.InvalidResponse, self.client.pull_subscriptions, DEVICE_ID_2) def test_pullSubscriptions_raisesInvalidResponse_onInvalidRemoveList(self): self.set_http_response_value(b""" {"add": [ "http://example.com/test.rss", "http://feeds.example.org/1/feed.atom" ], "remove": [ "http://example.co.uk/episodes.xml", ["should", "not", "work", "either"], "http://pod.cast/test.xml" ], "timestamp": 1262103016} """) self.assertRaises(api.InvalidResponse, self.client.pull_subscriptions, DEVICE_ID_2) def test_pullSubscriptions_returnsChangesListAndTimestamp(self): self.set_http_response_value(b""" {"add": [ "http://example.com/test.rss", "http://feeds.example.org/1/feed.atom" ], "remove": [ "http://example.co.uk/episodes.xml", "http://pod.cast/test.xml" ], "timestamp": 1262103016} """) changes = self.client.pull_subscriptions(DEVICE_ID_2) self.assertEquals(changes.add, [FEED_URL_1, FEED_URL_2]) self.assertEquals(changes.remove, [FEED_URL_3, FEED_URL_4]) self.assertEquals(changes.since, self.SINCE) self.assert_http_request_count(1) def test_uploadEpisodeActions_raisesInvalidResponse_onEmptyResponse(self): self.set_http_response_value(b'') self.assertRaises(api.InvalidResponse, self.client.upload_episode_actions, self.ACTIONS) def test_uploadEpisodeActions_raisesInvalidResponse_onMissingTimestamp( self): self.set_http_response_value(b'{}') self.assertRaises(api.InvalidResponse, self.client.upload_episode_actions, self.ACTIONS) def test_uploadEpisodeActions_raisesInvalidResponse_onInvalidTimestamp( self): self.set_http_response_value(b""" {"timestamp": "just nothin'.."} """) self.assertRaises(api.InvalidResponse, self.client.upload_episode_actions, self.ACTIONS) def test_uploadEpisodeActions_returnsTimestamp(self): self.set_http_response_value(b""" {"timestamp": 1262103016} """) result = self.client.upload_episode_actions(self.ACTIONS) self.assertEquals(result, self.SINCE) self.assert_http_request_count(1) self.assert_(self.has_posted_json_data(self.ACTIONS_AS_JSON_UPLOAD)) def test_downloadEpisodeActions_raisesInvalidResponse_onEmptyResponse( self): self.set_http_response_value(b'') self.assertRaises( api.InvalidResponse, self.client.download_episode_actions) def test_downloadEpisodeActions_raisesInvalidResponse_onMissingActions( self): self.set_http_response_value(b""" {"timestamp": 1262103016} """) self.assertRaises( api.InvalidResponse, self.client.download_episode_actions) def test_downloadEpisodeActions_raisesInvalidResponse_onMissingTimestamp( self): self.set_http_response_value(b""" {"actions": [ {"podcast": "a", "episode": "b", "action": "download"}, {"podcast": "x", "episode": "y", "action": "play"} ]} """) self.assertRaises( api.InvalidResponse, self.client.download_episode_actions) def test_downloadEpisodeActions_raisesInvalidResponse_onInvalidTimestamp( self): self.set_http_response_value(b""" {"actions": [ {"podcast": "a", "episode": "b", "action": "download"}, {"podcast": "x", "episode": "y", "action": "play"} ], "timestamp": "right now"} """) self.assertRaises( api.InvalidResponse, self.client.download_episode_actions) def test_downloadEpisodeActions_raisesInvalidResponse_onIncompleteActions( self): self.set_http_response_value(b""" {"actions": [ {"podcast": "a", "episode": "b", "action": "download"}, {"podcast": "x", "episode": "y"} ], "timestamp": 1262103016} """) self.assertRaises( api.InvalidResponse, self.client.download_episode_actions) def test_downloadEpisodeActions_returnsActionList(self): self.set_http_response_value(b""" {"actions": [ {"podcast": "a", "episode": "b", "action": "download"}, {"podcast": "x", "episode": "y", "action": "play"} ], "timestamp": 1262103016} """) changes = self.client.download_episode_actions() self.assertEquals(len(changes.actions), 2) action1, action2 = changes.actions self.assertEquals(action1.podcast, 'a') self.assertEquals(action1.episode, 'b') self.assertEquals(action1.action, 'download') self.assertEquals(action2.podcast, 'x') self.assertEquals(action2.episode, 'y') self.assertEquals(action2.action, 'play') self.assertEquals(changes.since, self.SINCE) self.assert_http_request_count(1) def test_updateDeviceSettings_withNothing(self): self.set_http_response_value(b'') result = self.client.update_device_settings(DEVICE_ID_1) self.assertEquals(result, True) self.assert_http_request_count(1) self.assert_(self.has_posted_json_data({})) def test_updateDeviceSettings_withCaption(self): self.set_http_response_value(b'') result = self.client.update_device_settings(DEVICE_ID_1, caption='Poodonkis') self.assertEquals(result, True) self.assert_http_request_count(1) self.assert_(self.has_posted_json_data({'caption': 'Poodonkis'})) def test_updateDeviceSettings_withType(self): self.set_http_response_value(b'') result = self.client.update_device_settings(DEVICE_ID_1, type='desktop') self.assertEquals(result, True) self.assert_http_request_count(1) self.assert_(self.has_posted_json_data({'type': 'desktop'})) def test_updateDeviceSettings_withCaptionAndType(self): self.set_http_response_value(b'') result = self.client.update_device_settings(DEVICE_ID_1, 'My Unit Testing Device', 'desktop') self.assertEquals(result, True) self.assert_http_request_count(1) self.assert_(self.has_posted_json_data({ 'caption': 'My Unit Testing Device', 'type': 'desktop'})) def test_getDevices_raisesInvalidResponse_onEmptyResponse(self): self.set_http_response_value(b'') self.assertRaises(api.InvalidResponse, self.client.get_devices) def test_getDevices_raisesInvalidResponse_onMissingKeys(self): self.set_http_response_value(b""" [ {"id": "gpodder.on.my.phone", "type": "mobile", "subscriptions": 42}, {"id": "95dce59cf340123fa", "caption": "The Lappy", "subscriptions": 4711} ] """) self.assertRaises(api.InvalidResponse, self.client.get_devices) def test_getDevices_returnsDeviceList(self): self.set_http_response_value(b""" [ {"id": "gpodder.on.my.phone", "caption": "Phone", "type": "mobile", "subscriptions": 42}, {"id": "95dce59cf340123fa", "caption": "The Lappy", "type": "laptop", "subscriptions": 4711} ] """) devices = self.client.get_devices() self.assertEquals(len(devices), 2) device1, device2 = devices self.assertEquals(device1.device_id, DEVICE_ID_1) self.assertEquals(device1.caption, 'Phone') self.assertEquals(device1.type, 'mobile') self.assertEquals(device1.subscriptions, 42) self.assertEquals(device2.device_id, DEVICE_ID_2) self.assertEquals(device2.caption, 'The Lappy') self.assertEquals(device2.type, 'laptop') self.assertEquals(device2.subscriptions, 4711) self.assert_http_request_count(1) def test_getFavoriteEpisodes_returnsEpisodeList(self): self.set_http_response_value(b""" [ {"title": "TWiT 245: No Hitler For You", "url": "http://www.podtrac.com/pts/redirect.mp3/aolradio.podcast.aol.com/twit/twit0245.mp3", "podcast_title": "this WEEK in TECH - MP3 Edition", "podcast_url": "http://leo.am/podcasts/twit", "description": "[...]", "website": "http://www.podtrac.com/pts/redirect.mp3/aolradio.podcast.aol.com/twit/twit0245.mp3", "released": "2010-12-25T00:30:00", "mygpo_link": "http://gpodder.net/episode/1046492"}, {"website": "http://feedproxy.google.com/~r/coverville/~3/5UK8-PZmmMQ/", "podcast_title": "Coverville", "description": "Bob Dylan turned 70 this week. Bob Dylan has done a lot of songs. A lot of people have covered Bob’s songs. Did I mention Bob Dylan turned 70 this week? All this adds up to a Cover Story. Let me play you it. 59 minutes | Featuring: Title Artist Album Original Artist 1 Blowin’ [...]", "title": "Coverville 774: The Bob Dylan Cover Story VI", "url": "http://feedproxy.google.com/~r/coverville/~5/iV_RxVU1Jek/Coverville-110527.mp3", "podcast_url": "http://feeds.feedburner.com/coverville", "released": "2011-05-28T01:08:59", "mygpo_link": "http://gpodder.net/episode/5329203"} ] """) favorites = self.client.get_favorite_episodes() self.assertEquals(len(favorites), 2) episode1, episode2 = favorites self.assertEquals(episode1.title, 'TWiT 245: No Hitler For You') self.assertEquals( episode1.url, 'http://www.podtrac.com/pts/redirect.mp3/aolradio.podcast.aol.com/twit/twit0245.mp3') self.assertEquals( episode1.podcast_title, 'this WEEK in TECH - MP3 Edition') self.assertEquals(episode1.podcast_url, 'http://leo.am/podcasts/twit') self.assertEquals(episode1.description, '[...]') self.assertEquals( episode1.website, 'http://www.podtrac.com/pts/redirect.mp3/aolradio.podcast.aol.com/twit/twit0245.mp3') self.assertEquals(episode1.released, '2010-12-25T00:30:00') self.assertEquals( episode1.mygpo_link, 'http://gpodder.net/episode/1046492') self.assertEquals( episode2.website, 'http://feedproxy.google.com/~r/coverville/~3/5UK8-PZmmMQ/') mygpoclient-1.9/mygpoclient/feeds.py000066400000000000000000000130311425512052500177060ustar00rootroot00000000000000# -*- coding: utf-8 -*- # mygpo-feedservice Client # Copyright (C) 2011 Stefan Kögl # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from __future__ import absolute_import import time try: # Python 3 from urllib.parse import urljoin, urlencode except ImportError: # Python 2 from urlparse import urljoin from urllib import urlencode from datetime import datetime from email import utils import mygpoclient.json try: # Prefer the usage of the simplejson module, as it # is most likely newer if it's installed as module # than the built-in json module (and is mandatory # in Python versions before 2.6, anyway). import simplejson as json except ImportError: # Python 2.6 ships the "json" module by default import json BASE_URL = 'http://mygpo-feedservice.appspot.com' class FeedServiceResponse(list): """ Encapsulates the relevant data of a mygpo-feedservice response """ def __init__(self, feeds, last_modified, feed_urls): super(FeedServiceResponse, self).__init__(feeds) self.last_modified = last_modified self.feed_urls = feed_urls self.indexed_feeds = {} for feed in feeds: for url in feed['urls']: self.indexed_feeds[url] = feed def get_feeds(self): """ Returns the parsed feeds in order of the initial request """ return (self.get_feed(url) for url in self.feed_urls) def get_feed(self, url): """ Returns the parsed feed for the given URL """ return self.indexed_feeds.get(url, None) class FeedserviceClient(mygpoclient.json.JsonClient): """A special-cased JsonClient for mygpo-feedservice""" def __init__(self, username=None, password=None, base_url=BASE_URL): self._base_url = base_url super(FeedserviceClient, self).__init__(username, password) def _prepare_request(self, method, uri, data): """Sets headers required by mygpo-feedservice Expects a dict with keys feed_urls and (optionally) last_modified""" # send URLs as POST data to avoid any length # restrictions for the query parameters post_data = [('url', feed_url) for feed_url in data['feed_urls']] post_data = urlencode(post_data) # call _prepare_request directly from HttpClient, because # JsonClient would JSON-encode our POST-data request = mygpoclient.http.HttpClient._prepare_request( method, uri, post_data) request.add_header('Accept', 'application/json') request.add_header('Accept-Encoding', 'gzip') last_modified = data.get('last_modified', None) if last_modified is not None: request.add_header( 'If-Modified-Since', self.format_header_date(last_modified)) return request def _process_response(self, response): """ Extract Last-modified header and passes response body to JsonClient for decoding""" last_modified = self.parse_header_date( response.headers['last-modified']) feeds = super(FeedserviceClient, self)._process_response(response) return feeds, last_modified def parse_feeds(self, feed_urls, last_modified=None, strip_html=False, use_cache=True, inline_logo=False, scale_logo=None, logo_format=None): """ Passes the given feed-urls to mygpo-feedservice to be parsed and returns the response """ url = self.build_url(strip_html=strip_html, use_cache=use_cache, inline_logo=inline_logo, scale_logo=scale_logo, logo_format=logo_format) request_data = dict(feed_urls=feed_urls, last_modified=last_modified) feeds, last_modified = self.POST(url, request_data) return FeedServiceResponse(feeds, last_modified, feed_urls) def build_url(self, **kwargs): """ Parameter such as strip_html, scale_logo, etc are pased as kwargs """ query_url = urljoin(self._base_url, 'parse') args = list(kwargs.items()) args = [k_v for k_v in args if k_v[1] is not None] # boolean flags are represented as 1 and 0 in the query-string args = [ (k_v1[0], int( k_v1[1]) if isinstance( k_v1[1], bool) else k_v1[1]) for k_v1 in args] args = urlencode(dict(args)) url = '%s?%s' % (query_url, args) return url @staticmethod def parse_header_date(date_str): """ Parses dates in RFC2822 format to datetime objects """ if not date_str: return None ts = time.mktime(utils.parsedate(date_str)) return datetime.utcfromtimestamp(ts) @staticmethod def format_header_date(datetime_obj): """ Formats the given datetime object for use in HTTP headers """ return utils.formatdate(time.mktime(datetime_obj.timetuple())) mygpoclient-1.9/mygpoclient/http.py000066400000000000000000000121701425512052500176020ustar00rootroot00000000000000# -*- coding: utf-8 -*- # gpodder.net API Client # Copyright (C) 2009-2013 Thomas Perl and the gPodder Team # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . try: from urllib import request from urllib.error import HTTPError from http.cookiejar import CookieJar except ImportError: import urllib2 as request from urllib2 import HTTPError from cookielib import CookieJar import mygpoclient class SimpleHttpPasswordManager(request.HTTPPasswordMgr): """Simplified password manager for urllib2 This class always provides the username/password combination that is passed to it as constructor argument, independent of the realm or authuri that is used. """ # The maximum number of authentication retries MAX_RETRIES = 3 def __init__(self, username, password): self._username = username self._password = password self._count = 0 def find_user_password(self, realm, authuri): self._count += 1 if self._count > self.MAX_RETRIES: return None, None return self._username, self._password class HttpRequest(request.Request): """Request object with customizable method The default behaviour of Request is unchanged: >>> request = HttpRequest('http://example.org/') >>> request.get_method() 'GET' >>> request = HttpRequest('http://example.org/', data='X') >>> request.get_method() 'POST' However, it's possible to customize the method name: >>> request = HttpRequest('http://example.org/', data='X') >>> request.set_method('PUT') >>> request.get_method() 'PUT' """ def set_method(self, method): setattr(self, '_method', method) def get_method(self): if hasattr(self, '_method'): return getattr(self, '_method') else: return request.Request.get_method(self) # Possible exceptions that will be raised by HttpClient class Unauthorized(Exception): pass class NotFound(Exception): pass class BadRequest(Exception): pass class UnknownResponse(Exception): pass class HttpClient(object): """A comfortable HTTP client This class hides the gory details of the underlying HTTP protocol from the rest of the code by providing a simple interface for doing requests and handling authentication. """ def __init__(self, username=None, password=None): self._username = username self._password = password self._cookie_jar = CookieJar() cookie_handler = request.HTTPCookieProcessor(self._cookie_jar) if username is not None and password is not None: password_manager = SimpleHttpPasswordManager(username, password) auth_handler = request.HTTPBasicAuthHandler(password_manager) self._opener = request.build_opener(auth_handler, cookie_handler) else: self._opener = request.build_opener(cookie_handler) @staticmethod def _prepare_request(method, uri, data): """Prepares the HttpRequest object""" if data is None: request = HttpRequest(uri) else: request = HttpRequest(uri, data) request.set_method(method) request.add_header('User-agent', mygpoclient.user_agent) return request @staticmethod def _process_response(response): return response.read() def _request(self, method, uri, data, **kwargs): """Request and exception handling Carries out a request with a given method (GET, POST, PUT) on a given URI with optional data (data only makes sense for POST and PUT requests and should be None for GET requests). """ request = self._prepare_request(method, uri, data) try: response = self._opener.open(request) except HTTPError as http_error: if http_error.code == 404: raise NotFound() elif http_error.code == 401: raise Unauthorized() elif http_error.code == 400: raise BadRequest() else: raise UnknownResponse(http_error.code) return self._process_response(response) def GET(self, uri): """Convenience method for carrying out a GET request""" return self._request('GET', uri, None) def POST(self, uri, data): """Convenience method for carrying out a POST request""" return self._request('POST', uri, data) def PUT(self, uri, data): """Convenience method for carrying out a PUT request""" return self._request('PUT', uri, data) mygpoclient-1.9/mygpoclient/http_test.py000066400000000000000000000163411425512052500206450ustar00rootroot00000000000000# -*- coding: utf-8 -*- # gpodder.net API Client # Copyright (C) 2009-2013 Thomas Perl and the gPodder Team # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import codecs import base64 from mygpoclient.http import (HttpClient, Unauthorized, BadRequest, UnknownResponse, NotFound) import unittest import multiprocessing try: # Python 3 from http.server import BaseHTTPRequestHandler, HTTPServer except ImportError: # Python 2 from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer str = unicode def http_server(port, username, password, response): storage = {} class Handler(BaseHTTPRequestHandler): def __init__(self, *args, **kwargs): BaseHTTPRequestHandler.__init__(self, *args, **kwargs) def _checks(self): if not self._check_auth(): return False elif not self._check_errors(): return False else: return True def _check_auth(self): if self.path.startswith('/auth'): authorization = self.headers.get('authorization', None) if authorization is not None: auth_type, credentials = authorization.split(None, 1) if auth_type.lower() == 'basic': credentials = base64.b64decode( credentials.encode('utf-8')) auth_user, auth_pass = credentials.decode( 'utf-8').split(':', 1) if username == auth_user and password == auth_pass: return True self.send_response(401) self.send_header( 'WWW-Authenticate', 'Basic realm="Fake HTTP Server"') self.end_headers() return False return True def _check_errors(self): if self.path.startswith('/badrequest'): self.send_response(400) self.end_headers() return False elif self.path.startswith('/notfound'): self.send_response(404) self.end_headers() return False elif self.path.startswith('/invaliderror'): self.send_response(444) self.end_headers() return False return True def do_POST(self): if not self._checks(): return input_data = self.rfile.read( int(self.headers.get('content-length'))) self.send_response(200) self.end_headers() self.wfile.write( codecs.encode( input_data.decode('utf-8'), 'rot-13').encode('utf-8')) def do_PUT(self): if not self._checks(): return input_data = self.rfile.read( int(self.headers.get('content-length'))) storage[self.path] = input_data self.send_response(200) self.end_headers() self.wfile.write(b'PUT OK') def do_GET(self): if not self._checks(): return self.send_response(200) self.end_headers() if self.path in storage: self.wfile.write(storage[self.path]) else: self.wfile.write(response) def log_request(*args): pass HTTPServer(('127.0.0.1', port), Handler).serve_forever() class Test_HttpClient(unittest.TestCase): USERNAME = 'john' PASSWORD = 'secret' PORT = 9876 URI_BASE = 'http://localhost:%(PORT)d' % locals() RESPONSE = b'Test_GET-HTTP-Response-Content' DUMMYDATA = b'fq28cnyp3ya8ltcy;ny2t8ay;iweuycowtc' def setUp(self): self.server_process = multiprocessing.Process(target=http_server, args=(self.PORT, self.USERNAME, self.PASSWORD, self.RESPONSE)) self.server_process.start() import time time.sleep(.1) def tearDown(self): self.server_process.terminate() import time time.sleep(.1) def test_UnknownResponse(self): client = HttpClient() path = self.URI_BASE + '/invaliderror' self.assertRaises(UnknownResponse, client.GET, path) def test_NotFound(self): client = HttpClient() path = self.URI_BASE + '/notfound' self.assertRaises(NotFound, client.GET, path) def test_Unauthorized(self): client = HttpClient('invalid-username', 'invalid-password') path = self.URI_BASE + '/auth' self.assertRaises(Unauthorized, client.GET, path) def test_BadRequest(self): client = HttpClient() path = self.URI_BASE + '/badrequest' self.assertRaises(BadRequest, client.GET, path) def test_GET(self): client = HttpClient() path = self.URI_BASE + '/noauth' self.assertEquals(client.GET(path), self.RESPONSE) def test_authenticated_GET(self): client = HttpClient(self.USERNAME, self.PASSWORD) path = self.URI_BASE + '/auth' self.assertEquals(client.GET(path), self.RESPONSE) def test_unauthenticated_GET(self): client = HttpClient() path = self.URI_BASE + '/auth' self.assertRaises(Unauthorized, client.GET, path) def test_POST(self): client = HttpClient() path = self.URI_BASE + '/noauth' self.assertEquals( client.POST( path, self.DUMMYDATA), codecs.encode( self.DUMMYDATA.decode('utf-8'), 'rot-13').encode('utf-8')) def test_authenticated_POST(self): client = HttpClient(self.USERNAME, self.PASSWORD) path = self.URI_BASE + '/auth' self.assertEquals( client.POST( path, self.DUMMYDATA), codecs.encode( self.DUMMYDATA.decode('utf-8'), 'rot-13').encode('utf-8')) def test_unauthenticated_POST(self): client = HttpClient() path = self.URI_BASE + '/auth' self.assertRaises(Unauthorized, client.POST, path, self.DUMMYDATA) def test_PUT(self): client = HttpClient() path = self.URI_BASE + '/noauth' self.assertEquals(client.PUT(path, self.DUMMYDATA), b'PUT OK') def test_GET_after_PUT(self): client = HttpClient() for i in range(10): path = self.URI_BASE + '/file.%(i)d.txt' % locals() client.PUT(path, self.RESPONSE + str(i).encode('utf-8')) self.assertEquals( client.GET(path), self.RESPONSE + str(i).encode('utf-8')) mygpoclient-1.9/mygpoclient/json.py000066400000000000000000000052321425512052500175750ustar00rootroot00000000000000# -*- coding: utf-8 -*- # gpodder.net API Client # Copyright (C) 2009-2013 Thomas Perl and the gPodder Team # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # Fix gPodder bug 900 (so "import json" doesn't import this module) from __future__ import absolute_import try: # Python 3 bytes = bytes except BaseException: # Python 2 bytes = str import json from mygpoclient import http # Additional exceptions for JSON-related errors class JsonException(Exception): pass class JsonClient(http.HttpClient): """A HttpClient with built-in JSON support This client will automatically marshal and unmarshal data for JSON-related web services so that code using this class will not need to care about (de-)serialization of data structures. """ def __init__(self, username=None, password=None): http.HttpClient.__init__(self, username, password) @staticmethod def encode(data): """Encodes a object into its JSON string repesentation >>> JsonClient.encode(None) is None True >>> JsonClient.encode([1,2,3]) == b'[1, 2, 3]' True >>> JsonClient.encode(42) == b'42' True """ if data is None: return None else: return json.dumps(data).encode('utf-8') @staticmethod def decode(data): """Decodes a response string to a Python object >>> JsonClient.decode(b'') >>> JsonClient.decode(b'[1,2,3]') [1, 2, 3] >>> JsonClient.decode(b'42') 42 """ if data == b'': return None data = data.decode('utf-8') try: return json.loads(data) except ValueError: raise JsonException('Value error while parsing response: ' + data) @staticmethod def _prepare_request(method, uri, data): data = JsonClient.encode(data) return http.HttpClient._prepare_request(method, uri, data) @staticmethod def _process_response(response): data = http.HttpClient._process_response(response) return JsonClient.decode(data) mygpoclient-1.9/mygpoclient/json_test.py000066400000000000000000000053031425512052500206330ustar00rootroot00000000000000# -*- coding: utf-8 -*- # gpodder.net API Client # Copyright (C) 2009-2013 Thomas Perl and the gPodder Team # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . try: # Python 3 from io import BytesIO from urllib import request except ImportError: # Python 2 from StringIO import StringIO as BytesIO import urllib2 as request from mygpoclient import json import unittest import minimock def fqname(o): return o.__module__ + "." + o.__name__ class Test_JsonClient(unittest.TestCase): PORT = 9876 URI_BASE = 'http://localhost:%(PORT)d' % locals() USERNAME = 'john' PASSWORD = 'secret' @classmethod def setUpClass(cls): cls.odName = fqname(request.OpenerDirector) cls.boName = fqname(request.build_opener) def setUp(self): self.mockopener = minimock.Mock(self.odName) request.build_opener = minimock.Mock(self.boName) request.build_opener.mock_returns = self.mockopener def tearDown(self): minimock.restore() def mock_setHttpResponse(self, value): self.mockopener.open.mock_returns = BytesIO(value) def test_parseResponse_worksWithDictionary(self): client = json.JsonClient(self.USERNAME, self.PASSWORD) self.mock_setHttpResponse(b'{"a": "B", "c": "D"}') items = list(sorted(client.GET(self.URI_BASE + '/').items())) self.assertEquals(items, [('a', 'B'), ('c', 'D')]) def test_parseResponse_worksWithIntegerList(self): client = json.JsonClient(self.USERNAME, self.PASSWORD) self.mock_setHttpResponse(b'[1,2,3,6,7]') self.assertEquals(client.GET(self.URI_BASE + '/'), [1, 2, 3, 6, 7]) def test_parseResponse_emptyString_returnsNone(self): client = json.JsonClient(self.USERNAME, self.PASSWORD) self.mock_setHttpResponse(b'') self.assertEquals(client.GET(self.URI_BASE + '/'), None) def test_invalidContent_raisesJsonException(self): client = json.JsonClient(self.USERNAME, self.PASSWORD) self.mock_setHttpResponse(b'this is not a valid json string') self.assertRaises(json.JsonException, client.GET, self.URI_BASE + '/') mygpoclient-1.9/mygpoclient/locator.py000066400000000000000000000325221425512052500202710ustar00rootroot00000000000000# -*- coding: utf-8 -*- # gpodder.net API Client # Copyright (C) 2009-2013 Thomas Perl and the gPodder Team # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import mygpoclient try: # Python 3 from urllib.parse import quote_plus, quote except ImportError: # Python 2 from urllib import quote_plus, quote from mygpoclient import util class Locator(object): """URI Locator for API endpoints This helper class abstracts the URIs for the gpodder.net webservice and provides a nice facility for generating API URIs and checking parameters. """ SIMPLE_FORMATS = ('opml', 'json', 'txt') SETTINGS_TYPES = ('account', 'device', 'podcast', 'episode') def __init__(self, username, root_url=mygpoclient.ROOT_URL, version=mygpoclient.VERSION): self._username = username if root_url.endswith('/'): root_url = root_url[:-1] if root_url.startswith('http'): self._simple_base = root_url self._base = '%(root_url)s/api/%(version)s' % locals() else: self._simple_base = 'http://%(root_url)s' % locals() self._base = 'http://%(root_url)s/api/%(version)s' % locals() @staticmethod def _convert_since(since): """Convert "since" into a numeric value This is internally used for value-checking. """ try: return int(since) except ValueError: raise ValueError('since must be a numeric value (or None)') def subscriptions_uri(self, device_id=None, format='opml'): """Get the Simple API URI for a subscription list >>> locator = Locator('john') >>> locator.subscriptions_uri('n800') 'http://gpodder.net/subscriptions/john/n800.opml' >>> locator.subscriptions_uri('ipod', 'txt') 'http://gpodder.net/subscriptions/john/ipod.txt' """ if format not in self.SIMPLE_FORMATS: raise ValueError('Unsupported file format') username = self._username if device_id is None: path = '%(username)s.%(format)s' % locals() else: path = '%(username)s/%(device_id)s.%(format)s' % locals() return util.join(self._simple_base, 'subscriptions', path) def toplist_uri(self, count=50, format='opml'): """Get the Simple API URI for the toplist >>> locator = Locator(None) >>> locator.toplist_uri() 'http://gpodder.net/toplist/50.opml' >>> locator.toplist_uri(70) 'http://gpodder.net/toplist/70.opml' >>> locator.toplist_uri(10, 'json') 'http://gpodder.net/toplist/10.json' """ if format not in self.SIMPLE_FORMATS: raise ValueError('Unsupported file format') filename = 'toplist/%(count)d.%(format)s' % locals() return util.join(self._simple_base, filename) def suggestions_uri(self, count=10, format='opml'): """Get the Simple API URI for user suggestions >>> locator = Locator('john') >>> locator.suggestions_uri() 'http://gpodder.net/suggestions/10.opml' >>> locator.suggestions_uri(50) 'http://gpodder.net/suggestions/50.opml' >>> locator.suggestions_uri(70, 'json') 'http://gpodder.net/suggestions/70.json' """ if format not in self.SIMPLE_FORMATS: raise ValueError('Unsupported file format') filename = 'suggestions/%(count)d.%(format)s' % locals() return util.join(self._simple_base, filename) def search_uri(self, query, format='opml'): """Get the Simple API URI for podcast search >>> locator = Locator(None) >>> locator.search_uri('outlaws') 'http://gpodder.net/search.opml?q=outlaws' >>> locator.search_uri(':something?', 'txt') 'http://gpodder.net/search.txt?q=%3Asomething%3F' >>> locator.search_uri('software engineering', 'json') 'http://gpodder.net/search.json?q=software+engineering' """ if format not in self.SIMPLE_FORMATS: raise ValueError('Unsupported file format') query = quote_plus(query) filename = 'search.%(format)s?q=%(query)s' % locals() return util.join(self._simple_base, filename) def add_remove_subscriptions_uri(self, device_id): """Get the Advanced API URI for uploading list diffs >>> locator = Locator('bill') >>> locator.add_remove_subscriptions_uri('n810') 'http://gpodder.net/api/2/subscriptions/bill/n810.json' """ filename = '%(device_id)s.json' % locals() return util.join(self._base, 'subscriptions', self._username, filename) def subscription_updates_uri(self, device_id, since=None): """Get the Advanced API URI for downloading list diffs The parameter "since" is optional and should be a numeric value (otherwise a ValueError is raised). >>> locator = Locator('jen') >>> locator.subscription_updates_uri('n900') 'http://gpodder.net/api/2/subscriptions/jen/n900.json' >>> locator.subscription_updates_uri('n900', 1234) 'http://gpodder.net/api/2/subscriptions/jen/n900.json?since=1234' """ filename = '%(device_id)s.json' % locals() if since is not None: since = self._convert_since(since) filename += '?since=%(since)d' % locals() return util.join(self._base, 'subscriptions', self._username, filename) def upload_episode_actions_uri(self): """Get the Advanced API URI for uploading episode actions >>> locator = Locator('thp') >>> locator.upload_episode_actions_uri() 'http://gpodder.net/api/2/episodes/thp.json' """ filename = self._username + '.json' return util.join(self._base, 'episodes', filename) def download_episode_actions_uri(self, since=None, podcast=None, device_id=None): """Get the Advanced API URI for downloading episode actions The parameter "since" is optional and should be a numeric value (otherwise a ValueError is raised). Both "podcast" and "device_id" are optional and exclusive: "podcast" should be a podcast URL "device_id" should be a device ID >>> locator = Locator('steve') >>> locator.download_episode_actions_uri() 'http://gpodder.net/api/2/episodes/steve.json' >>> locator.download_episode_actions_uri(since=1337) 'http://gpodder.net/api/2/episodes/steve.json?since=1337' >>> locator.download_episode_actions_uri(podcast='http://example.org/episodes.rss') 'http://gpodder.net/api/2/episodes/steve.json?podcast=http%3A//example.org/episodes.rss' >>> locator.download_episode_actions_uri(since=2000, podcast='http://example.com/') 'http://gpodder.net/api/2/episodes/steve.json?since=2000&podcast=http%3A//example.com/' >>> locator.download_episode_actions_uri(device_id='ipod') 'http://gpodder.net/api/2/episodes/steve.json?device=ipod' >>> locator.download_episode_actions_uri(since=54321, device_id='ipod') 'http://gpodder.net/api/2/episodes/steve.json?since=54321&device=ipod' """ if podcast is not None and device_id is not None: raise ValueError('must not specify both "podcast" and "device_id"') filename = self._username + '.json' params = [] if since is not None: since = str(self._convert_since(since)) params.append(('since', since)) if podcast is not None: params.append(('podcast', podcast)) if device_id is not None: params.append(('device', device_id)) if params: filename += '?' + '&'.join('%s=%s' % (key, quote(value)) for key, value in params) return util.join(self._base, 'episodes', filename) def device_settings_uri(self, device_id): """Get the Advanced API URI for setting per-device settings uploads >>> locator = Locator('mike') >>> locator.device_settings_uri('ipod') 'http://gpodder.net/api/2/devices/mike/ipod.json' """ filename = '%(device_id)s.json' % locals() return util.join(self._base, 'devices', self._username, filename) def device_list_uri(self): """Get the Advanced API URI for retrieving the device list >>> locator = Locator('jeff') >>> locator.device_list_uri() 'http://gpodder.net/api/2/devices/jeff.json' """ filename = self._username + '.json' return util.join(self._base, 'devices', filename) def toptags_uri(self, count=50): """Get the Advanced API URI for retrieving the top Tags >>> locator = Locator(None) >>> locator.toptags_uri() 'http://gpodder.net/api/2/tags/50.json' >>> locator.toptags_uri(70) 'http://gpodder.net/api/2/tags/70.json' """ filename = '%(count)d.json' % locals() return util.join(self._base, 'tags', filename) def podcasts_of_a_tag_uri(self, tag, count=50): """Get the Advanced API URI for retrieving the top Podcasts of a Tag >>> locator = Locator(None) >>> locator.podcasts_of_a_tag_uri('linux') 'http://gpodder.net/api/2/tag/linux/50.json' >>> locator.podcasts_of_a_tag_uri('linux',70) 'http://gpodder.net/api/2/tag/linux/70.json' """ filename = '%(tag)s/%(count)d.json' % locals() return util.join(self._base, 'tag', filename) def podcast_data_uri(self, podcast_url): """Get the Advanced API URI for retrieving Podcast Data >>> locator = Locator(None) >>> locator.podcast_data_uri('http://podcast.com') 'http://gpodder.net/api/2/data/podcast.json?url=http%3A//podcast.com' """ filename = 'podcast.json?url=%s' % quote(podcast_url) return util.join(self._base, 'data', filename) def episode_data_uri(self, podcast_url, episode_url): """Get the Advanced API URI for retrieving Episode Data >>> locator = Locator(None) >>> locator.episode_data_uri('http://podcast.com','http://podcast.com/foo') 'http://gpodder.net/api/2/data/episode.json?podcast=http%3A//podcast.com&url=http%3A//podcast.com/foo' """ filename = 'episode.json?podcast=%s&url=%s' % ( quote(podcast_url), quote(episode_url)) return util.join(self._base, 'data', filename) def favorite_episodes_uri(self): """Get the Advanced API URI for listing favorite episodes >>> locator = Locator('mike') >>> locator.favorite_episodes_uri() 'http://gpodder.net/api/2/favorites/mike.json' """ filename = self._username + '.json' return util.join(self._base, 'favorites', filename) def settings_uri(self, type, scope_param1, scope_param2): """Get the Advanced API URI for retrieving or saving Settings Depending on the Type of setting scope_param2 or scope_param1 and scope_param2 are not necessary. >>> locator = Locator('joe') >>> locator.settings_uri('account',None,None) 'http://gpodder.net/api/2/settings/joe/account.json' >>> locator.settings_uri('device','foodevice',None) 'http://gpodder.net/api/2/settings/joe/device.json?device=foodevice' >>> locator.settings_uri('podcast','http://podcast.com',None) 'http://gpodder.net/api/2/settings/joe/podcast.json?podcast=http%3A//podcast.com' >>> locator.settings_uri('episode','http://podcast.com','http://podcast.com/foo') 'http://gpodder.net/api/2/settings/joe/episode.json?podcast=http%3A//podcast.com&episode=http%3A//podcast.com/foo' """ if type not in self.SETTINGS_TYPES: raise ValueError('Unsupported Setting Type') filename = self._username + '/%(type)s.json' % locals() if type == 'device': if scope_param1 is None: raise ValueError('Devicename not specified') filename += '?device=%(scope_param1)s' % locals() if type == 'podcast': if scope_param1 is None: raise ValueError('Podcast URL not specified') filename += '?podcast=%s' % quote(scope_param1) if type == 'episode': if (scope_param1 is None) or (scope_param2 is None): raise ValueError('Podcast or Episode URL not specified') filename += '?podcast=%s&episode=%s' % ( quote(scope_param1), quote(scope_param2)) return util.join(self._base, 'settings', filename) def root_uri(self): """ Get the server's root URI. >>> locator = Locator(None) >>> locator.root_uri() 'http://gpodder.net' """ return self._simple_base mygpoclient-1.9/mygpoclient/locator_test.py000066400000000000000000000114011425512052500213210ustar00rootroot00000000000000# -*- coding: utf-8 -*- # gpodder.net API Client # Copyright (C) 2009-2013 Thomas Perl and the gPodder Team # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from mygpoclient import locator import unittest class Test_Exceptions(unittest.TestCase): def setUp(self): self.locator = locator.Locator('jane') def test_subscriptions_uri_exceptions(self): """Test if unsupported formats raise a ValueError""" self.assertRaises(ValueError, self.locator.subscriptions_uri, 'gpodder', 'html') def test_toplist_uri_exceptions(self): """Test if unsupported formats raise a ValueError""" self.assertRaises(ValueError, self.locator.toplist_uri, 10, 'html') def test_suggestions_uri_exceptions(self): """Test if unsupported formats raise a ValueError""" self.assertRaises(ValueError, self.locator.suggestions_uri, 20, 'jpeg') def test_search_uri_exception(self): """Test if unsupported formats raise a ValueError""" self.assertRaises(ValueError, self.locator.search_uri, 30, 'mp3') def test_subscription_updates_uri_exceptions(self): """Test if wrong "since" values raise a ValueError""" self.assertRaises(ValueError, self.locator.subscription_updates_uri, 'ipod', 'anytime') def test_download_episode_actions_uri_exceptions(self): """Test if using both "podcast" and "device_id" raises a ValueError""" self.assertRaises(ValueError, self.locator.download_episode_actions_uri, podcast='http://example.org/episodes.rss', device_id='gpodder') def test_device_settings_uri_exception(self): """Test if using no parameter for a device Setting raises a ValueError""" self.assertRaises(ValueError, self.locator.settings_uri, type='device', scope_param1=None, scope_param2=None) def test_podcast_settings_uri_exception(self): """Test if using no parameter for a podcast Setting raises a ValueError""" self.assertRaises(ValueError, self.locator.settings_uri, type='podcast', scope_param1=None, scope_param2=None) def test_episode_settings_uri_exception(self): """Test if only using one parameter for a episode Setting raises a ValueError""" self.assertRaises(ValueError, self.locator.settings_uri, type='episode', scope_param1='http://www.podcast.com', scope_param2=None) def test_unsupported_settings_uri_exception2(self): """Test if unsupported setting type raises a ValueError""" self.assertRaises(ValueError, self.locator.settings_uri, type='foobar', scope_param1=None, scope_param2=None) def test_subscriptions_uri_no_device(self): """Test that no device returns user subscriptions""" self.assertEquals(self.locator.subscriptions_uri(), 'http://gpodder.net/subscriptions/jane.opml') def test_root_uri(self): """Test that root_uri trivially works""" self.assertEquals(self.locator.root_uri(), 'http://gpodder.net') def test_create_with_url(self): """Test locator creation with a root URL instead of host""" loc = locator.Locator('hello', 'https://gpo.self.hosted/my') self.assertEquals(loc.toplist_uri(), 'https://gpo.self.hosted/my/toplist/50.opml') def test_create_with_url_slash(self): """Test locator creation with a root URL ending with a slash""" loc = locator.Locator('hello', 'https://gpo.self.hosted/my/') self.assertEquals(loc.toplist_uri(), 'https://gpo.self.hosted/my/toplist/50.opml') def test_create_with_host(self): """Test locator creation with a host""" loc = locator.Locator('hello', 'gpo.self.hosted') self.assertEquals(loc.toplist_uri(), 'http://gpo.self.hosted/toplist/50.opml') mygpoclient-1.9/mygpoclient/public.py000066400000000000000000000155701425512052500201100ustar00rootroot00000000000000# -*- coding: utf-8 -*- # gpodder.net API Client # Copyright (C) 2009-2013 Thomas Perl and the gPodder Team # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import mygpoclient from mygpoclient import locator from mygpoclient import json from mygpoclient import simple class Tag(object): """Container class for a tag in the top tag list Attributes: tag - The name of the tag usage - Usage of the tag """ REQUIRED_KEYS = ('tag', 'usage') def __init__(self, tag, usage): self.tag = tag self.usage = usage @classmethod def from_dict(cls, d): for key in cls.REQUIRED_KEYS: if key not in d: raise ValueError('Missing keys for tag') return cls(*(d.get(k) for k in cls.REQUIRED_KEYS)) def __eq__(self, other): """Test two tag objects for equality >>> Tag('u', 123) == Tag('u', 123) True >>> Tag('u', 123) == Tag('a', 345) False >>> Tag('u', 123) == 'x' False """ if not isinstance(other, self.__class__): return False return all(getattr(self, k) == getattr(other, k) for k in self.REQUIRED_KEYS) class Episode(object): """Container Class for Episodes Attributes: title - url - podcast_title - podcast_url - description - website - released - mygpo_link - """ REQUIRED_KEYS = ('title', 'url', 'podcast_title', 'podcast_url', 'description', 'website', 'released', 'mygpo_link') def __init__(self, title, url, podcast_title, podcast_url, description, website, released, mygpo_link): self.title = title self.url = url self.podcast_title = podcast_title self.podcast_url = podcast_url self.description = description self.website = website self.released = released self.mygpo_link = mygpo_link @classmethod def from_dict(cls, d): for key in cls.REQUIRED_KEYS: if key not in d: raise ValueError('Missing keys for episode') return cls(*(d.get(k) for k in cls.REQUIRED_KEYS)) def __eq__(self, other): """Test two Episode objects for equality >>> Episode('a','b','c','d','e','f','g','h') == Episode('a','b','c','d','e','f','g','h') True >>> Episode('a','b','c','d','e','f','g','h') == Episode('s','t','u','v','w','x','y','z') False >>> Episode('a','b','c','d','e','f','g','h') == 'x' False """ if not isinstance(other, self.__class__): return False return all(getattr(self, k) == getattr(other, k) for k in self.REQUIRED_KEYS) class PublicClient(object): """Client for the gpodder.net "anonymous" API This is the API client implementation that provides a pythonic interface to the parts of the gpodder.net Simple API that don't need user authentication. """ FORMAT = 'json' def __init__(self, root_url=mygpoclient.ROOT_URL, client_class=json.JsonClient): """Creates a new Public API client The parameter root_url is optional and defaults to the main webservice. It can be either a hostname or a full URL (to force https, for instance). The parameter client_class is optional and should not need to be changed in normal use cases. If it is changed, it should provide the same interface as the json.JsonClient class in mygpoclient. """ self._locator = locator.Locator(None, root_url) self._client = client_class(None, None) def get_toplist(self, count=mygpoclient.TOPLIST_DEFAULT): """Get a list of most-subscribed podcasts Returns a list of simple.Podcast objects. The parameter "count" is optional and describes the amount of podcasts that are returned. The default value is 50, the minimum value is 1 and the maximum value is 100. """ uri = self._locator.toplist_uri(count, self.FORMAT) return [simple.Podcast.from_dict(x) for x in self._client.GET(uri)] def search_podcasts(self, query): """Search for podcasts on the webservice Returns a list of simple.Podcast objects. The parameter "query" specifies the search query as a string. """ uri = self._locator.search_uri(query, self.FORMAT) return [simple.Podcast.from_dict(x) for x in self._client.GET(uri)] def get_podcasts_of_a_tag(self, tag, count=mygpoclient.TOPLIST_DEFAULT): """Get a list of most-subscribed podcasts of a Tag Returns a list of simple.Podcast objects. The parameter "tag" specifies the tag as a String The parameter "count" is optional and describes the amount of podcasts that are returned. The default value is 50, the minimum value is 1 and the maximum value is 100. """ uri = self._locator.podcasts_of_a_tag_uri(tag, count) return [simple.Podcast.from_dict(x) for x in self._client.GET(uri)] def get_toptags(self, count=mygpoclient.TOPLIST_DEFAULT): """Get a list of most-used tags Returns a list of Tag objects. The parameter "count" is optional and describes the amount of podcasts that are returned. The default value is 50, the minimum value is 1 and the maximum value is 100. """ uri = self._locator.toptags_uri(count) return [Tag.from_dict(x) for x in self._client.GET(uri)] def get_podcast_data(self, podcast_uri): """Get Metadata for the specified Podcast Returns a simple.Podcast object. The parameter "podcast_uri" specifies the URL of the Podcast. """ uri = self._locator.podcast_data_uri(podcast_uri) return simple.Podcast.from_dict(self._client.GET(uri)) def get_episode_data(self, podcast_uri, episode_uri): """Get Metadata for the specified Episode Returns a Episode object. The parameter "podcast_uri" specifies the URL of the Podcast, which this Episode belongs to The parameter "episode_uri" specifies the URL of the Episode """ uri = self._locator.episode_data_uri(podcast_uri, episode_uri) return Episode.from_dict(self._client.GET(uri)) mygpoclient-1.9/mygpoclient/public_test.py000066400000000000000000000234321425512052500211430ustar00rootroot00000000000000# -*- coding: utf-8 -*- # gpodder.net API Client # Copyright (C) 2009-2013 Thomas Perl and the gPodder Team # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from mygpoclient import public from mygpoclient import simple from mygpoclient import testing import unittest class Test_Tag(unittest.TestCase): def test_tagFromDict_raisesValueError_missingKey(self): self.assertRaises(ValueError, public.Tag.from_dict, {'tag': 'abcde'}) class Test_Episode(unittest.TestCase): def test_episodeFromDict_raisesValueError_missingKey(self): self.assertRaises( ValueError, public.Episode.from_dict, { 'title': 'foobar', 'podcast_url': 'http://www.podcast.com'}) class Test_PublicClient(unittest.TestCase): TOPLIST_JSON = b""" [{ "website": "http://linuxoutlaws.com/podcast", "description": "Open source talk with a serious attitude", "title": "Linux Outlaws", "url": "http://feeds.feedburner.com/linuxoutlaws", "subscribers_last_week": 1736, "subscribers": 1736, "mygpo_link": "http://www.gpodder.net/podcast/11092", "logo_url": "http://linuxoutlaws.com/files/albumart-itunes.jpg" }, { "website": "http://syndication.mediafly.com/redirect/show/d581e9b773784df7a56f37e1138c037c", "description": "We are not talking dentistry here; FLOSS all about Free Libre Open Source Software. Join hosts Randal Schwartz and Leo Laporte every Saturday as they talk with the most interesting and important people in the Open Source and Free Software community.", "title": "FLOSS Weekly Video (large)", "url": "http://feeds.twit.tv/floss_video_large", "subscribers_last_week": 50, "subscribers": 50, "mygpo_link": "http://www.gpodder.net/podcast/31991", "logo_url": "http://static.mediafly.com/publisher/images/06cecab60c784f9d9866f5dcb73227c3/icon-150x150.png" }] """ TOPLIST = [ simple.Podcast('http://feeds.feedburner.com/linuxoutlaws', 'Linux Outlaws', 'Open source talk with a serious attitude', 'http://linuxoutlaws.com/podcast', 1736, 1736, 'http://www.gpodder.net/podcast/11092', 'http://linuxoutlaws.com/files/albumart-itunes.jpg'), simple.Podcast('http://feeds.twit.tv/floss_video_large', 'FLOSS Weekly Video (large)', 'We are not talking dentistry here; FLOSS all about Free Libre Open Source Software. Join hosts Randal Schwartz and Leo Laporte every Saturday as they talk with the most interesting and important people in the Open Source and Free Software community.', 'http://syndication.mediafly.com/redirect/show/d581e9b773784df7a56f37e1138c037c', 50, 50, 'http://www.gpodder.net/podcast/31991', 'http://static.mediafly.com/publisher/images/06cecab60c784f9d9866f5dcb73227c3/icon-150x150.png'), ] SEARCHRESULT_JSON = b""" [{ "website": "http://linuxoutlaws.com/podcast", "description": "Open source talk with a serious attitude", "title": "Linux Outlaws", "url": "http://feeds.feedburner.com/linuxoutlaws", "subscribers_last_week": 1736, "subscribers": 1736, "mygpo_link": "http://www.gpodder.net/podcast/11092", "logo_url": "http://linuxoutlaws.com/files/albumart-itunes.jpg" }, { "website": "http://syndication.mediafly.com/redirect/show/d581e9b773784df7a56f37e1138c037c", "description": "We are not talking dentistry here; FLOSS all about Free Libre Open Source Software. Join hosts Randal Schwartz and Leo Laporte every Saturday as they talk with the most interesting and important people in the Open Source and Free Software community.", "title": "FLOSS Weekly Video (large)", "url": "http://feeds.twit.tv/floss_video_large", "subscribers_last_week": 50, "subscribers": 50, "mygpo_link": "http://www.gpodder.net/podcast/31991", "logo_url": "http://static.mediafly.com/publisher/images/06cecab60c784f9d9866f5dcb73227c3/icon-150x150.png" }] """ SEARCHRESULT = [ simple.Podcast('http://feeds.feedburner.com/linuxoutlaws', 'Linux Outlaws', 'Open source talk with a serious attitude', 'http://linuxoutlaws.com/podcast', 1736, 1736, 'http://www.gpodder.net/podcast/11092', 'http://linuxoutlaws.com/files/albumart-itunes.jpg'), simple.Podcast('http://feeds.twit.tv/floss_video_large', 'FLOSS Weekly Video (large)', 'We are not talking dentistry here; FLOSS all about Free Libre Open Source Software. Join hosts Randal Schwartz and Leo Laporte every Saturday as they talk with the most interesting and important people in the Open Source and Free Software community.', 'http://syndication.mediafly.com/redirect/show/d581e9b773784df7a56f37e1138c037c', 50, 50, 'http://www.gpodder.net/podcast/31991', 'http://static.mediafly.com/publisher/images/06cecab60c784f9d9866f5dcb73227c3/icon-150x150.png'), ] TOPTAGS_JSON = b""" [ {"tag": "Technology", "usage": 530 }, {"tag": "Arts", "usage": 400} ] """ TOPTAGS = [ public.Tag('Technology', 530), public.Tag('Arts', 400) ] PODCAST_JSON = b""" { "website": "http://linuxoutlaws.com/podcast", "description": "Open source talk with a serious attitude", "title": "Linux Outlaws", "url": "http://feeds.feedburner.com/linuxoutlaws", "subscribers_last_week": 1736, "subscribers": 1736, "mygpo_link": "http://www.gpodder.net/podcast/11092", "logo_url": "http://linuxoutlaws.com/files/albumart-itunes.jpg" } """ PODCAST = simple.Podcast('http://feeds.feedburner.com/linuxoutlaws', 'Linux Outlaws', 'Open source talk with a serious attitude', 'http://linuxoutlaws.com/podcast', 1736, 1736, 'http://www.gpodder.net/podcast/11092', 'http://linuxoutlaws.com/files/albumart-itunes.jpg') EPISODE_JSON = b""" {"title": "TWiT 245: No Hitler For You", "url": "http://www.podtrac.com/pts/redirect.mp3/aolradio.podcast.aol.com/twit/twit0245.mp3", "podcast_title": "this WEEK in TECH - MP3 Edition", "podcast_url": "http://leo.am/podcasts/twit", "description": "[...]", "website": "http://www.podtrac.com/pts/redirect.mp3/aolradio.podcast.aol.com/twit/twit0245.mp3", "released": "2010-12-25T00:30:00", "mygpo_link": "http://gpodder.net/episode/1046492"} """ EPISODE = public.Episode('TWiT 245: No Hitler For You', 'http://www.podtrac.com/pts/redirect.mp3/aolradio.podcast.aol.com/twit/twit0245.mp3', 'this WEEK in TECH - MP3 Edition', 'http://leo.am/podcasts/twit', '[...]', 'http://www.podtrac.com/pts/redirect.mp3/aolradio.podcast.aol.com/twit/twit0245.mp3', '2010-12-25T00:30:00', 'http://gpodder.net/episode/1046492' ) def setUp(self): self.fake_client = testing.FakeJsonClient() self.client = public.PublicClient(client_class=self.fake_client) def test_getToplist(self): self.fake_client.response_value = self.TOPLIST_JSON result = self.client.get_toplist() self.assertEquals(result, self.TOPLIST) self.assertEquals(len(self.fake_client.requests), 1) def test_searchPodcasts(self): self.fake_client.response_value = self.SEARCHRESULT_JSON result = self.client.search_podcasts('wicked') self.assertEquals(result, self.SEARCHRESULT) self.assertEquals(len(self.fake_client.requests), 1) def test_getPodcastsOfATag(self): self.fake_client.response_value = self.SEARCHRESULT_JSON result = self.client.get_podcasts_of_a_tag('wicked') self.assertEquals(result, self.SEARCHRESULT) self.assertEquals(len(self.fake_client.requests), 1) def test_getTopTags(self): self.fake_client.response_value = self.TOPTAGS_JSON result = self.client.get_toptags() self.assertEquals(result, self.TOPTAGS) self.assertEquals(len(self.fake_client.requests), 1) def test_getPodcastData(self): self.fake_client.response_value = self.PODCAST_JSON result = self.client.get_podcast_data( 'http://feeds.feedburner.com/linuxoutlaws') self.assertEquals(result, self.PODCAST) self.assertEquals(len(self.fake_client.requests), 1) def test_getEpisodeData(self): self.fake_client.response_value = self.EPISODE_JSON result = self.client.get_episode_data( 'http://leo.am/podcasts/twit', 'http://www.podtrac.com/pts/redirect.mp3/aolradio.podcast.aol.com/twit/twit0245.mp3') self.assertEquals(result, self.EPISODE) self.assertEquals(len(self.fake_client.requests), 1) mygpoclient-1.9/mygpoclient/simple.py000066400000000000000000000131141425512052500201130ustar00rootroot00000000000000# -*- coding: utf-8 -*- # gpodder.net API Client # Copyright (C) 2009-2013 Thomas Perl and the gPodder Team # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from functools import wraps import mygpoclient from mygpoclient import locator from mygpoclient import json class MissingCredentials(Exception): """ Raised when instantiating a SimpleClient without credentials """ def needs_credentials(f): """ apply to all methods that initiate requests that require credentials """ @wraps(f) def _wrapper(self, *args, **kwargs): if not self.username or not self.password: raise MissingCredentials return f(self, *args, **kwargs) return _wrapper class Podcast(object): """Container class for a podcast Encapsulates the metadata for a podcast. Attributes: url - The URL of the podcast feed title - The title of the podcast description - The description of the podcast """ REQUIRED_FIELDS = ('url', 'title', 'description', 'website', 'subscribers', 'subscribers_last_week', 'mygpo_link', 'logo_url') def __init__(self, url, title, description, website, subscribers, subscribers_last_week, mygpo_link, logo_url): self.url = url self.title = title self.description = description self.website = website self.subscribers = subscribers self.subscribers_last_week = subscribers_last_week self.mygpo_link = mygpo_link self.logo_url = logo_url @classmethod def from_dict(cls, d): for key in cls.REQUIRED_FIELDS: if key not in d: raise ValueError('Missing keys for toplist podcast') return cls(*(d.get(k) for k in cls.REQUIRED_FIELDS)) def __eq__(self, other): """Test two Podcast objects for equality >>> Podcast('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') == Podcast('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') True >>> Podcast('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') == Podcast('s', 't', 'u', 'v', 'w', 'x', 'y', 'z') False >>> Podcast('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') == 'a' False """ if not isinstance(other, self.__class__): return False return all(getattr(self, k) == getattr(other, k) for k in self.REQUIRED_FIELDS) class SimpleClient(object): """Client for the gpodder.net Simple API This is the API client implementation that provides a pythonic interface to the gpodder.net Simple API. """ FORMAT = 'json' def __init__(self, username, password, root_url=mygpoclient.ROOT_URL, client_class=json.JsonClient): """Creates a new Simple API client Username and password must be specified and are the user's login data for the webservice. The parameter root_url is optional and defaults to the main webservice. It can be either a hostname or a full URL (to force https, for instance). The parameter client_class is optional and should not need to be changed in normal use cases. If it is changed, it should provide the same interface as the json.JsonClient class in mygpoclient. """ self.username = username self.password = password self._locator = locator.Locator(username, root_url) self._client = client_class(username, password) @needs_credentials def get_subscriptions(self, device_id): """Get a list of subscriptions for a device Returns a list of URLs (one per subscription) for the given device_id that reflects the current list of subscriptions. Raises http.NotFound if the device does not exist. """ uri = self._locator.subscriptions_uri(device_id, self.FORMAT) return self._client.GET(uri) @needs_credentials def put_subscriptions(self, device_id, urls): """Update a device's subscription list Sets the server-side subscription list for the device "device_id" to be equivalent to the URLs in the list of strings "urls". The device will be created if it does not yet exist. Returns True if the update was successful, False otherwise. """ uri = self._locator.subscriptions_uri(device_id, self.FORMAT) return self._client.PUT(uri, urls) is None @needs_credentials def get_suggestions(self, count=10): """Get podcast suggestions for the user Returns a list of Podcast objects that are to be suggested to the user. The parameter count is optional and if specified has to be a value between 1 and 100 (with 10 being the default), and determines how much search results are returned (at maximum). """ uri = self._locator.suggestions_uri(count, self.FORMAT) return [Podcast.from_dict(x) for x in self._client.GET(uri)] @property def locator(self): """ read-only access to the locator """ return self._locator mygpoclient-1.9/mygpoclient/simple_test.py000066400000000000000000000135321425512052500211560ustar00rootroot00000000000000# -*- coding: utf-8 -*- # gpodder.net API Client # Copyright (C) 2009-2013 Thomas Perl and the gPodder Team # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from mygpoclient import simple from mygpoclient import testing import unittest class Test_Podcast(unittest.TestCase): def test_podcastFromDict_raisesValueError_missingKey(self): self.assertRaises(ValueError, simple.Podcast.from_dict, {'url': 'a', 'title': 'b'}) class Test_SimpleClient(unittest.TestCase): USERNAME = 'a' PASSWORD = 'b' DEVICE_NAME = 'x' SUBSCRIPTIONS = [ 'http://lugradio.org/episodes.rss', 'http://feeds2.feedburner.com/LinuxOutlaws', ] SUBSCRIPTIONS_JSON = b""" ["http://lugradio.org/episodes.rss", "http://feeds2.feedburner.com/LinuxOutlaws"] """ SUGGESTIONS = [ simple.Podcast('http://feeds.feedburner.com/linuxoutlaws', 'Linux Outlaws', 'Open source talk with a serious attitude', 'http://linuxoutlaws.com/podcast', 1736, 1736, 'http://www.gpodder.net/podcast/11092', 'http://linuxoutlaws.com/files/albumart-itunes.jpg'), simple.Podcast('http://feeds.twit.tv/floss_video_large', 'FLOSS Weekly Video (large)', 'We are not talking dentistry here; FLOSS all about Free Libre Open Source Software. Join hosts Randal Schwartz and Leo Laporte every Saturday as they talk with the most interesting and important people in the Open Source and Free Software community.', 'http://syndication.mediafly.com/redirect/show/d581e9b773784df7a56f37e1138c037c', 50, 50, 'http://www.gpodder.net/podcast/31991', 'http://static.mediafly.com/publisher/images/06cecab60c784f9d9866f5dcb73227c3/icon-150x150.png'), ] SUGGESTIONS_JSON = b""" [{ "website": "http://linuxoutlaws.com/podcast", "description": "Open source talk with a serious attitude", "title": "Linux Outlaws", "url": "http://feeds.feedburner.com/linuxoutlaws", "subscribers_last_week": 1736, "subscribers": 1736, "mygpo_link": "http://www.gpodder.net/podcast/11092", "logo_url": "http://linuxoutlaws.com/files/albumart-itunes.jpg" }, { "website": "http://syndication.mediafly.com/redirect/show/d581e9b773784df7a56f37e1138c037c", "description": "We are not talking dentistry here; FLOSS all about Free Libre Open Source Software. Join hosts Randal Schwartz and Leo Laporte every Saturday as they talk with the most interesting and important people in the Open Source and Free Software community.", "title": "FLOSS Weekly Video (large)", "url": "http://feeds.twit.tv/floss_video_large", "subscribers_last_week": 50, "subscribers": 50, "mygpo_link": "http://www.gpodder.net/podcast/31991", "logo_url": "http://static.mediafly.com/publisher/images/06cecab60c784f9d9866f5dcb73227c3/icon-150x150.png" }] """ def setUp(self): self.fake_client = testing.FakeJsonClient() self.client = simple.SimpleClient(self.USERNAME, self.PASSWORD, client_class=self.fake_client) def test_putSubscriptions(self): self.fake_client.response_value = b'' result = self.client.put_subscriptions( self.DEVICE_NAME, self.SUBSCRIPTIONS) self.assertEquals(result, True) self.assertEquals(len(self.fake_client.requests), 1) def test_getSubscriptions(self): self.fake_client.response_value = self.SUBSCRIPTIONS_JSON subscriptions = self.client.get_subscriptions(self.DEVICE_NAME) self.assertEquals(subscriptions, self.SUBSCRIPTIONS) self.assertEquals(len(self.fake_client.requests), 1) def test_getSuggestions(self): self.fake_client.response_value = self.SUGGESTIONS_JSON suggestions = self.client.get_suggestions(50) self.assertEquals(suggestions, self.SUGGESTIONS) self.assertEquals(len(self.fake_client.requests), 1) class Test_MissingCredentials(unittest.TestCase): DEVICE_NAME = 'unit-test-device' def test_getSubscriptions_UserAndPassAreNone(self): client = simple.SimpleClient( None, None, client_class=testing.FakeJsonClient()) self.assertRaises(simple.MissingCredentials, client.get_subscriptions, (self.DEVICE_NAME,)) def test_getSubscriptions_EmptyUserAndPass(self): client = simple.SimpleClient( '', '', client_class=testing.FakeJsonClient()) self.assertRaises(simple.MissingCredentials, client.get_subscriptions, (self.DEVICE_NAME,)) def test_getSubscriptions_EmptyPassword(self): client = simple.SimpleClient( 'user', '', client_class=testing.FakeJsonClient()) self.assertRaises(simple.MissingCredentials, client.get_subscriptions, (self.DEVICE_NAME,)) def test_getSubscriptions_EmptyUsername(self): client = simple.SimpleClient( '', 'pass', client_class=testing.FakeJsonClient()) self.assertRaises(simple.MissingCredentials, client.get_subscriptions, (self.DEVICE_NAME,)) mygpoclient-1.9/mygpoclient/testing.py000066400000000000000000000033731425512052500203050ustar00rootroot00000000000000# -*- coding: utf-8 -*- # gpodder.net API Client # Copyright (C) 2009-2013 Thomas Perl and the gPodder Team # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from mygpoclient import json class FakeJsonClient(object): """Fake implementation of a JsonClient used for testing Set the response using response_value and check the list of requests this object got using the requests list. """ def __init__(self): self.requests = [] self.response_value = '' def __call__(self, *args, **kwargs): """Fake a constructor for an existing object >>> fake_class = FakeJsonClient() >>> fake_object = fake_class('username', 'password') >>> fake_object == fake_class True """ return self def _request(self, method, uri, data): self.requests.append((method, uri, data)) data = json.JsonClient.encode(data) return json.JsonClient.decode(self.response_value) def GET(self, uri): return self._request('GET', uri, None) def POST(self, uri, data): return self._request('POST', uri, data) def PUT(self, uri, data): return self._request('PUT', uri, data) mygpoclient-1.9/mygpoclient/util.py000066400000000000000000000053461425512052500176070ustar00rootroot00000000000000# -*- coding: utf-8 -*- # gpodder.net API Client # Copyright (C) 2009-2013 Thomas Perl and the gPodder Team # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import datetime def join(*args): """Join separate URL parts to a full URL""" return '/'.join(args) def iso8601_to_datetime(s): """Convert a ISO8601-formatted string to datetime >>> iso8601_to_datetime('2009-12-29T19:25:33') datetime.datetime(2009, 12, 29, 19, 25, 33) >>> iso8601_to_datetime('2009-12-29T19:25:33.1') datetime.datetime(2009, 12, 29, 19, 25, 33, 100000) >>> iso8601_to_datetime('2009-12-29T19:25:33Z') datetime.datetime(2009, 12, 29, 19, 25, 33) >>> iso8601_to_datetime('xXxXxXxXxxxxXxxxXxx') >>> """ for format in ('%Y-%m-%dT%H:%M:%S', '%Y-%m-%dT%H:%M:%S.%f', '%Y-%m-%dT%H:%M:%SZ'): try: return datetime.datetime.strptime(s, format) except ValueError: continue return None def datetime_to_iso8601(dt): """Convert a datetime to a ISO8601-formatted string >>> datetime_to_iso8601(datetime.datetime(2009, 12, 29, 19, 25, 33)) '2009-12-29T19:25:33' """ return dt.strftime('%Y-%m-%dT%H:%M:%S') def position_to_seconds(s): """Convert a position string to its amount of seconds >>> position_to_seconds('00:00:01') 1 >>> position_to_seconds('00:01:00') 60 >>> position_to_seconds('01:00:00') 3600 >>> position_to_seconds('02:59:59') 10799 >>> position_to_seconds('100:00:00') 360000 """ hours, minutes, seconds = (int(x) for x in s.split(':', 2)) return (((hours * 60) + minutes) * 60) + seconds def seconds_to_position(seconds): """Convert the amount of seconds to a position string >>> seconds_to_position(1) '00:00:01' >>> seconds_to_position(60) '00:01:00' >>> seconds_to_position(60*60) '01:00:00' >>> seconds_to_position(59 + 60*59 + 60*60*2) '02:59:59' >>> seconds_to_position(60*60*100) '100:00:00' """ minutes = int(seconds / 60) seconds = seconds % 60 hours = int(minutes / 60) minutes = minutes % 60 return '%02d:%02d:%02d' % (hours, minutes, seconds) mygpoclient-1.9/requirements-test.txt000066400000000000000000000000531425512052500201550ustar00rootroot00000000000000pytest >= 4.6 pytest-cov coverage minimock mygpoclient-1.9/setup.py000066400000000000000000000036731425512052500154410ustar00rootroot00000000000000#!/usr/bin/env python # Generic setup script for single-package Python projects # by Thomas Perl from distutils.core import setup import re import os import glob PACKAGE = 'mygpoclient' SCRIPT_FILE = os.path.join(PACKAGE, '__init__.py') main_py = open(SCRIPT_FILE).read() metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", main_py)) docstrings = re.findall('"""(.*?)"""', main_py, re.DOTALL) # List the packages that need to be installed/packaged PACKAGES = ( PACKAGE, ) SCRIPTS = glob.glob('bin/*') # Metadata fields extracted from SCRIPT_FILE AUTHOR_EMAIL = metadata['author'] VERSION = metadata['version'] WEBSITE = metadata['website'] LICENSE = metadata['license'] DESCRIPTION = docstrings[0].strip() if '\n\n' in DESCRIPTION: DESCRIPTION, LONG_DESCRIPTION = DESCRIPTION.split('\n\n', 1) else: LONG_DESCRIPTION = None # Extract name and e-mail ("Firstname Lastname ") AUTHOR, EMAIL = re.match(r'(.*) <(.*)>', AUTHOR_EMAIL).groups() DATA_FILES = [ ('share/man/man1', glob.glob('man/*')), ] CLASSIFIERS = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ] setup(name=PACKAGE, version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author=AUTHOR, author_email=EMAIL, license=LICENSE, url=WEBSITE, packages=PACKAGES, scripts=SCRIPTS, data_files=DATA_FILES, download_url=WEBSITE + PACKAGE + '-' + VERSION + '.tar.gz', classifiers=CLASSIFIERS, )