diff --git a/.gitignore b/.gitignore index fca8896..0de2941 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,13 @@ MANIFEST dist build -listparser$py.class +*$py.class +.tox/ +listparser.egg-info/ +.cache +htmlcov/ +.coverage +venv/ +.idea/ +.venv/ +poetry.lock diff --git a/CHANGELOG.rst b/CHANGELOG.rst new file mode 100644 index 0000000..5fa4fa5 --- /dev/null +++ b/CHANGELOG.rst @@ -0,0 +1,281 @@ +.. + This is the feedparser changelog. + + It is managed and updated by scriv during development. + Please do not edit this file directly. Instead, run + "scriv create" to create a new changelog fragment file. + + +Changelog +********* + + +Unreleased changes +================== + +Please see the fragment files in the `changelog.d directory`_. + +.. _changelog.d directory: https://github.com/kurtmckee/listparser/tree/develop/changelog.d + + +.. scriv-insert-here + +.. _changelog-0.19: + +0.19 - 2022-06-04 +================= + +*"Spring cleaning"* + +Added +----- + +* Add ``requests`` as an optional dependency. +* Add ``lxml`` as an optional dependency. + This is currently the only way to parse malformed XML files. +* Add support for Python 3.7 through Python 3.10. + +Removed +------- + +* Drop support for CPython 3.6 and lower. +* Drop support for IronPython. +* Drop support for Jython. +* Remove some ancient Jython compatibility code. +* HTML entities are no longer automatically injected into the DTD. + + If ``lxml`` is installed and undeclared HTML entities are encountered, + they will be ignored. + + If lxml is not installed and undeclared HTML entities are encountered, + Python's ``xml.sax`` parser will fail to parse the document. + +Fixed +----- + +* Fix some coverage messages that were output during testing. +* Fix the combined coverage HTML report's paths. + +Changed +------- + +* Migrate to a ``src/``-based directory structure. +* Migrate to Read the Docs for documentation hosting. +* ``parse()`` no longer accepts *etag*, *modified*, or *agent* arguments. +* HTTP response information is no longer available in the return dictionary. +* The unit tests no longer launch an HTTP server. +* Coverage data is now erased before the unit tests begin. +* ``bozo`` is now ``True`` or ``False``, not ``1`` or ``0``. +* ``bozo_exception`` is guaranteed to exist in the return dict. +* The RFC 822 parser now returns timezone-aware ``datetime`` objects + instead of converting to UTC and losing timezone info. +* Move and split ``lptest.py`` into the ``tests/`` subdirectory + and into specific ``test_*`` files. +* Increased test coverage reporting to include test runners. +* Decreased the number of ``tox`` environments where listparser must be built and installed. +* Internally rely on ``dict`` key-based lookups instead of ``SuperDict`` attribute-based lookups. +* Cache XML parsing method lookup results to avoid excessive string formatting. +* Change the name of the ``ListError`` to ``ListparserError``. +* Split the codebase into multiple files. +* Use ``tox`` to automate testing across multiple interpreters and versions. +* Migrate to ``pytest`` for unit testing. +* Remove dependence on the ``six`` package. +* Add type annotations. +* Remove compatibility code. +* Migrate to Poetry and ``pyproject.toml`` for project configuration. +* Change the license from LGPLv3 to MIT. +* Use scriv to manage the CHANGELOG. + + +0.18 - 2015-04-21 +================= + +* Replace the regex RFC 822 date parser with procedural code. + + +0.17 - 2012-12-16 +================= + +*"Territory expansion"* + +* Python 3.3 is now tested and supported! +* PyPy is now tested and supported! +* Jython 2.5.2 and 2.5.3 are now tested and supported! +* Python 2 and 3 are now supported without 2to3 conversion +* Remove the hack to work around Jython bug 1375. + (This means that Jython 2.5.1 is no longer supported.) +* Support single-digit days in RFC822 dates + + +0.16 - 2011-12-17 +================= + +*"Refresh"* + +* Python 3.2 is now supported! +* Made setup.py auto-convert listparser using 2to3 if necessary. +* Switched to absolute URLs in the HTTP redirect tests. + + +0.15 - 2010-11-15 +================= + +*"A special day"* + +* IronPython 2.6.2 is now supported! + + +0.14 - 2010-10-22 +================= + +*"A good year"* + +* Added support for LiveJournal FOAF files. +* Improved the documentation. +* Improved the code quality. + + +0.13 - 2010-02-01 +================= + +*"Revelations"* + +* Fixed an infinite loop bug in Injector. +* Fixed a threading-related bug in the unit tests. +* Made Injector inject after the first '>', not '\n'. +* Overhauled and modularized the unit test code. +* Increased the code coverage of the unit tests. + + +0.12 - 2010-01-03 +================= + +*"Safety net"* + +* Fixed global USER_AGENT behavior. +* Fixed several crasher bugs. +* Fixed a 2to3 tool warning in lptest.py. +* Made lptest.py return a status code to the shell. + + +0.11 - 2009-12-25 +================= + +*"Floodgates"* + +* Jython 2.5.1 is now supported! +* Added support for opening relative and absolute filenames. + + +0.10 - 2009-12-12 +================= + +*"Internet-ready"* + +* Python 3 is now supported! +* Correctly interpret undeclared HTML character entities. +* Significantly sped up large RDF+FOAF document parsing. +* Fixed RFC 822 date and time creation bug. +* Fixed RFC 822 crasher bugs. +* Fixed iGoogle-related crasher bug. +* Refreshed and added to documentation. +* Added many more tests. + + +0.9 - 2009-10-03 +================ + +*"Celery wolves"* + +* Support RDF+FOAF! +* Capture opportunity URLs. +* Added duplicate URL detection. +* Added distutils support for easier distribution. + + +0.8 - 2009-09-03 +================ + +*"Three day weekend"* + +* Support the iGoogle exported settings format! +* Support Liferea's version of subscription lists in OPML. +* Removed ``feeds[i].claims``. +* Removed almost all of listparser's bozo warnings. + + +0.7 - 2009-08-28 +================ + +*"The Codex"* + +* Added documentation! +* Unified feed and subscription list code. +* Extended category and tag support to subscription lists. +* Result dictionary keys are now also attributes (i.e. ``result['meta']['title']`` -> ``result.meta.title``). +* Feed and list titles are no longer filled with the associated URL if the title is not found. + + +0.6 - 2009-08-07 +================ + +*"Hatchet Hotel"* + +* Certain return result elements are now guaranteed. +* ``bozo_detail`` has been renamed ``bozo_exception``. +* Better support for Wordpress' wp-links-opml.php output. +* Added 22 new tests (and modified several others). + + +0.5 - 2009-08-01 +================ + +*"Going green"* + +* Send a (configurable) User-Agent header. +* Support HTTP ETag and Last-Modified headers. +* Support HTTP redirects and errors. +* Support parsing of strings and file-like objects (not just URLs). +* The subscription list title is now stripped of whitespace. +* Added 11 more tests. + + +0.4 - 2009-07-18 +================ + +*"07/18,29"* + +* Support categories and tags specified in ``@category``. +* Support categorization using nested ```` tags. +* Added 21 more tests. + + +0.3 - 2009-07-03 +================ + +*"...and Recursion for all."* + +* The feed key ``name`` is now ``title``. +* Additional optional attributes supported. +* Support subscription list inclusions. +* Added 13 more tests. + + +0.2 - 2009-06-26 +================ + +*"Leveling up"* + +* RFC 822 date and time support added (+39 tests). +* Added more thorough OPML version attribute detection (+5 tests). +* ``dateModified`` and ``dateCreated`` OPML tags supported (+4 tests). +* Added test cases for existing functionality (+2 tests). +* ```` ``htmlUrl`` attribute support added (+1 test). + + +0.1 - 2009-06-19 +================ + +*"Achievement unlocked"* + +* Initial release. diff --git a/COPYING b/COPYING deleted file mode 100644 index 94a9ed0..0000000 --- a/COPYING +++ /dev/null @@ -1,674 +0,0 @@ - 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 -. diff --git a/COPYING.LESSER b/COPYING.LESSER deleted file mode 100644 index 65c5ca8..0000000 --- a/COPYING.LESSER +++ /dev/null @@ -1,165 +0,0 @@ - GNU LESSER 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. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser 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 -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..5dea287 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright 2009-2022 Kurt McKee + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/MANIFEST.in b/MANIFEST.in deleted file mode 100644 index bdf71d4..0000000 --- a/MANIFEST.in +++ /dev/null @@ -1,8 +0,0 @@ -include COPYING -include COPYING.LESSER -include NEWS -include README -include lptest.py -include project.opml -recursive-include docs *.rst conf.py -recursive-include tests *.xml diff --git a/NEWS b/NEWS deleted file mode 100644 index d8f6754..0000000 --- a/NEWS +++ /dev/null @@ -1,107 +0,0 @@ -v0.18 (21 April 2015) - * Replace the regex RFC 822 date parser with procedural code - -v0.17 (16 Dec 2012) "Territory expansion" - * Python 3.3 is now tested and supported! - * PyPy is now tested and supported! - * Jython 2.5.2 and 2.5.3 are now tested and supported! - * Python 2 and 3 are now supported without 2to3 conversion - * Remove the hack to work around Jython bug 1375 - (this means that Jython 2.5.1 is no longer supported) - * Support single-digit days in RFC822 dates - -v0.16 (17 Dec 2011) "Refresh" - * Python 3.2 is now supported! - * Made setup.py auto-convert listparser using 2to3 if necessary - * Switched to absolute URLs in the HTTP redirect tests - -v0.15 (15 Nov 2010) "A special day" - * IronPython 2.6.2 is now supported! - -v0.14 (22 Oct 2010) "A good year" - * Added support for LiveJournal FOAF files - * Improved the documentation - * Improved the code quality - -v0.13 (1 Feb 2010) "Revelations" - * Fixed an infinite loop bug in Injector - * Fixed a threading-related bug in the unit tests - * Made Injector inject after the first '>', not '\n' - * Overhauled and modularized the unit test code - * Increased the code coverage of the unit tests - -v0.12 (3 Jan 2010) "Safety net" - * Fixed global USER_AGENT behavior - * Fixed several crasher bugs - * Fixed a 2to3 tool warning in lptest.py - * Made lptest.py return a status code to the shell - -v0.11 (25 Dec 2009) "Floodgates" - * Jython 2.5.1 is now supported! - * Added support for opening relative and absolute filenames - -v0.10 (12 Dec 2009) "Internet-ready" - * Python 3 is now supported! - * Correctly interpret undeclared HTML character entities - * Significantly sped up large RDF+FOAF document parsing - * Fixed RFC 822 date and time creation bug - * Fixed RFC 822 crasher bugs - * Fixed iGoogle-related crasher bug - * Refreshed and added to documentation - * Added many more tests - -v0.9 (3 Oct 2009) "Celery wolves" - * Support RDF+FOAF! - * Capture opportunity URLs - * Added duplicate URL detection - * Added distutils support for easier distribution - -v0.8 (3 Sep 2009) "Three day weekend" - * Support the iGoogle exported settings format! - * Support Liferea's version of subscription lists in OPML - * Removed feeds[i].claims - * Removed almost all of listparser's bozo warnings - -v0.7 (28 Aug 2009) "The Codex" - * Added documentation! - * Unified feed and subscription list code - * Extended category and tag support to subscription lists - * Result dictionary keys are now also attributes - (i.e. result['meta']['title'] -> result.meta.title) - * Feed and list titles are no longer filled with the - associated URL if the title is not found - -v0.6 (7 Aug 2009) "Hatchet Hotel" - * Certain return result elements are now guaranteed - * `bozo_detail` has been renamed `bozo_exception` - * Better support for Wordpress' wp-links-opml.php output - * Added 22 new tests (and modified several others) - -v0.5 (1 Aug 2009) "Going green" - * Send a (configurable) User-Agent header - * Support HTTP ETag and Last-Modified headers - * Support HTTP redirects and errors - * Support parsing of strings and file-like objects (not just URLs) - * The subscription list title is now stripped of whitespace - * Added 11 more tests - -v0.4 (18 July 2009) "07/18,29" - * Support categories and tags specified in @category - * Support categorization using nested tags - * Added 21 more tests - -v0.3 (3 July 2009) "...and Recursion for all." - * The feed key `name` is now `title` - * Additional optional attributes supported - * Support subscription list inclusions - * Added 13 more tests - -v0.2 (26 June 2009) "Leveling up" - * RFC 822 date and time support added (+39 tests) - * Added more thorough OPML version attribute detection (+5 tests) - * `dateModified` and `dateCreated` OPML tags supported (+4 tests) - * Added test cases for existing functionality (+2 tests) - * `htmlUrl` attribute support added (+1 test) - -v0.1 (19 June 2009) "Achievement unlocked" - * Initial release diff --git a/README.rst b/README.rst index e966937..bdcdf51 100644 --- a/README.rst +++ b/README.rst @@ -1,41 +1,51 @@ -What is listparser? -=================== +listparser +========== -listparser is a Python module that parses subscription lists (also called -reading lists) and returns all of the feeds and subscription lists that it -finds. It supports OPML, RDF+FOAF, and the iGoogle exported settings format, -and runs in Python 2.4 through Python 3.3. +*Parse OPML subscription lists in Python.* + +------------------------------------------------------------------------------- + +If you're building a feed reader and you need to parse OPML subscription lists, +you've come to the right place! + +listparser makes it easy to parse and use subscription lists in multiple formats. +It supports OPML, RDF+FOAF, and the iGoogle exported settings format, +and runs on Python 3.7+ and on PyPy 3.7. -listparser is licensed under the terms of the GNU Lesser General Public License -version 3 or higher. Usage ===== ->>> import listparser ->>> result = listparser.parse('project.opml') +.. code-block:: pycon + + >>> import listparser + >>> result = listparser.parse(open('feeds.opml').read()) A dictionary will be returned with several keys: -* ``meta``: a dictionary of information about the subscription list -* ``feeds``: a list of feeds -* ``lists``: a list of subscription lists -* ``version``: a file format identifier -* ``bozo``: 1 if there is a problem with the list, 0 otherwise -* ``bozo_exception``: (if ``bozo`` is 1) a description of the problem +* ``meta``: a dictionary of information about the subscription list +* ``feeds``: a list of feeds +* ``lists``: a list of subscription lists +* ``version``: a format identifier like "opml2" +* ``bozo``: True if there is a problem with the list, False otherwise +* ``bozo_exception``: (if ``bozo`` is 1) a description of the problem + +For convenience, the result dictionary supports attribute access for its keys. Continuing the example: ->>> result.meta.title -u'listparser project feeds' ->>> len(result.feeds) -2 ->>> result.feeds[0].url -u'http://kurtmckee.livejournal.com/data/atom?tag=listparser' +.. code-block:: pycon + + >>> result.meta.title + 'listparser project feeds' + >>> len(result.feeds) + 2 + >>> result.feeds[0].title, result.feeds[0].url + ('listparser blog', 'https://kurtmckee.org/tag/listparser') -More extensive documentation is available in the docs/ directory, -or online at . +More extensive documentation is available in the ``docs/`` directory +and online at . Bugs @@ -48,4 +58,4 @@ that document as a test case, and then find and fix the problem. ...you can also just report the bug and leave it to someone else to fix the problem, but that won't be as much fun for you! -Bugs can be reported at . +Bugs can be reported at . diff --git a/changelog.d/fragment-template.rst.txt b/changelog.d/fragment-template.rst.txt new file mode 100644 index 0000000..de56313 --- /dev/null +++ b/changelog.d/fragment-template.rst.txt @@ -0,0 +1,28 @@ +.. + + Please select the correct category for the change you are making. + + 1. Remove all lines before and after the chosen category + including these instructions and the divider lines that + use tildes ("~"). + + 2. Remove the four spaces in front of the remaining text. + + 3. Describe your change using active verbs and full sentences. + For example, write "Support a new feature" instead of + "Supports a new feature" or "A new feature is supported". + + 4. If your change is associated with an issue on GitHub, + list the issue number(s) in parentheses, separated by + commas. For example: + + Support a new feature. (#10, #20) + +{% for category in config.categories %} + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + {{ category }} + {{ config.rst_header_chars[1] * (category|length) }} + + * Describe your "{{ category }}" change here. EDIT ME! +{% endfor -%} diff --git a/docs/changelog.rst b/docs/changelog.rst new file mode 100644 index 0000000..565b052 --- /dev/null +++ b/docs/changelog.rst @@ -0,0 +1 @@ +.. include:: ../CHANGELOG.rst diff --git a/docs/conf.py b/docs/conf.py index db22ea1..d3d23f4 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,190 +1,40 @@ -# -*- coding: utf-8 -*- -# -# listparser documentation build configuration file, created by -# sphinx-quickstart on Sun Aug 9 16:06:07 2009. -# -# This file is execfile()d with the current directory set to its containing dir. -# -# The contents of this file are pickled, so don't put values in the namespace -# that aren't pickleable (module imports are okay, they're removed automatically). -# -# 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. +import os +import pathlib +import sys + +import toml -import sys, os +# Allow autodoc to import listparser. +sys.path.append(os.path.abspath('../src')) -# If your extensions (or modules documented by 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. -#sys.path.append(os.path.abspath('.')) # General configuration # --------------------- -# Add any Sphinx extension module names here, as strings. They can be extensions -# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = [] - -# Add any paths that contain templates here, relative to this directory. -#templates_path = ['_templates'] +# 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'] # The suffix of source filenames. source_suffix = '.rst' -# The encoding of source files. -#source_encoding = 'utf-8' - # The master toctree document. master_doc = 'index' # General information about the project. -project = u'listparser' -copyright = u'2009-2015 Kurt McKee' +project = 'listparser' +copyright = '2009-2022 Kurt McKee' # 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 = '0.18' -# The full version, including alpha/beta/rc tags. -release = '0.18' - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -#language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -#today = '' -# Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' - -# List of documents that shouldn't be included in the build. -#unused_docs = [] +info = toml.load(pathlib.Path(__file__) / '../../pyproject.toml') +version = release = info['tool']['poetry']['version'] # List of directories, relative to source directory, that shouldn't be searched # for source files. exclude_trees = [] -# The reST default role (used for this markup: `text`) to use for all documents. -#default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -#add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -#show_authors = False - # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' - - -# Options for HTML output -# ----------------------- - -# The style sheet to use for HTML and HTML Help pages. A file of that name -# must exist either in Sphinx' static/ path, or in one of the custom paths -# given in html_static_path. -#html_style = 'default.css' - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -#html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -#html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -#html_favicon = None - -# 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'] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -#html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -#html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -#html_additional_pages = {} - -# If false, no module index is generated. -#html_use_modindex = True - -# If false, no index is generated. -#html_use_index = True - -# If true, the index is split into individual pages for each letter. -#html_split_index = False - -# If true, the reST sources are included in the HTML build as _sources/. -#html_copy_source = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -#html_use_opensearch = '' - -# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = '' - -# Output file base name for HTML help builder. -htmlhelp_basename = 'listparserdoc' - - -# Options for LaTeX output -# ------------------------ - -# The paper size ('letter' or 'a4'). -#latex_paper_size = 'letter' - -# The font size ('10pt', '11pt' or '12pt'). -#latex_font_size = '10pt' - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, author, document class [howto/manual]). -latex_documents = [ - ('index', 'listparser.tex', ur'listparser Documentation', - ur'Kurt McKee', 'manual'), -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -#latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -#latex_use_parts = False - -# Additional stuff for the LaTeX preamble. -#latex_preamble = '' - -# Documents to append as an appendix to all manuals. -#latex_appendices = [] - -# If false, no module index is generated. -#latex_use_modindex = True diff --git a/docs/detection-algorithm.rst b/docs/detection-algorithm.rst index e66327a..00aef55 100644 --- a/docs/detection-algorithm.rst +++ b/docs/detection-algorithm.rst @@ -3,22 +3,42 @@ Feed and subscription list detection algorithm .. note:: - Neither RDF+FOAF nor the iGoogle exported settings formats support embedded subscription lists. This detection algorithm only applies to OPML subscription lists. + Neither RDF+FOAF nor the iGoogle exported settings formats support + embedded subscription lists. This detection algorithm only applies + to OPML subscription lists. -Many services and softwares output OPML subscription lists with slight variations. listparser attempts to correctly determine whether an ``outline`` element is attempting to reference a feed or subscription list. As an example, although feeds should be indicated using ``type="rss"`` (no matter the format), some services refer to feeds using ``type="link"``, others indicate that the feed is Atom-formatted using ``type="pie"``, and still others fail to include a ``type`` attribute at all! Therefore it is necessary to make educated guesses. +Many services and softwares output OPML subscription lists with slight +variations. listparser attempts to correctly determine whether an +``outline`` element is attempting to reference a feed or subscription +list. As an example, although feeds should be indicated using +``type="rss"`` (no matter the format), some services refer to feeds +using ``type="link"``, others indicate that the feed is Atom-formatted +using ``type="pie"``, and still others fail to include a ``type`` +attribute at all! Therefore it is necessary to make educated guesses. Feed detection -------------- -If the ``outline`` element contains an ``xmlUrl`` attribute, the ``outline`` is assumed to represent a feed. listparser will also accept ``xmlurl``, or ``xmlURL``, or indeed any capitalization combination. +If the ``outline`` element contains an ``xmlUrl`` attribute, the +``outline`` is assumed to represent a feed. listparser will also accept +``xmlurl``, or ``xmlURL``, or indeed any capitalization combination. -The ``type`` is ignored entirely in making the decision, with one notable exception (see below). +The ``type`` is ignored entirely in making the decision, with one +notable exception (see below). Subscription list detection --------------------------- -If the ``outline`` element has a ``url`` attribute and ``type="link"`` or ``type="include"``, listparser assumes that it has found a subscription list. Additionally, if it has an ``xmlUrl`` attribute and ``type="source"``, it is also considered a subscription list. - -Although the "include" value was only introduced in OPML 2.0, listparser ignores the OPML version entirely. Additionally, despite the OPML 2.0 requirement that the ``url`` value of "link" ``outline`` elements must end in ".opml" to be considered an OPML file, listparser ignores the URL suffix when detecting whether the element is a subscription list. +If the ``outline`` element has a ``url`` attribute and ``type="link"`` +or ``type="include"``, listparser assumes that it has found a +subscription list. Additionally, if it has an ``xmlUrl`` attribute and +``type="source"``, it is also considered a subscription list. + +Although the "include" value was only introduced in OPML 2.0, +listparser ignores the OPML version entirely. Additionally, despite the +OPML 2.0 requirement that the ``url`` value of "link" ``outline`` +elements must end in ".opml" to be considered an OPML file, listparser +ignores the URL suffix when detecting whether the element is a +subscription list. diff --git a/docs/getting-started.rst b/docs/getting-started.rst index 87f8a55..45ba364 100644 --- a/docs/getting-started.rst +++ b/docs/getting-started.rst @@ -1,51 +1,93 @@ Getting started =============== -Because listparser is just a single file, you can copy it to a convenient directory and start the Python interpreter. listparser has a single public function, :py:func:`~listparser.parse`. :: +Use pip to install listparser. + +To support retrieving and parsing of URL's, add ``[http]`` to the command +so the requests package will be installed as well. + +To parse broken XML, add ``[lxml]`` to the command +so the lxml package will be installed as well. + +.. code-block:: shell + + python -m pip install listparser[http,lxml] + +You don't have to install lxml or requests but it will reduce listparser's functionality. + + +listparser has a single public function, :py:func:`~listparser.parse`. + +.. code-block:: pycon >>> import listparser - >>> result = listparser.parse('http://github.com/kurtmckee/listparser/raw/master/project.opml') + >>> result = listparser.parse('https://github.com/kurtmckee/listparser/raw/develop/feeds.opml') -:py:func:`~listparser.parse` can be given a URL, an open file handle, or even an in-memory string. +:py:func:`~listparser.parse` can be given a URL, an open file handle, +or even an in-memory string. -The dictionary that :py:func:`~listparser.parse` returns will contain several important keys. +The dictionary that :py:func:`~listparser.parse` returns will contain +several important keys. The ``meta`` key ---------------- -The ``meta`` key contains a dictionary of information about the subscription list, including its title, when it was created and last modified, and who maintains the subscription list:: +The ``meta`` key contains a dictionary of information about the +subscription list, including its title, when it was created and last +modified, and who maintains the subscription list. + +.. code-block:: pycon >>> result.meta.title - u'listparser project feeds' + 'listparser project feeds' >>> result.meta.author.keys() - ['url', 'name', 'email'] + dict_keys(['name', 'email', 'url']) The ``feeds`` key ----------------- -The ``feeds`` key is a list of dictionaries. The title and the URL are stored in keys of the same names:: +The ``feeds`` key is a list of dictionaries. +The title and the URL are stored in keys of the same names. + +.. code-block:: pycon >>> for i in result.feeds: - ... print "%s <%s>" % (i.title, i.url) - ... - listparser blog - listparser releases - listparser changelog + ... print('{title} <{url}>'.format(**i)) + ... + listparser blog + listparser changelog + The ``lists`` key ----------------- -OPML subscription lists can point to other subscription lists as easily as they can point to feeds. These subscription lists are placed in the ``lists`` key, and have the same title and URL information as feeds do. +OPML subscription lists can point to other subscription lists as easily +as they can point to feeds. These subscription lists are placed in the +``lists`` key, and have the same title and URL information that feeds do. The ``opportunities`` key ------------------------- -Several subscription list formats can contain not just a feed URL but the feed's homepage URL as well. Some software butchers the OPML or RDF+FOAF file creation and outputs only the feed's homepage URL. +Several subscription list formats can contain not just a feed URL but +the feed's homepage URL as well. Some software butchers the OPML or +RDF+FOAF file creation and outputs only the feed's homepage URL. + +When listparser encounters a homepage URL without a corresponding feed +URL, it puts that information into the ``opportunities`` key. +Opportunities contain the same title and URL information as feeds do, +but remember that the URLs are expected to point to a homepage. It is +therefore expected that feed readers using listparser will have to run +feed and subscription list autodiscovery software against the list of +opportunity URLs. + -When listparser encounters a homepage URL without a corresponding feed URL, it puts that information into the ``opportunities`` key. Opportunities contain the same title and URL information as feeds do, but remember that the URLs are expected to point to a homepage. It is therefore expected that feed readers using listparser will have to run feed and subscription list autodiscovery software against the list of opportunity URLs. +.. seealso:: -.. seealso:: :doc:`reference/meta`, :doc:`reference/feeds`, :doc:`reference/lists`, :doc:`reference/opportunities` + :doc:`reference/meta`, + :doc:`reference/feeds`, + :doc:`reference/lists`, + :doc:`reference/opportunities` diff --git a/docs/http-features.rst b/docs/http-features.rst index 1deebe3..63e0fd8 100644 --- a/docs/http-features.rst +++ b/docs/http-features.rst @@ -1,63 +1,21 @@ HTTP Features ============= -listparser supports several HTTP features, both to identify itself to webservers and to save bandwidth. +If the requests package is installed, listparser will be able to accept HTTP and HTTPS URL's for parsing. +For example: +.. code-block:: pycon -User-Agent ----------- + >>> result = listparser.parse('https://domain.example/feeds.opml') -listparser identifies itself to webservers by sending an HTTP User-Agent header. By default the header contains listparser's version, and a reference to the listparser homepage, but the header can be changed on a per-request basis or for all requests. +A 30-second timeout is set on all requests. -To change the User-Agent for only one request, call :py:func:`~listparser.parse` with an ``agent`` argument:: +If requests is not installed, listparser will return a dictionary with the following data: - >>> listparser.parse('http://localhost/list', agent='PowerfulSoftware/1.0') +.. code-block:: pycon -To configure the User-Agent for all requests you need only set :py:data:`~listparser.USER_AGENT` to the desired value. The following code will send the same User-Agent header as the code above:: - - >>> listparser.USER_AGENT = 'PowerfulSoftware/1.0' - >>> listparser.parse('http://localhost/list') - -If listparser is being used in a larger program it may be appropriate to change the User-Agent. - -.. seealso:: :py:data:`~listparser.USER_AGENT`, `User agent at Wikipedia `_ - - -ETag ----- - -When a webserver fulfills a request, it will often include an ETag header (the value of which may be a checksum of the file, such as its MD5 or SHA1 hash). listparser stores the value of the ETag header in the result's ``etag`` attribute:: - - >>> result = listparser.parse('http://localhost/list') - >>> result.etag - '"ebe4f71184"' - -If this value is passed in the ``etag`` argument to :py:func:`~listparser.parse`, the webserver will know whether the file has been modified since the last request. If it has been modified, the request will be fulfilled normally, and a new ETag header will be sent along with the file. If the file has not been modified, the webserver will return an HTTP 304 response in order to save bandwidth:: - - >>> result = listparser.parse('http://localhost/list', etag='"ebe4f71184"') - >>> result.status - 304 - -It is strongly recommended that software using listparser take advantage of the bandwidth-saving benefits of both the ETag and Last-Modified headers by checking for, storing, and sending both, as not all webservers support both. - -.. seealso:: `HTTP Etag at Wikipedia `_ - - -Last-Modified -------------- - -In addition to the ETag header above, webservers often include a Last-Modified header, which represents the date and time at which a file was last updated. listparser stores the value of the Last-Modified header in the result's ``modified`` and ``modified_parsed`` attribute:: - - >>> result = listparser.parse('http://localhost/list') - >>> result.modified - 'Mon, 24 Aug 2009 21:10:01 GMT' - >>> result.modified_parsed - datetime.datetime(2009, 8, 24, 21, 10, 1) - -If either of these values is passed to the ``modified`` argument of :py:func:`~listparser.parse`, the webserver will know whether to send the file or not. If the file has been modified, the request will be fulfilled normally and a new Last-Modified header will be sent. If not, the webserver will return an HTTP 304 response:: - - >>> result = listparser.parse('http://localhost/list', modified='Mon, 24 Aug 2009 21:10:01 GMT') - >>> result.status - 304 - -It is strongly recommended that software using listparser store and send both the Last-Modified and ETag headers, as not all webservers support both. + >>> listparser.parse('https://domain.example/feeds.opml') + { + 'bozo': 1, + 'bozo_exception': ListError('requests is not installed...') + } diff --git a/docs/index.rst b/docs/index.rst index 32a6e45..73eeb3a 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -1,13 +1,22 @@ -Welcome to listparser's documentation! -====================================== +listparser - Parse subscription lists in Python +=============================================== -listparser is a Python module that parses subscription lists (also called reading lists) and returns all of the feeds and subscription lists that it finds. It supports OPML, RDF+FOAF, and the iGoogle exported settings format. +If you're building a feed reader and you need to import OPML subscription lists, +you've come to the right place! + +listparser makes it easy to parse and use subscription lists in multiple formats. +It supports OPML, RDF+FOAF, and the iGoogle exported settings format, +and runs on Python 3.6+ and on PyPy 3.7. -listparser has been tested and runs on Python 2.4 and up, Python 3.0 and up, Jython 2.5.2 and up, PyPy 1.8.0, and IronPython 2.6.2. Contents -------- +.. toctree:: + :maxdepth: 1 + + changelog + .. toctree:: :maxdepth: 2 @@ -24,21 +33,14 @@ Reference :maxdepth: 2 reference/parse - reference/user_agent .. toctree:: :maxdepth: 2 reference/bozo reference/bozo_exception - reference/etag reference/feeds - reference/headers - reference/href reference/lists reference/meta - reference/modified - reference/modified_parsed reference/opportunities - reference/status reference/version diff --git a/docs/reference/bozo.rst b/docs/reference/bozo.rst index c958f7b..325ac3a 100644 --- a/docs/reference/bozo.rst +++ b/docs/reference/bozo.rst @@ -1,6 +1,8 @@ bozo ==== -The ``bozo`` key can be either ``0`` or ``1``. If it is ``1``, it indicates that there was an error or exception somewhere during parsing. In such cases the exception can be found in the ``bozo_exception`` key. +The ``bozo`` key can be either ``False`` or ``True``. +If it is ``True``, it indicates that there was an error or exception during parsing. +In such cases the exception can be found in the ``bozo_exception`` key. .. seealso:: :doc:`bozo_exception` diff --git a/docs/reference/bozo_exception.rst b/docs/reference/bozo_exception.rst index 0061a3d..28855ef 100644 --- a/docs/reference/bozo_exception.rst +++ b/docs/reference/bozo_exception.rst @@ -1,6 +1,8 @@ bozo_exception ============== -listparser should never propogate an exception to the software that called it; instead it will store the exception in the ``bozo_exception`` key of the result it returns. Developers may wish to check for exceptions, but it should never be a necessity. +listparser should never propagate an exception to the software that called it; +instead it will store the exception in the ``bozo_exception`` key of the result it returns. +Developers may wish to check for exceptions, but it should not be a necessity. .. seealso:: :doc:`bozo` diff --git a/docs/reference/etag.rst b/docs/reference/etag.rst deleted file mode 100644 index 78b02b6..0000000 --- a/docs/reference/etag.rst +++ /dev/null @@ -1,10 +0,0 @@ -etag -==== - -If an HTTP ETag header is received from the webserver, its exact text is stored in the ``etag`` key. It is strongly recommended that the ETag be stored and sent with every subsequent request in order to reduce bandwidth usage. - -.. seealso:: :doc:`../http-features` - -.. rubric:: Comes from - -* HTTP ETag header diff --git a/docs/reference/headers.rst b/docs/reference/headers.rst deleted file mode 100644 index c237c1a..0000000 --- a/docs/reference/headers.rst +++ /dev/null @@ -1,6 +0,0 @@ -headers -======= - -The ``headers`` key is a dictionary of all of the headers returned by a webserver if a subscription list is requested from a URL. - -Developers should be aware that Python 2 normalizes all header names, while Python 3 does not. Thus, if the webserver sends an ``X-Bender`` header, its Python 2 name will be ``x-bender``, while its Python 3 name will be unchanged. diff --git a/docs/reference/href.rst b/docs/reference/href.rst deleted file mode 100644 index 9ba0ef2..0000000 --- a/docs/reference/href.rst +++ /dev/null @@ -1,8 +0,0 @@ -href -==== - -The URL of the subscription list. - -The URL in ``href`` represents the last URL requested by listparser. For instance, if a subscription list at "olddomain.com" has been moved to "newdomain.com", ``href`` will contain the subscription list's address at "newdomain.com". - -.. seealso:: :doc:`status` diff --git a/docs/reference/lists.rst b/docs/reference/lists.rst index c812634..916df27 100644 --- a/docs/reference/lists.rst +++ b/docs/reference/lists.rst @@ -1,7 +1,7 @@ lists ===== -The ``lists`` attribute contains a list of all of the subscription lists in the parsed subscription list. +The ``lists`` attribute is a list of all of the subscription lists in the parsed subscription list. .. seealso:: diff --git a/docs/reference/meta-author-email.rst b/docs/reference/meta-author-email.rst index b04c38b..745035f 100644 --- a/docs/reference/meta-author-email.rst +++ b/docs/reference/meta-author-email.rst @@ -3,7 +3,8 @@ meta.author.email The email address of the author/maintainer of the subscription list. -No attempt is made to verify that the value is a valid email address. However, leading and trailing whitespace characters are stripped off. +No attempt is made to verify that the value is a valid email address. +However, leading and trailing whitespace characters are stripped off. .. rubric:: Comes from diff --git a/docs/reference/meta-author-name.rst b/docs/reference/meta-author-name.rst index 399d7c5..62c6f5d 100644 --- a/docs/reference/meta-author-name.rst +++ b/docs/reference/meta-author-name.rst @@ -3,7 +3,8 @@ meta.author.name The name of the author/maintainer of the subscription list. -No normalization is performed, although leading and trailing whitespace characters are stripped off. +No normalization is performed, although leading and trailing whitespace +characters are stripped off. .. rubric:: Comes from diff --git a/docs/reference/meta-author-url.rst b/docs/reference/meta-author-url.rst index ded78ae..012da84 100644 --- a/docs/reference/meta-author-url.rst +++ b/docs/reference/meta-author-url.rst @@ -3,7 +3,8 @@ meta.author.url The webpage of the author/maintainer of the subscription list. -No attempt is made to verify that the value is a valid URL. However, leading and trailing whitespace characters are stripped off. +No attempt is made to verify that the value is a valid URL. However, +leading and trailing whitespace characters are stripped off. .. rubric:: Comes from diff --git a/docs/reference/meta-created.rst b/docs/reference/meta-created.rst index c43bc6b..e5933a2 100644 --- a/docs/reference/meta-created.rst +++ b/docs/reference/meta-created.rst @@ -1,9 +1,14 @@ meta.created ============ -A string representing the date and time at which the subscription list was originally created. The string should be in RFC 822 date/time format, with the exception that the year may be four digits long instead of just two. +A string representing the date and time at which the subscription list +was originally created. The string should be in RFC 822 date/time +format, with the exception that the year may be four digits long +instead of just two. -.. seealso:: :doc:`meta-created_parsed` +.. seealso:: + + * :doc:`meta-created_parsed` .. rubric:: Comes from diff --git a/docs/reference/meta-created_parsed.rst b/docs/reference/meta-created_parsed.rst index 5f27c85..3d49b7e 100644 --- a/docs/reference/meta-created_parsed.rst +++ b/docs/reference/meta-created_parsed.rst @@ -1,9 +1,15 @@ meta.created_parsed =================== -A Python ``datetime`` object representing the date and time at which the subscription list was originally created, normalized to the UTC timezone. ``meta.created_parsed`` is parsed from the ``meta.created`` string. +A Python ``datetime`` object representing the date and time at which +the subscription list was originally created. The ``datetime`` +object is timezone-aware. -.. seealso:: :doc:`meta-created` +``meta.created_parsed`` is parsed from the ``meta.created`` string. + +.. seealso:: + + * :doc:`meta-created` .. rubric:: Comes from diff --git a/docs/reference/meta-modified.rst b/docs/reference/meta-modified.rst index a2005e6..e3d02d6 100644 --- a/docs/reference/meta-modified.rst +++ b/docs/reference/meta-modified.rst @@ -1,17 +1,15 @@ meta.modified ============= -A string representing the date and time at which the subscription list was last modified. The string should be in RFC 822 date/time format, with the exception that the year may be four digits long instead of just two. - -.. note:: - - ``meta.modified`` represents the date and time at which the **subscription list** claims to have last been updated. ``modified`` represents the date and time at which the **webserver** claims the file was last updated. +A string representing the date and time at which the subscription list +was last modified. The string should be in RFC 822 date/time format, +with the exception that the year may be four digits long instead of +just two. .. seealso:: - * :doc:`meta-modified_parsed` - * :doc:`modified` - + * :doc:`meta-modified_parsed` + .. rubric:: Comes from * ``/opml/head/dateModified`` diff --git a/docs/reference/meta-modified_parsed.rst b/docs/reference/meta-modified_parsed.rst index 1a39ca9..0e94321 100644 --- a/docs/reference/meta-modified_parsed.rst +++ b/docs/reference/meta-modified_parsed.rst @@ -1,6 +1,16 @@ meta.modified_parsed ==================== -A Python ``datetime`` object representing the date and time at which the subscription list was last modified, normalized to the UTC timezone. ``meta.modified_parsed`` is parsed from the ``meta.modified`` string. +A Python ``datetime`` object representing the date and time at which +the subscription list was last modified. The ``datetime`` object +is timezone-aware. -.. seealso:: :doc:`meta-modified` +``meta.modified_parsed`` is parsed from the ``meta.modified`` string. + +.. seealso:: + + * :doc:`meta-modified` + +.. rubric:: Comes from + +* ``/opml/head/dateModified`` diff --git a/docs/reference/meta.rst b/docs/reference/meta.rst index 959a640..e6a03a7 100644 --- a/docs/reference/meta.rst +++ b/docs/reference/meta.rst @@ -1,7 +1,9 @@ meta ==== -The ``meta`` attribute contains all of the information about the subscription list, including its title, when it was created or last updated, and information about its author or maintainer. +The ``meta`` attribute contains all of the information about the +subscription list, including its title, when it was created or last +updated, and information about its author or maintainer. .. toctree:: :glob: diff --git a/docs/reference/modified.rst b/docs/reference/modified.rst deleted file mode 100644 index ec87100..0000000 --- a/docs/reference/modified.rst +++ /dev/null @@ -1,18 +0,0 @@ -modified -======== - -A string returned by the webserver representing the date and time at which the subscription list was last modified. The string should be in RFC 2822 format. - -.. note:: - - ``modified`` represents the date and time at which the **webserver** claims the file was last updated. ``meta.modified`` represents the date and time at which the **subscription list** claims to have last been updated. - -.. seealso:: - - * :doc:`modified_parsed` - * :doc:`meta-modified` - * :doc:`../http-features` - -.. rubric:: Comes from - -* HTTP Last-Modified header diff --git a/docs/reference/modified_parsed.rst b/docs/reference/modified_parsed.rst deleted file mode 100644 index 6811bf7..0000000 --- a/docs/reference/modified_parsed.rst +++ /dev/null @@ -1,6 +0,0 @@ -modified_parsed -=============== - -A Python ``datetime`` object representing the date and time at which the subscription list was last modified. The object is normalized to the UTC timezone. ``modified_parsed`` is parsed from the ``modified`` string. - -.. seealso:: :doc:`modified` diff --git a/docs/reference/object-categories.rst b/docs/reference/object-categories.rst index 8f9b28c..5d02406 100644 --- a/docs/reference/object-categories.rst +++ b/docs/reference/object-categories.rst @@ -1,13 +1,14 @@ objects[i].categories ===================== -A list of all of the categories associated with the feed, subscription list, or opportunity object. +A list of all of the categories associated with the feed, subscription +list, or opportunity object. -Categories are hierarchical, and are represented as lists of strings. listparser uses the hierarchical groupings in the subscription list in order to assign categories. Here is an example in OPML: +Categories are hierarchical, and are represented as lists of strings. +listparser uses the hierarchical groupings in the subscription list in +order to assign categories. Here is an example in OPML: -.. highlight:: xml - -:: +.. code-block:: xml @@ -15,7 +16,9 @@ Categories are hierarchical, and are represented as lists of strings. listparser -In this example, the category hierarchy is ``["news", "sports"]``. In the OPML format, listparser will also use the ``category`` attribute of the ``opml:outline`` element as a source of categorization information. +In this example, the category hierarchy is ``["news", "sports"]``. In +the OPML format, listparser will also use the ``category`` attribute of +the ``opml:outline`` element as a source of categorization information. .. seealso:: :doc:`object-tags` diff --git a/docs/reference/object-tags.rst b/docs/reference/object-tags.rst index 306c02f..e67af31 100644 --- a/docs/reference/object-tags.rst +++ b/docs/reference/object-tags.rst @@ -1,11 +1,11 @@ objects[i].tags =============== -A list of all of the tags associated with the feed, subscription list, or opportunity object. They are copied from the ``categories`` key if the category is one level deep. As an example: +A list of all of the tags associated with the feed, subscription list, +or opportunity object. They are copied from the ``categories`` key if +the category is one level deep. As an example: -.. highlight:: xml - -:: +.. code-block:: xml diff --git a/docs/reference/object-title.rst b/docs/reference/object-title.rst index 19e44fd..a4e9ea6 100644 --- a/docs/reference/object-title.rst +++ b/docs/reference/object-title.rst @@ -1,29 +1,34 @@ objects[i].title ================ -The title of the feed, subscription list, or opportunity object. It is not normalized except for the stripping of whitespace. +The title of the feed, subscription list, or opportunity object. It is +not normalized except for the stripping of whitespace. .. note:: - The ``opml:outline`` element's ``text`` and ``title`` attributes differ in function. Many feed readers keep track of the feed's original title while allowing users to change the title that they see. When their subscription list is exported, the ``opml:outline`` element's ``text`` attribute should contain the user's preferred title, and the ``title`` attribute should contain the original title. + The ``opml:outline`` element's ``text`` and ``title`` attributes + differ in function. Many feed readers keep track of the feed's + original title while allowing users to change the title that they + see. When their subscription list is exported, the ``opml:outline`` + element's ``text`` attribute should contain the user's preferred + title, and the ``title`` attribute should contain the original title. - In practice, however, some softwares don't use the ``text`` attribute at all. Therefore, ``feeds[i].title`` is filled from the ``text`` attribute or, if that isn't available, the ``title`` attribute. For example: + In practice, however, some software doesn't use the ``text`` + attribute at all. Therefore, ``feeds[i].title`` is filled from the + ``text`` attribute or, if that isn't available, the ``title`` + attribute. For example: - .. highlight:: xml + .. code-block:: xml - :: - - + And here is the title returned by listparser: - .. highlight:: python - - :: + .. code-block:: pycon >>> result.feeds[0].title - u'Hal Tucker' + '*text* attribute' .. rubric:: Comes from diff --git a/docs/reference/object-url.rst b/docs/reference/object-url.rst index 034aeb6..0375664 100644 --- a/docs/reference/object-url.rst +++ b/docs/reference/object-url.rst @@ -1,9 +1,11 @@ objects[i].url ============== -The URL of the feed, subscription list, or opportunity object. It is not normalized beyond the stripping of whitespace. +The URL of the feed, subscription list, or opportunity object. It is +not normalized beyond the stripping of whitespace. -Due to the ubiquity of format-agnostic feed parsers, there is nothing to indicate what format the target feed is presented in. +Due to the ubiquity of format-agnostic feed parsers, there is nothing +to indicate what format the target feed is presented in. .. rubric:: Feed URLs come from diff --git a/docs/reference/objects.rst b/docs/reference/objects.rst index 4e597ed..638d7df 100644 --- a/docs/reference/objects.rst +++ b/docs/reference/objects.rst @@ -1,7 +1,12 @@ Shared object properties ======================== -Feed, subscription list, and opportunity objects share several common properties. Although the content may come from different elements in the source document, the information is stored in consistent attributes. +Feed, subscription list, and opportunity objects share several common +properties. Although the content may come from different elements in +the source document, the information is stored in consistent attributes. + +Wherever you see ``objects[i]`` in these documents +you can substitute ``feeds[i]``, ``lists[i]``, or ``opportunities[i]``. .. toctree:: :glob: diff --git a/docs/reference/opportunities.rst b/docs/reference/opportunities.rst index 14bf26a..a80285b 100644 --- a/docs/reference/opportunities.rst +++ b/docs/reference/opportunities.rst @@ -1,9 +1,13 @@ opportunities ============= -The ``opportunities`` attribute contains a list of all of the homepage URLs in the parsed subscription list for which a corresponding feed or subscription list URL was not found. +The ``opportunities`` attribute contains a list of all of the homepage +URLs in the parsed subscription list for which a corresponding feed or +subscription list URL was not found. -It is expected that feed readers using listparser can choose to run feed and subscription list autodiscovery software against the list of opportunity URLs. +It is expected that feed readers using listparser can choose to run +feed and subscription list autodiscovery software against the list of +opportunity URLs. .. seealso:: diff --git a/docs/reference/parse.rst b/docs/reference/parse.rst index 310175a..439b958 100644 --- a/docs/reference/parse.rst +++ b/docs/reference/parse.rst @@ -1,26 +1,5 @@ parse() ======= -.. py:currentmodule:: listparser - -.. py:function:: parse(obj[, agent, etag, modified]) - - Parse a subscription list and return a dictionary containing the results. - - :param obj: a file-like object or a string containing a URL, an absolute or relative filename, or an XML document - :type obj: file or string - :param agent: User-Agent header to be sent when requesting a URL - :type agent: string - :param etag: ETag header to be sent when requesting a URL - :type etag: string - :param modified: Last-Modified header to be sent when requesting a URL - :type modified: string or datetime - - :return: all of the parsed information, webserver HTTP response headers, and any exception encountered - :rtype: dictionary - - :py:func:`~listparser.parse` is the only public function exposed by listparser. - - If *obj* is a URL, the :py:obj:`agent` will identify the software making the request, :py:obj:`etag` will identify the last HTTP ETag header returned by the webserver, and :py:obj:`modified` will identify the last HTTP Last-Modified header returned by the webserver. :py:obj:`agent` and :py:obj:`etag` must be strings, while :py:obj:`modified` can be either a string or a Python :py:class:`~datetime.datetime` object. - - If :py:obj:`agent` is not provided, the :py:data:`~listparser.USER_AGENT` global variable will be used by default. +.. automodule:: listparser + :members: parse diff --git a/docs/reference/status.rst b/docs/reference/status.rst deleted file mode 100644 index e02012f..0000000 --- a/docs/reference/status.rst +++ /dev/null @@ -1,13 +0,0 @@ -status -====== - -An integer representing the HTTP status returned by the webserver. [#codes]_ - -This value can be used to determine whether the location of the subscription list is still valid, or if it should be updated. For instance, if ``status == 301``, the subscription list has been "Moved Permanently", and the new location should be used for future requests. - -.. seealso:: :doc:`href` - -.. rubric:: Footnotes - -.. [#codes] `List of HTTP status codes `_ - diff --git a/docs/reference/user_agent.rst b/docs/reference/user_agent.rst deleted file mode 100644 index a03f4a2..0000000 --- a/docs/reference/user_agent.rst +++ /dev/null @@ -1,8 +0,0 @@ -USER_AGENT -========== - -.. py:currentmodule:: listparser - -.. py:data:: USER_AGENT - - A global variable that is used to to identify the software requesting a resource from a webserver. By default it contains listparser's name, version, and homepage. In larger software programs that use listparser, it may be appropriate to override :py:data:`~listparser.USER_AGENT` with more relevant information. diff --git a/docs/reference/version.rst b/docs/reference/version.rst index a406599..cf93bf4 100644 --- a/docs/reference/version.rst +++ b/docs/reference/version.rst @@ -1,21 +1,23 @@ version ======= -``version`` is a string that represents the format of the subscription list. It always exists, although it may be an empty string if the subscription list format is not recognized. +``version`` is a string that represents the format of the subscription +list. It always exists, although it may be an empty string if the +subscription list format is not recognized. These are the possible values: opml1 - `OPML 1.0 and 1.1 `_ [#opml11]_ + `OPML 1.0 and 1.1 `_ [#opml11]_ opml2 - `OPML version 2.0 `_ + `OPML version 2.0 `_ opml An OPML file with an unknown or unspecified version rdf - `RDF+FOAF `_ + `RDF+FOAF `_ igoogle iGoogle exported settings format [#igoog_export]_ @@ -23,5 +25,5 @@ igoogle .. rubric:: Footnotes -.. [#opml11] `OPML 1.1 files are treated as OPML 1.0 files. `_ -.. [#igoog_export] `How to export your iGoogle page settings `_ +.. [#opml11] `OPML 1.1 files are treated as OPML 1.0 files. `_ +.. [#igoog_export] `How to export your iGoogle page settings `_ diff --git a/project.opml b/feeds.opml similarity index 76% rename from project.opml rename to feeds.opml index 9edef5f..ba8a36f 100644 --- a/project.opml +++ b/feeds.opml @@ -4,11 +4,11 @@ listparser project feeds Kurt McKee contactme@kurtmckee.org - http://kurtmckee.org/ + https://kurtmckee.org/ + xmlUrl="https://kurtmckee.org/tag/listparser" /> diff --git a/listparser.py b/listparser.py deleted file mode 100644 index cd549dd..0000000 --- a/listparser.py +++ /dev/null @@ -1,721 +0,0 @@ -# listparser.py - Parse OPML, FOAF, and iGoogle subscription lists. -# Copyright (C) 2009-2015 Kurt McKee -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser 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 Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see . - -__author__ = "Kurt McKee " -__url__ = "https://github.com/kurtmckee/listparser" -__version__ = "0.18" - -import copy -import datetime -import re -import sys -import xml.sax - -try: - import htmlentitydefs -except ImportError: - import html.entities as htmlentitydefs - -try: - import httplib - class http(object): - client = httplib -except ImportError: - import http.client - -try: - import urllib2 - class urllib(object): - request = urllib2 - error = urllib2 - parse = urllib2 -except ImportError: - import urllib.error - import urllib.parse - import urllib.request - -try: - # Python 3: Use a bytes-compatible stream implementation - from io import BytesIO as BytesStrIO -except ImportError: - # Python 2: Use a basestring-compatible stream implementation - from StringIO import StringIO as BytesStrIO - -# Account for differences between the CPythons and Jython -# HACK: platform.python_implementation() might be ideal here, but -# Jython 2.5.1 doesn't have it yet, and neither do CPythons < 2.6 -try: - from org.xml.sax import SAXParseException - from com.sun.org.apache.xerces.internal.impl.io import \ - MalformedByteSequenceException -except ImportError: - # This isn't Jython - SAXParseException = xml.sax.SAXParseException - MalformedByteSequenceException = IOError - -def _to_bytes(text): - # Force `text` to the type expected by different interpreters - # Python 3 expects type(bytes) - # Python 2 and IronPython expect type(basestring) - if 'IronPython' in sys.version: - return text - try: - return bytes(text, 'utf8') - except (TypeError, NameError): - return text - -USER_AGENT = "listparser/%s +%s" % (__version__, __url__) - -namespaces = { - 'http://opml.org/spec2': 'opml', - 'http://www.google.com/ig': 'iGoogle', - 'http://schemas.google.com/GadgetTabML/2008': 'gtml', - 'http://www.w3.org/1999/02/22-rdf-syntax-ns#': 'rdf', - 'http://www.w3.org/2000/01/rdf-schema#': 'rdfs', - 'http://xmlns.com/foaf/0.1/': 'foaf', - 'http://purl.org/dc/elements/1.1/': 'dc', - 'http://purl.org/rss/1.0/': 'rss', - 'http://blogs.yandex.ru/schema/foaf/': 'ya', -} -# Provide a shorthand to save space in-code, e.g. _ns['rdf'] -_ns = dict((v, k) for k, v in namespaces.items()) - -def parse(parse_obj, agent=None, etag=None, modified=None, inject=False): - guarantees = SuperDict({ - 'bozo': 0, - 'feeds': [], - 'lists': [], - 'opportunities': [], - 'meta': SuperDict(), - 'version': '', - }) - fileobj, info = _mkfile(parse_obj, (agent or USER_AGENT), etag, modified) - guarantees.update(info) - if not fileobj: - return guarantees - - handler = Handler() - handler.harvest.update(guarantees) - parser = xml.sax.make_parser() - parser.setFeature(xml.sax.handler.feature_namespaces, True) - parser.setContentHandler(handler) - parser.setErrorHandler(handler) - if inject: - fileobj = Injector(fileobj) - try: - parser.parse(fileobj) - except (SAXParseException, MalformedByteSequenceException, - SystemError, - UnicodeDecodeError): - # Jython propagates exceptions past the ErrorHandler; - # The pyexpat module for IronPython throws a SystemError - # instead of a SaxParseException or something more sensible; - # Python 3 chokes if a file not opened in binary mode - # contains non-Unicode byte sequences - err = sys.exc_info()[1] - handler.harvest.bozo = 1 - handler.harvest.bozo_exception = err - fileobj.close() - - # Test if a DOCTYPE injection is needed - if hasattr(handler.harvest, 'bozo_exception'): - if "entity" in handler.harvest.bozo_exception.__str__(): - if not inject: - return parse(parse_obj, agent, etag, modified, True) - # Make it clear that the XML file is broken - # (if no other exception has been assigned) - if inject and not handler.harvest.bozo: - handler.harvest.bozo = 1 - handler.harvest.bozo_exception = ListError("undefined entity found") - return handler.harvest - -class Handler(xml.sax.handler.ContentHandler, xml.sax.handler.ErrorHandler): - def __init__(self): - xml.sax.handler.ContentHandler.__init__(self) - self.harvest = SuperDict() - self.expect = False - self._characters = str() - self.hierarchy = [] - self.flag_agent = False - self.flag_feed = False - self.flag_new_title = False - self.flag_opportunity = False - self.flag_group = False - # found_urls = {url: (append_to_key, obj)} - self.found_urls = SuperDict() - # group_objs = [(append_to_key, obj)] - self.group_objs = [] - self.agent_feeds = [] - self.agent_lists = [] - self.agent_opps = [] - self.foaf_name = [] - - def raise_bozo(self, err): - self.harvest.bozo = 1 - if isinstance(err, str): - self.harvest.bozo_exception = ListError(err) - else: - self.harvest.bozo_exception = err - - # ErrorHandler functions - def warning(self, exception): - self.raise_bozo(exception) - return - error = warning - fatalError = warning - - # ContentHandler functions - def startElementNS(self, name, qname, attrs): - fn = '' - if name[0] in namespaces: - fn = '_start_%s_%s' % (namespaces[name[0]], name[1]) - elif name[0] is None: - fn = '_start_opml_%s' % (name[1]) - if hasattr(getattr(self, fn, None), '__call__'): - getattr(self, fn)(attrs) - - def endElementNS(self, name, qname): - fn = '' - if name[0] in namespaces: - fn = '_end_%s_%s' % (namespaces[name[0]], name[1]) - elif name[0] is None: - fn = '_end_opml_%s' % (name[1]) - if hasattr(getattr(self, fn, None), '__call__'): - getattr(self, fn)() - # Always disable and reset character capture in order to - # reduce code duplication in the _end_opml_* functions - self.expect = False - self._characters = str() - - def normchars(self): - # Jython parsers split characters() calls between the bytes of - # multibyte characters. Thus, decoding has to be put off until - # all of the bytes are collected and the text node has ended. - return self._characters.encode('utf8').decode('utf8').strip() - - def characters(self, content): - if self.expect: - self._characters += content - - # OPML support - #-------------- - - def _start_opml_opml(self, attrs): - self.harvest.version = 'opml' - if attrs.get((None, 'version')) in ("1.0", "1.1"): - self.harvest.version = 'opml1' - elif attrs.get((None, 'version')) == "2.0": - self.harvest.version = 'opml2' - - def _start_opml_outline(self, attrs): - url = None - # Find an appropriate title in @text or @title (else empty) - if attrs.get((None, 'text'), '').strip(): - title = attrs[(None, 'text')].strip() - else: - title = attrs.get((None, 'title'), '').strip() - - # Search for the URL regardless of xmlUrl's case - for k, v in attrs.items(): - if k[1].lower() == 'xmlurl': - url = v.strip() - break - # Determine whether the outline is a feed or subscription list - if url is not None: - # It's a feed - append_to = 'feeds' - if attrs.get((None, 'type'), '').strip().lower() == 'source': - # Actually, it's a subscription list! - append_to = 'lists' - elif attrs.get((None, 'type'), '').lower() in ('link', 'include'): - # It's a subscription list - append_to = 'lists' - url = attrs.get((None, 'url'), '').strip() - elif title: - # Assume that this is a grouping node - self.hierarchy.append(title) - return - # Look for an opportunity URL - if not url and 'htmlurl' in (k[1].lower() for k in attrs.keys()): - for k, v in attrs.items(): - if k[1].lower() == 'htmlurl': - url = v.strip() - append_to = 'opportunities' - if not url: - # Maintain the hierarchy - self.hierarchy.append('') - return - if url not in self.found_urls: - # This is a brand new URL - obj = SuperDict({'url': url, 'title': title}) - self.found_urls[url] = (append_to, obj) - self.harvest[append_to].append(obj) - else: - obj = self.found_urls[url][1] - - # Handle categories and tags - obj.setdefault('categories', []) - if (None, 'category') in attrs.keys(): - for i in attrs[(None, 'category')].split(','): - tmp = [j.strip() for j in i.split('/') if j.strip()] - if tmp and tmp not in obj.categories: - obj.categories.append(tmp) - # Copy the current hierarchy into `categories` - if self.hierarchy and self.hierarchy not in obj.categories: - obj.categories.append(copy.copy(self.hierarchy)) - # Copy all single-element `categories` into `tags` - obj.tags = [i[0] for i in obj.categories if len(i) == 1] - - self.hierarchy.append('') - def _end_opml_outline(self): - self.hierarchy.pop() - - def _expect_characters(self, attrs): - # Most _start_opml_* functions only need to set these two variables, - # so this function exists to reduce significant code duplication - self.expect = True - self._characters = str() - - _start_opml_title = _expect_characters - def _end_opml_title(self): - if self.normchars(): - self.harvest.meta.title = self.normchars() - - _start_opml_ownerId = _expect_characters - def _end_opml_ownerId(self): - if self.normchars(): - self.harvest.meta.setdefault('author', SuperDict()) - self.harvest.meta.author.url = self.normchars() - - _start_opml_ownerEmail = _expect_characters - def _end_opml_ownerEmail(self): - if self.normchars(): - self.harvest.meta.setdefault('author', SuperDict()) - self.harvest.meta.author.email = self.normchars() - - _start_opml_ownerName = _expect_characters - def _end_opml_ownerName(self): - if self.normchars(): - self.harvest.meta.setdefault('author', SuperDict()) - self.harvest.meta.author.name = self.normchars() - - _start_opml_dateCreated = _expect_characters - def _end_opml_dateCreated(self): - if self.normchars(): - self.harvest.meta.created = self.normchars() - d = _rfc822(self.harvest.meta.created) - if isinstance(d, datetime.datetime): - self.harvest.meta.created_parsed = d - else: - self.raise_bozo('dateCreated is not an RFC 822 datetime') - - _start_opml_dateModified = _expect_characters - def _end_opml_dateModified(self): - if self.normchars(): - self.harvest.meta.modified = self.normchars() - d = _rfc822(self.harvest.meta.modified) - if isinstance(d, datetime.datetime): - self.harvest.meta.modified_parsed = d - else: - self.raise_bozo('dateModified is not an RFC 822 datetime') - - # iGoogle/GadgetTabML support - #----------------------------- - - def _start_gtml_GadgetTabML(self, attrs): - self.harvest.version = 'igoogle' - - def _start_gtml_Tab(self, attrs): - if attrs.get((None, 'title'), '').strip(): - self.hierarchy.append(attrs[(None, 'title')].strip()) - def _end_gtml_Tab(self): - if self.hierarchy: - self.hierarchy.pop() - - def _start_iGoogle_Module(self, attrs): - if attrs.get((None, 'type'), '').strip().lower() == 'rss': - self.flag_feed = True - def _end_iGoogle_Module(self): - self.flag_feed = False - - def _start_iGoogle_ModulePrefs(self, attrs): - if self.flag_feed and attrs.get((None, 'xmlUrl'), '').strip(): - obj = SuperDict({'url': attrs[(None, 'xmlUrl')].strip()}) - obj.title = '' - if self.hierarchy: - obj.categories = [copy.copy(self.hierarchy)] - if len(self.hierarchy) == 1: - obj.tags = copy.copy(self.hierarchy) - self.harvest.feeds.append(obj) - - # RDF+FOAF support - #------------------ - - def _start_rdf_RDF(self, attrs): - self.harvest.version = 'rdf' - - def _start_rss_channel(self, attrs): - if attrs.get((_ns['rdf'], 'about'), '').strip(): - # We now have a feed URL, so forget about any opportunity URL - if self.flag_opportunity: - self.flag_opportunity = False - self.agent_opps.pop() - self.agent_feeds.append(attrs.get((_ns['rdf'], 'about')).strip()) - - def _start_ya_feed(self, attrs): - if attrs.get((_ns['rdf'], 'resource'), '').strip(): - # This is a feed URL - self.agent_feeds.append(attrs[(_ns['rdf'], 'resource')].strip()) - - def _clean_found_objs(self): - if self.foaf_name: - title = self.foaf_name[-1] - else: - title = str() - for url in self.agent_feeds: - obj = SuperDict({'url': url, 'title': title}) - self.group_objs.append(('feeds', obj)) - for url in self.agent_lists: - obj = SuperDict({'url': url, 'title': title}) - self.group_objs.append(('lists', obj)) - for url in self.agent_opps: - obj = SuperDict({'url': url, 'title': title}) - self.group_objs.append(('opportunities', obj)) - - def _start_foaf_Agent(self, attrs): - self.flag_agent = True - self.flag_feed = True - self.flag_new_title = True - def _end_foaf_Agent(self): - if self.flag_agent: - self.flag_agent = False - self._clean_found_objs() - if self.foaf_name: - self.foaf_name.pop() - self.agent_feeds = [] - self.agent_lists = [] - self.agent_opps = [] - self.flag_agent = False - self.flag_feed = False - self.flag_opportunity = False - - def _start_foaf_Person(self, attrs): - self.flag_feed = True - self.flag_new_title = True - self._clean_found_objs() - _end_foaf_Person = _end_foaf_Agent - - def _start_rdfs_seeAlso(self, attrs): - if attrs.get((_ns['rdf'], 'resource'), '').strip(): - # This is a subscription list URL - self.agent_lists.append(attrs[(_ns['rdf'], 'resource')].strip()) - - def _start_foaf_Group(self, attrs): - self.flag_group = True - def _end_foaf_Group(self): - self.flag_group = False - for key, obj in self.group_objs: - # Check for duplicates - if obj.url in self.found_urls: - obj = self.found_urls[obj.url][1] - else: - self.found_urls[obj.url] = (key, obj) - self.harvest[key].append(obj) - # Create or consolidate categories and tags - obj.setdefault('categories', []) - obj.setdefault('tags', []) - if self.hierarchy and self.hierarchy not in obj.categories: - obj.categories.append(copy.copy(self.hierarchy)) - if len(self.hierarchy) == 1 and \ - self.hierarchy[0] not in obj.tags: - obj.tags.extend(copy.copy(self.hierarchy)) - self.group_objs = [] - # Maintain the hierarchy - if self.hierarchy: - self.hierarchy.pop() - _end_rdf_RDF = _end_foaf_Group - - _start_foaf_name = _expect_characters - def _end_foaf_name(self): - if self.flag_feed and self.flag_new_title: - self.foaf_name.append(self.normchars()) - self.flag_new_title = False - elif self.flag_group and self.normchars(): - self.hierarchy.append(self.normchars()) - self.flag_group = False - - _start_foaf_member_name = _expect_characters - _end_foaf_member_name = _end_foaf_name - - def _start_foaf_Document(self, attrs): - if attrs.get((_ns['rdf'], 'about'), '').strip(): - # Flag this as an opportunity (but ignore if a feed URL is found) - self.flag_opportunity = True - self.agent_opps.append(attrs.get((_ns['rdf'], 'about')).strip()) - -class HTTPRedirectHandler(urllib.request.HTTPRedirectHandler): - def http_error_301(self, req, fp, code, msg, hdrs): - result = urllib.request.HTTPRedirectHandler.http_error_301(self, req, fp, - code, msg, hdrs) - result.status = code - result.newurl = result.geturl() - return result - # The default implementations in urllib2.HTTPRedirectHandler - # are identical, so hardcoding a http_error_301 call above - # won't affect anything - http_error_302 = http_error_303 = http_error_307 = http_error_301 - -class HTTPErrorHandler(urllib.request.HTTPDefaultErrorHandler): - def http_error_default(self, req, fp, code, msg, hdrs): - # The default implementation just raises HTTPError. - # Forget that. - fp.status = code - return fp - -def _mkfile(obj, agent, etag, modified): - if hasattr(obj, 'read') and hasattr(obj, 'close'): - # It's file-like - return obj, SuperDict() - elif not isinstance(obj, str): - # This isn't a known-parsable object - err = ListError('parse() called with unparsable object') - return None, SuperDict({'bozo': 1, 'bozo_exception': err}) - elif not (obj.startswith('http://') or obj.startswith('https://') or - obj.startswith('ftp://') or obj.startswith('file://')): - # It's not a URL; test if it's an XML document - if obj.lstrip().startswith('<'): - return BytesStrIO(_to_bytes(obj)), SuperDict() - # Try dealing with it as a file - try: - return open(obj, 'rb'), SuperDict() - except IOError: - err = sys.exc_info()[1] - return None, SuperDict({'bozo': 1, 'bozo_exception': err}) - # It's a URL - headers = {} - if isinstance(agent, str): - headers['User-Agent'] = agent - if isinstance(etag, str): - headers['If-None-Match'] = etag - if isinstance(modified, str): - headers['If-Modified-Since'] = modified - elif isinstance(modified, datetime.datetime): - # It is assumed that `modified` is in UTC time - headers['If-Modified-Since'] = _to_rfc822(modified) - request = urllib.request.Request(obj, headers=headers) - opener = urllib.request.build_opener(HTTPRedirectHandler, HTTPErrorHandler) - try: - ret = opener.open(request) - except (urllib.error.URLError, http.client.HTTPException): - err = sys.exc_info()[1] - return None, SuperDict({'bozo': 1, 'bozo_exception': err}) - - info = SuperDict({'status': getattr(ret, 'status', 200)}) - info.href = getattr(ret, 'newurl', obj) - info.headers = SuperDict(getattr(ret, 'headers', {})) - # Python 3 doesn't normalize header names; Python 2 does - if info.headers.get('ETag') or info.headers.get('etag'): - info.etag = info.headers.get('ETag') or info.headers.get('etag') - if info.headers.get('Last-Modified') or info.headers.get('last-modified'): - info.modified = info.headers.get('Last-Modified') or \ - info.headers.get('last-modified') - if isinstance(_rfc822(info.modified), datetime.datetime): - info.modified_parsed = _rfc822(info.modified) - return ret, info - - -def _rfc822(date): - """Parse RFC 822 dates and times - http://tools.ietf.org/html/rfc822#section-5 - - There are some formatting differences that are accounted for: - 1. Years may be two or four digits. - 2. The month and day can be swapped. - 3. Additional timezone names are supported. - 4. A default time and timezone are assumed if only a date is present. - 5. - """ - daynames = set(['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']) - months = { - 'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6, - 'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12, - } - timezonenames = { - 'ut': 0, 'gmt': 0, 'z': 0, - 'adt': -3, 'ast': -4, 'at': -4, - 'edt': -4, 'est': -5, 'et': -5, - 'cdt': -5, 'cst': -6, 'ct': -6, - 'mdt': -6, 'mst': -7, 'mt': -7, - 'pdt': -7, 'pst': -8, 'pt': -8, - 'a': -1, 'n': 1, - 'm': -12, 'y': 12, - } - - parts = date.lower().split() - if len(parts) < 5: - # Assume that the time and timezone are missing - parts.extend(('00:00:00', '0000')) - # Remove the day name - if parts[0][:3] in daynames: - parts = parts[1:] - if len(parts) < 5: - # If there are still fewer than five parts, there's not enough - # information to interpret this - return None - try: - day = int(parts[0]) - except ValueError: - # Check if the day and month are swapped - if months.get(parts[0][:3]): - try: - day = int(parts[1]) - except ValueError: - return None - else: - parts[1] = parts[0] - else: - return None - month = months.get(parts[1][:3]) - if not month: - return None - try: - year = int(parts[2]) - except ValueError: - return None - # Normalize two-digit years: - # Anything in the 90's is interpreted as 1990 and on - # Anything 89 or less is interpreted as 2089 or before - if len(parts[2]) <= 2: - year += (1900, 2000)[year < 90] - timeparts = parts[3].split(':') - timeparts = timeparts + ([0] * (3 - len(timeparts))) - try: - (hour, minute, second) = map(int, timeparts) - except ValueError: - return None - tzhour = 0 - tzmin = 0 - # Strip 'Etc/' from the timezone - if parts[4].startswith('etc/'): - parts[4] = parts[4][4:] - # Normalize timezones that start with 'gmt': - # GMT-05:00 => -0500 - # GMT => GMT - if parts[4].startswith('gmt'): - parts[4] = ''.join(parts[4][3:].split(':')) or 'gmt' - # Handle timezones like '-0500', '+0500', and 'EST' - if parts[4] and parts[4][0] in ('-', '+'): - try: - tzhour = int(parts[4][1:3]) - tzmin = int(parts[4][3:]) - except ValueError: - return None - if parts[4].startswith('-'): - tzhour = tzhour * -1 - tzmin = tzmin * -1 - else: - tzhour = timezonenames.get(parts[4], 0) - # Create the datetime object and timezone delta objects - try: - stamp = datetime.datetime(year, month, day, hour, minute, second) - except ValueError: - return None - delta = datetime.timedelta(0, 0, 0, 0, tzmin, tzhour) - # Return the date and timestamp in a UTC 9-tuple - try: - return stamp - delta - except (OverflowError, ValueError): - # IronPython throws ValueErrors instead of OverflowErrors - return None - -def _to_rfc822(date): - """_to_rfc822(datetime.datetime) -> str - The datetime `strftime` method is subject to locale-specific - day and month names, so this function hardcodes the conversion.""" - months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', - 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] - days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] - fmt = '%(day)s, %(d)02i %(month)s %(y)04i %(h)02i:%(m)02i:%(s)02i GMT' - return fmt % { - 'day': days[date.weekday()], - 'd': date.day, - 'month': months[date.month - 1], - 'y': date.year, - 'h': date.hour, - 'm': date.minute, - 's': date.second, - } - -class SuperDict(dict): - """ - SuperDict is a dictionary object with keys posing as instance attributes. - - >>> i = SuperDict() - >>> i.one = 1 - >>> i - {'one': 1} - """ - - def __getattribute__(self, name): - if name in self: - return self[name] - else: - return dict.__getattribute__(self, name) - - def __setattr__(self, name, value): - self[name] = value - return value - -class Injector(object): - """ - Injector buffers read() calls to a file-like object in order to - inject a DOCTYPE containing HTML entity definitions immediately - following the XML declaration. - """ - def __init__(self, obj): - self.obj = obj - self.injected = False - self.cache = _to_bytes('') - def read(self, size): - # Read from the cache (and the object if necessary) - read = self.cache[:size] - if len(self.cache) < size: - read += self.obj.read(size - len(self.cache)) - self.cache = self.cache[size:] - - if self.injected or _to_bytes('>') not in read: - return read - - # Inject the entity declarations into the cache - entities = str() - for k, v in htmlentitydefs.name2codepoint.items(): - entities += '' % (k, v) - # The '>' is deliberately missing; it will be appended by join() - doctype = "'), 1) - content.insert(1, _to_bytes(doctype)) - self.cache = _to_bytes('>').join(content) - self.injected = True - - ret = self.cache[:size] - self.cache = self.cache[size:] - return ret - def __getattr__(self, name): - return getattr(self.obj, name) - -class ListError(Exception): - """Used when a specification deviation is encountered in an XML file""" - pass diff --git a/lptest.py b/lptest.py deleted file mode 100644 index b8ed614..0000000 --- a/lptest.py +++ /dev/null @@ -1,416 +0,0 @@ -# lptest.py - Run unit tests against listparser.py -# Copyright (C) 2009-2015 Kurt McKee -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser 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 Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see . - -import datetime # required by evals -import os -from os.path import abspath, dirname, join, splitext -import threading -import unittest -import sys - -import listparser - -try: - import BaseHTTPServer - import SimpleHTTPServer -except ImportError: - import http.server - BaseHTTPServer = http.server - SimpleHTTPServer = http.server - -try: - from StringIO import StringIO -except ImportError: - from io import StringIO - -try: - if bytes is str: - # bytes is an alias for str in Python 2.6 and 2.7 - raise NameError -except NameError: - # Python 2 - def _to_unicode(obj): - """_to_unicode(str or unicode) -> unicode""" - if isinstance(obj, str): - obj.decode('utf-8') - return obj -else: - # Python 3 - def _to_unicode(obj): - """_to_unicode(bytes or str) -> str""" - if isinstance(obj, bytes): - return obj.decode('utf-8') - return obj - -try: - unicode -except NameError: - # Python 3 - def _to_str(obj): - return obj -else: - # Python 2 - def _to_str(obj): - """_to_str(unicode or str) -> str (UTF-8 encoded)""" - if isinstance(obj, unicode): - return obj.encode('utf-8') - return obj - -class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler): - def do_GET(self): - status = 200 - location = etag = modified = None - reply = listparser._to_bytes('') - end_directives = False - f = open(dirname(abspath(__file__)) + self.path, 'rb') - for line in f: - reply += line - line = line.decode('utf8', 'replace') - if not end_directives: - if line.strip() == '-->': - end_directives = True - elif 'Status:' in line: - status = int(line.strip()[7:]) - elif 'Location:' in line: - location = line.strip()[9:].strip() - elif 'Server-ETag:' in line: - etag = line.split(': ', 1)[1].strip() - if self.headers.get('if-none-match') == etag: - status = 304 - elif 'Server-Modified:' in line: - modified = line.split(': ', 1)[1].strip() - if self.headers.get('if-modified-since') == modified: - status = 304 - f.close() - self.send_response(status) - if location: - self.send_header('Location', location) - if etag: - self.send_header('ETag', etag) - if modified: - self.send_header('Last-Modified', modified) - self.send_header('Content-type', 'text/xml') - self.send_header('x-agent', self.headers.get('user-agent')) - self.end_headers() - self.wfile.write(reply) - def log_request(self, *arg, **karg): - pass - -class ServerThread(threading.Thread): - def __init__(self, numtests): - super(ServerThread, self).__init__() - self.numtests = numtests - self.ready = threading.Event() - def run(self): - server = BaseHTTPServer.HTTPServer - bind_to = ('127.0.0.1', 8091) - reqhandler = Handler - httpd = server(bind_to, reqhandler) - self.ready.set() - for i in range(self.numtests): - httpd.handle_request() - -class TestCases(unittest.TestCase): - def testUserAgentInvalid(self): - url = 'http://localhost:8091/tests/http/useragent.xml' - obj, sdict = listparser._mkfile(url, True, None, None) - obj.close() - self.assertEqual(sdict.status, 200) - def testUserAgentDefault(self): - url = 'http://localhost:8091/tests/http/useragent.xml' - result = listparser.parse(url) - self.assertFalse(result.bozo) - self.assert_(result.headers.get('x-agent') == listparser.USER_AGENT) - def testUserAgentCustomArg(self): - url = 'http://localhost:8091/tests/http/useragent.xml' - result = listparser.parse(url, agent="CustomAgent") - self.assertFalse(result.bozo) - self.assert_(result.headers.get('x-agent') == "CustomAgent") - def testUserAgentGlobalOverride(self): - url = 'http://localhost:8091/tests/http/useragent.xml' - tmp = listparser.USER_AGENT - listparser.USER_AGENT = "NewGlobalAgent" - result = listparser.parse(url) - listparser.USER_AGENT = tmp - self.assertFalse(result.bozo) - self.assert_(result.headers.get('x-agent') == "NewGlobalAgent") - def testImage(self): - f = os.path.abspath(os.path.join('tests', '1x1.gif')) - result = listparser.parse(f) - self.assert_(result.bozo == 1) - def worker(self, evals, testfile, etag, modified): - if 'http' in testfile: - testfile = 'http://localhost:8091/tests/' + testfile - else: - testfile = join('tests', testfile) - result = listparser.parse(testfile, etag=etag, modified=modified) - for ev in evals: - self.assert_(eval(ev)) - -class TestMkfile(unittest.TestCase): - def _bad_test(obj): - # A TestCase factory; its tests assume unusable return values - def fn(self): - n, sdict = listparser._mkfile(obj, 'agent', None, None) - self.assert_(n is None) - self.assertEqual(sdict.bozo, 1) - return fn - testUnparsableObject = _bad_test(True) - testBadURLProtocol = _bad_test("xxx://badurl.com/") - testBadURLUnreachable = _bad_test("http://badurl.com.INVALID/") - testBogusFilename = _bad_test('totally made up and bogus /\:') - - def _good_test(obj): - # A TestCase factory; its tests expect a usable file-like or - # stream object and an empty SuperDict will be returned - def fn(self): - f, sdict = listparser._mkfile(obj, 'agent', None, None) - f.close() - self.assert_(f is not None) - self.assertFalse(sdict) - return fn - doc = """""" - testStringInput = _good_test(doc) - testFileishInput = _good_test(StringIO(_to_str(doc))) - - testfile = os.path.join('tests', 'filename.xml') - testRelativeFilename = _good_test(testfile) - testAbsoluteFilename = _good_test(os.path.abspath(testfile)) - -class TestInjection(unittest.TestCase): - def _read_size(size): - # Return a TestCase function that will manually feed the subscription - # list through the Injector, calling read() using the given size - def fn(self): - doc = listparser._to_bytes(""" - á - - - - """) - idoc = listparser.Injector(listparser.BytesStrIO(doc)) - tmp = [] - while 1: - i = idoc.read(size) - if i: - tmp.append(i) - else: - idoc.close() - break - xml = _to_unicode(listparser._to_bytes('').join(tmp)) - result = listparser.parse(xml) - self.assertFalse(result.bozo) - self.assertEqual(len(result.feeds), 1) - self.assertEqual(ord(result.feeds[0].title), 225) # \u00e1 - return fn - testRead1by1 = _read_size(1) - testReadChunks = _read_size(20) - -class TestRFC822(unittest.TestCase): - def testGeneral(self): - dt = listparser._rfc822('Sun, 14 Jun 2009 11:47:32 GMT') - self.assertEqual(dt.day, 14) - self.assertEqual(dt.month, 6) - self.assertEqual(dt.year, 2009) - self.assertEqual(dt.hour, 11) - self.assertEqual(dt.minute, 47) - self.assertEqual(dt.second, 32) - def testSwappedMonthAndDay(self): - dt = listparser._rfc822('Sun, Dec 16 2012 11:15:01 GMT') - self.assertEqual(dt.day, 16) - self.assertEqual(dt.month, 12) - self.assertEqual(dt.year, 2012) - self.assertEqual(dt.hour, 11) - self.assertEqual(dt.minute, 15) - self.assertEqual(dt.second, 1) - def testMissingTimeAndTimezone(self): - dt = listparser._rfc822('Sun, Dec 16 2012') - self.assertEqual(dt.day, 16) - self.assertEqual(dt.month, 12) - self.assertEqual(dt.year, 2012) - self.assertEqual(dt.hour, 0) - self.assertEqual(dt.minute, 0) - self.assertEqual(dt.second, 0) - def testSingleDigitDay(self): - dt = listparser._rfc822('Thu, 5 Apr 2012 10:00:00 GMT') - self.assertEqual(dt.day, 5) - def testSecondMissing(self): - dt = listparser._rfc822('Sun, 21 Jun 2009 12:00 GMT') - self.assertEqual(dt.second, 0) - - def _month_test(s, month): - # Take an RFC822 datetime string and a month integer (1-12) and - # return a TestCase function that tests that datetime.month == m - def fn(self): - dt = listparser._rfc822(s) - self.assertEqual(dt.month, month) - return fn - testMonth01 = _month_test('21 Jan 2009 12:00:00 GMT', 1) - testMonth02 = _month_test('21 Feb 2009 12:00:00 GMT', 2) - testMonth03 = _month_test('21 Mar 2009 12:00:00 GMT', 3) - testMonth04 = _month_test('21 Apr 2009 12:00:00 GMT', 4) - testMonth05 = _month_test('21 May 2009 12:00:00 GMT', 5) - testMonth06 = _month_test('21 Jun 2009 12:00:00 GMT', 6) - testMonth07 = _month_test('21 Jul 2009 12:00:00 GMT', 7) - testMonth08 = _month_test('21 Aug 2009 12:00:00 GMT', 8) - testMonth09 = _month_test('21 Sep 2009 12:00:00 GMT', 9) - testMonth10 = _month_test('21 Oct 2009 12:00:00 GMT', 10) - testMonth11 = _month_test('21 Nov 2009 12:00:00 GMT', 11) - testMonth12 = _month_test('21 Dec 2009 12:00:00 GMT', 12) - - def _tz_test(s, hour, minute=15, day=22): - # Take an RFC822 datetime string, and hour, minute, and day - # integers, and return a TestCase function that tests that: - # dt.hour == hour, dt.minute == minute, dt.day == day - def fn(self): - dt = listparser._rfc822(s) - self.assertEqual(dt.hour, hour) - self.assertEqual(dt.minute, minute) - self.assertEqual(dt.day, day) - return fn - testTZ_Z = _tz_test('Mon, 22 Jun 2009 13:15:17 Z', 13) - testTZ_UT = _tz_test('Mon, 22 Jun 2009 13:15:17 UT', 13) - testTZ_GMT = _tz_test('Mon, 22 Jun 2009 13:15:17 GMT', 13) - testTZ_CDT = _tz_test('Mon, 22 Jun 2009 13:15:17 CDT', 18) - testTZ_CST = _tz_test('Mon, 22 Jun 2009 13:15:17 CST', 19) - testTZ_EDT = _tz_test('Mon, 22 Jun 2009 13:15:17 EDT', 17) - testTZ_EST = _tz_test('Mon, 22 Jun 2009 13:15:17 EST', 18) - testTZ_MDT = _tz_test('Mon, 22 Jun 2009 13:15:17 MDT', 19) - testTZ_MST = _tz_test('Mon, 22 Jun 2009 13:15:17 MST', 20) - testTZ_PDT = _tz_test('Mon, 22 Jun 2009 13:15:17 PDT', 20) - testTZ_PST = _tz_test('Mon, 22 Jun 2009 13:15:17 PST', 21) - testTZ_A = _tz_test('Mon, 22 Jun 2009 13:15:17 A', 14) - testTZ_N = _tz_test('Mon, 22 Jun 2009 13:15:17 N', 12) - testTZ_M = _tz_test('Mon, 22 Jun 2009 13:15:17 M', 1, day=23) - testTZ_Y = _tz_test('Mon, 22 Jun 2009 13:15:17 Y', 1, day=22) - testTZ_plus = _tz_test('Mon, 22 Jun 2009 13:15:17 -0430', 17, minute=45) - testTZ_minus = _tz_test('Mon, 22 Jun 2009 13:15:17 +0545', 7, minute=30) - testTZ_ETC_GMT = _tz_test('Mon, 22 Jun 2009 13:15:17 Etc/GMT', 13) - testTZ_crasher = _tz_test('Mon, 22 Jun 2009 13:15:17 Etc/', 13) - - def _year2digit_test(s, year): - # Take an RFC822 datetime string and a year and, - # return a TestCase that tests that dt.year == y - def fn(self): - dt = listparser._rfc822(s) - self.assertEqual(dt.year, year) - return fn - testYear2Digit00 = _year2digit_test('Wed, 21 Jun 00 12:00:00 GMT', 2000) - testYear2Digit89 = _year2digit_test('Wed, 21 Jun 89 12:00:00 GMT', 2089) - testYear2Digit90 = _year2digit_test('Thu, 21 Jun 90 12:00:00 GMT', 1990) - testYear2Digit99 = _year2digit_test('Mon, 21 Jun 99 12:00:00 GMT', 1999) - - def _invalid_date_test(s): - # Test extreme date and time ranges - def fn(self): - dt = listparser._rfc822(s) - self.assertEqual(dt, None) - return fn - testRangeDayHigh = _invalid_date_test('Sun, 99 Jun 2009 12:00:00 GMT') - testRangeDayLow = _invalid_date_test('Sun, 00 Jun 2009 12:00:00 GMT') - testRangeHour = _invalid_date_test('Sun, 01 Jun 2009 99:00:00 GMT') - testRangeMinute = _invalid_date_test('Sun, 01 Jun 2009 00:99:00 GMT') - testRangeSecond = _invalid_date_test('Sun, 01 Jun 2009 00:00:99 GMT') - testRangeYearHigh = _invalid_date_test('Sun, 31 Dec 9999 23:59:59 -9999') - testRangeYearLow = _invalid_date_test('Sun, 01 Jan 0000 00:00:00 +9999') - testTooFewParts = _invalid_date_test('yesterday') - testTooManyTimeParts = _invalid_date_test('Sun, 16 Dec 2012 1:2:3:4 GMT') - testBadMonthName = _invalid_date_test('Sun, 16 zzz 2012 11:47:32 GMT') - testBadMonthDaySwap = _invalid_date_test('Sun, Dec x 2012 11:47:32 GMT') - testBadYear = _invalid_date_test('Sun, 16 Dec zz 11:47:32 GMT') - testBadPosTZHour = _invalid_date_test('Sun, 16 Dec 2012 11:47:32 +zz:00') - testBadPosTZMinute = _invalid_date_test('Sun, 16 Dec 2012 11:47:32 +00:zz') - testBadNegTZHour = _invalid_date_test('Sun, 16 Dec 2012 11:47:32 -zz:00') - testBadNegTZMinute = _invalid_date_test('Sun, 16 Dec 2012 11:47:32 -00:zz') - -def make_testcase(evals, testfile, etag, modified): - # HACK: Only necessary in order to ensure that `evals` is evaluated - # for every testcase, not just for the last one in the loop below - # (where, apparently, `lambda` would cause it to be evaluated only - # once at the end of the loop, containing the final testcase' values). - return lambda self: self.worker(evals, testfile, etag, modified) - -numtests = 0 -testpath = join(dirname(abspath(__file__)), 'tests/') -# files contains a list of relative paths to test files -# HACK: replace() is only being used because os.path.relpath() -# was only added to Python in version 2.6 -files = (join(r, f).replace(testpath, '', 1) - for r, d, files in os.walk(testpath) - for f in files if f.endswith('.xml')) -for testfile in files: - info = {} - evals = [] - openfile = open(join(testpath, testfile), 'rb') - for line in openfile: - line = line.decode('utf8', 'replace').strip() - if '-->' in line: - break - if line.lstrip().startswith('Eval:'): - evals.append(line.split(': ', 1)[1].strip()) - elif ': ' in line: - info.update((map(str.strip, _to_str(line).split(': ', 1)),)) - openfile.close() - description = info.get('Description', '') - etag = info.get('ETag', None) - modified = info.get('Modified', None) - if 'http' in testfile: - numtests += int(info.get('Requests', 1)) - - if 'No-Eval' in info: - # No-Eval files are requested over HTTP (generally representing - # an HTTP redirection destination) and contain no testcases. - # They probably have a Requests directive, though, which is why - # the `continue` here appears after numtests is incremented. - continue - if not description: - raise ValueError("Description not found in test %s" % testfile) - if not evals: - raise ValueError("Eval not found in test %s" % testfile) - if modified: - testcase = make_testcase(evals, testfile, etag, modified) - testcase.__doc__ = '%s: %s [string]' % (testfile, description) - setattr(TestCases, 'test_%s_1' % splitext(testfile)[0], testcase) - testcase = make_testcase(evals, testfile, etag, - listparser._rfc822(modified)) - testcase.__doc__ = '%s: %s [datetime]' % (testfile, description) - setattr(TestCases, 'test_%s_2' % splitext(testfile)[0], testcase) - else: - testcase = make_testcase(evals, testfile, etag, modified) - testcase.__doc__ = '%s: %s' % (testfile, description) - setattr(TestCases, 'test_%s' % splitext(testfile)[0], testcase) - -server = ServerThread(numtests) -server.setDaemon(True) -server.start() - -# Wait for the server thread to signal that it's ready -server.ready.wait() - -testsuite = unittest.TestSuite() -testloader = unittest.TestLoader() -testsuite.addTest(testloader.loadTestsFromTestCase(TestCases)) -testsuite.addTest(testloader.loadTestsFromTestCase(TestInjection)) -testsuite.addTest(testloader.loadTestsFromTestCase(TestRFC822)) -testsuite.addTest(testloader.loadTestsFromTestCase(TestMkfile)) -testresults = unittest.TextTestRunner(verbosity=1).run(testsuite) - -# Return 0 if successful, 1 if there was a failure -sys.exit(not testresults.wasSuccessful()) diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..900a96d --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,117 @@ +[tool.poetry] +name = "listparser" +version = "0.19" +description = "Parse OPML subscription lists" +authors = ["Kurt McKee "] +license = "MIT" +readme = "README.rst" +repository = "https://github.com/kurtmckee/listparser/" +documentation = "https://listparser.readthedocs.io/en/stable/" +keywords = ["opml", "foaf", "igoogle", "feed"] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Topic :: Text Processing :: Markup :: XML", +] + +[tool.poetry.dependencies] +python = "^3.7" +requests = {version = "^2.25.1", optional = true} +lxml = {version = "^4.6.2", optional = true} + + +[tool.poetry.extras] +http = ['requests'] +lxml = ['lxml'] + + +[tool.poetry.dev-dependencies] +tox = "^3.25.0" +Sphinx = "^5.0.0" +scriv = "^0.15.0" + + +[build-system] +requires = ["poetry-core>=1.0.0"] +build-backend = "poetry.core.masonry.api" + + +[tool.tox] +legacy_tox_ini = """ + +[tox] +envlist = + coverage_erase + py{310, 39, 38, 37}{-requests,}{-lxml,}, pypy3{-requests,} + coverage_report + flake8 + docs + +skip_missing_interpreters = True +isolated_build = True + +[testenv] +deps = + lxml: lxml + requests: requests + pytest + pytest-cov + +commands = + {envpython} -m pytest --cov=listparser --cov=tests --cov-append + +[testenv:flake8] +skipsdist = true +skip_install = true +deps = + flake8 + +commands = + {envpython} -m flake8 src tests docs + +[testenv:docs] +skipsdist = true +skip_install = true +deps = + lxml + sphinx + toml + +commands = + {envpython} -m sphinx -aWEqb html docs/ build/trash + +[testenv:coverage_erase] +skipsdist = true +skip_install = true +deps = coverage[toml] +commands = coverage erase + +[testenv:coverage_report] +skipsdist = true +skip_install = true +deps = coverage[toml] +commands = coverage html -d htmlcov + +""" + + +[tool.coverage.run] +branch = true + + +[tool.coverage.paths] +source = [ + "src", + ".tox/*/site-packages", +] + + +[tool.scriv] +version = "literal: pyproject.toml: tool.poetry.version" +categories = ["Added", "Fixed", "Removed", "Changed", "Deprecated", "Security"] +entry_title_template = "{{ version }} - {{ date.strftime('%Y-%m-%d') }}" +format = "rst" +fragment_directory = "changelog.d" +insert_marker = "scriv-insert-here" +main_branches = ["develop", "master"] +new_fragment_template = "file: fragment-template.rst.txt" diff --git a/setup.py b/setup.py deleted file mode 100644 index 1d4fba7..0000000 --- a/setup.py +++ /dev/null @@ -1,34 +0,0 @@ -from setuptools import setup - -setup( - name='listparser', - version='0.18', - description='Parse OPML, FOAF, and iGoogle subscription lists.', - long_description="""listparser is a Python library that parses subscription lists (also called reading lists) and returns all of the feeds, subscription lists, and "opportunity" URLs that it finds. It supports OPML, RDF+FOAF, and the iGoogle exported settings format.""", - author='Kurt McKee', - author_email='contactme@kurtmckee.org', - url='https://github.com/kurtmckee/listparser', - py_modules=['listparser'], - classifiers=[ - 'Development Status :: 5 - Production/Stable', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', - 'Programming Language :: Java', - 'Programming Language :: Python', - 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 2.4', - 'Programming Language :: Python :: 2.5', - 'Programming Language :: Python :: 2.6', - 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.0', - 'Programming Language :: Python :: 3.1', - 'Programming Language :: Python :: 3.2', - 'Programming Language :: Python :: 3.3', - 'Programming Language :: Python :: Implementation :: CPython', - 'Programming Language :: Python :: Implementation :: Jython', - 'Programming Language :: Python :: Implementation :: PyPy', - 'Topic :: Software Development :: Libraries', - 'Topic :: Text Processing :: Markup :: XML', - ] -) diff --git a/src/listparser/__init__.py b/src/listparser/__init__.py new file mode 100644 index 0000000..46f86a4 --- /dev/null +++ b/src/listparser/__init__.py @@ -0,0 +1,103 @@ +# This file is part of listparser. +# Copyright 2009-2022 Kurt McKee +# SPDX-License-Identifier: MIT +# + +import io +from typing import Dict, Optional, Tuple, Union + +import xml.sax + +try: + import requests +except ImportError: + requests = None + +from . import common +from .exceptions import ListparserError +from . import parsers + + +__author__ = 'Kurt McKee ' +__url__ = 'https://github.com/kurtmckee/listparser' +__version__ = '0.19' + + +def parse(parse_obj: Union[str, bytes]) -> common.SuperDict: + """Parse a subscription list and return a dict containing the results. + + *parse_obj* must be one of the following: + + * a string containing a URL + * a string or bytes object containing an XML document + + The dictionary returned will contain all of the parsed information, + HTTP response headers (if applicable), and any exception encountered. + """ + + guarantees = { + 'bozo': False, + 'bozo_exception': None, + 'feeds': [], + 'lists': [], + 'opportunities': [], + 'meta': common.SuperDict(), + 'version': '', + } + content, info = get_content(parse_obj) + guarantees.update(info) + if not content: + return common.SuperDict(guarantees) + + handler = parsers.Handler() + handler.harvest.update(guarantees) + content_file = io.BytesIO(content) + + if parsers.lxml: + parser = parsers.lxml.etree.XMLParser(target=handler, recover=True) + parsers.lxml.etree.parse(content_file, parser) + else: + parser = xml.sax.make_parser() + parser.setFeature(xml.sax.handler.feature_namespaces, True) + parser.setContentHandler(handler) + parser.setErrorHandler(handler) + parser.parse(content_file) + + return common.SuperDict(handler.harvest) + + +def get_content(obj) -> Tuple[Optional[bytes], Dict]: + if isinstance(obj, bytes): + return obj, {'bozo': False, 'bozo_exception': None} + elif not isinstance(obj, str): + # Only str and bytes objects can be parsed. + error = ListparserError('parse() called with unparsable object') + return None, {'bozo': True, 'bozo_exception': error} + elif not obj.startswith(('http://', 'https://')): + # It's not a URL, so it must be treated as an XML document. + return obj.encode('utf8'), { + 'bozo': False, + 'bozo_exception': None, + } + + # It's a URL. Confirm requests is installed. + elif requests is None: + message = f"requests is not installed so {obj} cannot be retrieved" + return None, { + 'bozo': True, + 'bozo_exception': ListparserError(message), + } + + headers = {'user-agent': f'listparser/{__version__} +{__url__}'} + try: + response = requests.get(obj, headers=headers, timeout=30) + except ( + requests.exceptions.RequestException, + requests.exceptions.BaseHTTPError, + ) as error: + return None, {'bozo': True, 'bozo_exception': error} + + return response.text.encode('utf8'), { + 'bozo': False, + 'bozo_exception': None, + } diff --git a/src/listparser/common.py b/src/listparser/common.py new file mode 100644 index 0000000..e70bff3 --- /dev/null +++ b/src/listparser/common.py @@ -0,0 +1,100 @@ +# This file is part of listparser. +# Copyright 2009-2022 Kurt McKee +# SPDX-License-Identifier: MIT +# + +from typing import Callable, Dict, List, Tuple, Union + +from .exceptions import ListparserError + + +namespaces = { + 'http://opml.org/spec2': 'opml', + 'http://www.google.com/ig': 'iGoogle', + 'http://schemas.google.com/GadgetTabML/2008': 'gtml', + 'http://www.w3.org/1999/02/22-rdf-syntax-ns#': 'rdf', + 'http://www.w3.org/2000/01/rdf-schema#': 'rdfs', + 'http://xmlns.com/foaf/0.1/': 'foaf', + 'http://purl.org/dc/elements/1.1/': 'dc', + 'http://purl.org/rss/1.0/': 'rss', + 'http://blogs.yandex.ru/schema/foaf/': 'ya', +} + + +class SuperDict(dict): + """ + SuperDict is a dictionary object with keys posing as instance attributes. + + .. code-block:: pycon + + >>> i = SuperDict() + >>> i.one = 1 + >>> i + {'one': 1} + + """ + + def __getattribute__(self, name): + if name in self: + return self[name] + else: + return dict.__getattribute__(self, name) + + +class CommonMixin: + def __init__(self): + super().__init__() + self.harvest = {} + self.flag_expect_text: bool = False + self.text: List[str] = [] + self.hierarchy = [] + self.flag_agent = False + self.flag_feed = False + self.flag_new_title = False + self.flag_opportunity = False + self.flag_group = False + + # found_urls = {url: (append_to_key, obj)} + self.found_urls: Dict[str, Tuple[str, Dict]] = {} + + # group_objs = [(append_to_key, obj)] + self.group_objs: List[Tuple[str, Dict]] = [] + self.agent_feeds = [] + self.agent_lists = [] + self.agent_opps = [] + self.foaf_name = [] + + # Cache element-to-method name lookups. + # + # The dictionary key types vary between parsers: + # + # If lxml is the parser, the keys will be strings. + # If xml.sax is the parser, the keys will be tuples of strings. + # + self.start_methods: Dict[Union[Tuple[str, str], str], Callable] = {} + self.end_methods: Dict[Union[Tuple[str, str], str], Callable] = {} + + def raise_bozo(self, error: Union[Exception, str]): + self.harvest['bozo'] = True + if isinstance(error, str): + self.harvest['bozo_exception'] = ListparserError(error) + else: + self.harvest['bozo_exception'] = error + + def expect_text(self, _): + """Flag that text content is anticipated. + + Many start_* methods only need to prepare for text content. + This method exists so those start_* methods can be declared + as aliases for this method. + """ + + self.flag_expect_text = True + self.text = [] + + def get_text(self) -> str: + """Get text content.""" + + text = ''.join(self.text).strip() + self.text = [] + return text diff --git a/src/listparser/dates.py b/src/listparser/dates.py new file mode 100644 index 0000000..7169380 --- /dev/null +++ b/src/listparser/dates.py @@ -0,0 +1,172 @@ +# This file is part of listparser. +# Copyright 2009-2022 Kurt McKee +# SPDX-License-Identifier: MIT +# + +import datetime +from typing import Dict, Optional + + +months: Dict[str, int] = { + 'jan': 1, + 'feb': 2, + 'mar': 3, + 'apr': 4, + 'may': 5, + 'jun': 6, + 'jul': 7, + 'aug': 8, + 'sep': 9, + 'oct': 10, + 'nov': 11, + 'dec': 12, +} + +timezones: Dict[str, int] = { + # Universal Time + 'ut': 0, + 'utc': 0, + 'gmt': 0, + + # North America + 'est': -5, + 'edt': -4, + 'cst': -6, + 'cdt': -5, + 'mst': -7, + 'mdt': -6, + 'pst': -8, + 'pdt': -7, + + # Military + 'z': 0, + 'a': -1, + 'n': +1, + 'm': -12, + 'y': +12, +} + + +def parse_rfc822(date: str) -> Optional[datetime.datetime]: + """Parse RFC 822 dates and times. + + https://tools.ietf.org/html/rfc822#section-5 + + The basic format is: + + .. code-block:: text + + [ day "," ] dd mmm [yy]yy hh:mm[:ss] zzz + + Note that RFC 822 only specifies an explicit comma, + but fails to make whitespace mandatory. + + Some non-standard formatting differences are allowed: + + * Whitespace is assumed to separate each part of the timestamp. + * Years may be two or four digits. + This is explicitly allowed in the OPML specification. + * The month name and day can be swapped. + * Timezones may be prefixed with "Etc/". + * If the time and/or timezone are missing, + midnight and GMT will be assumed. + * "UTC" is supported as a timezone name. + + """ + + parts = date.rpartition(',')[2].lower().split() + if len(parts) == 3: + # Assume that the time is missing. + parts.append('00:00:00') + if len(parts) == 4: + # Assume that the timezone is missing. + parts.append('gmt') + elif len(parts) != 5: + # If there are not exactly five parts then this isn't an + # RFC 822 date and time. + return None + + # Parse the day and month. + try: + day = int(parts[0]) + except ValueError: + # Check if the day and month are swapped. + if months.get(parts[0][:3]): + try: + day = int(parts[1]) + except ValueError: + return None + else: + parts[1] = parts[0] + else: + return None + month = months.get(parts[1][:3]) + if month is None: + return None + + # Parse the year. + try: + year = int(parts[2]) + except ValueError: + return None + # Normalize two-digit years: + # + # * Anything in the 90's is interpreted as the 1990's. + # * Anything 89 or before is interpreted as 2089 or before. + # + if year < 100: + if year >= 90: + year += 1900 + else: + year += 2000 + + # Parse the time. + time_parts = parts[3].split(':') + time_parts += ['0'] * (3 - len(time_parts)) + try: + hour, minute, second = map(int, time_parts) + except ValueError: + return None + + # Parse named timezones. + tz_min = 0 + # Strip 'Etc/' from the timezone name. + timezone = parts[4] + if timezone.startswith('etc/'): + timezone = timezone[4:] or 'gmt' + # Normalize timezones that start with 'gmt': + # + # * gmt-05:00 => -05:00 + # * gmt => gmt + # + if timezone.startswith('gmt'): + timezone = timezone[3:] or 'gmt' + tz_hour = timezones.get(timezone) + + # Parse numeric timezones like '-0500' and '+0500'. + if tz_hour is None: + try: + tz_left, tz_right = timezone.split(':') + tz_hour = int(tz_left) + tz_min = int(tz_right) + except ValueError: + # Perhaps there was no ':' in *timezone*. + try: + tz_hour = int(timezone[:-2]) + tz_min = int(timezone[-2:]) + except ValueError: + return None + if tz_hour < 0: + tz_min = tz_min * -1 + + # Create the datetime and timezone offset return values. + try: + return datetime.datetime( + year, month, day, + hour, minute, second, + tzinfo=datetime.timezone( + datetime.timedelta(minutes=(tz_hour * 60) + tz_min) + ), + ) + except (ValueError, OverflowError): + return None diff --git a/src/listparser/exceptions.py b/src/listparser/exceptions.py new file mode 100644 index 0000000..98b0f7d --- /dev/null +++ b/src/listparser/exceptions.py @@ -0,0 +1,7 @@ +# This file is part of listparser. +# Copyright 2009-2022 Kurt McKee +# SPDX-License-Identifier: MIT +# + +class ListparserError(Exception): + pass diff --git a/src/listparser/foaf.py b/src/listparser/foaf.py new file mode 100644 index 0000000..a70b4eb --- /dev/null +++ b/src/listparser/foaf.py @@ -0,0 +1,127 @@ +# This file is part of listparser. +# Copyright 2009-2022 Kurt McKee +# SPDX-License-Identifier: MIT +# + +import copy + +from . import common + + +# Attribute key constants +RDF_ABOUT = '{http://www.w3.org/1999/02/22-rdf-syntax-ns#}about' +RDF_RESOURCE = '{http://www.w3.org/1999/02/22-rdf-syntax-ns#}resource' + + +class FoafMixin(common.CommonMixin): + def start_rdf_RDF(self, _): + self.harvest['version'] = 'rdf' + + def start_rss_channel(self, attrs): + if attrs.get(RDF_ABOUT, '').strip(): + # We now have a feed URL, so forget about any opportunity URL. + if self.flag_opportunity: + self.flag_opportunity = False + self.agent_opps.pop() + agent_feed = attrs[RDF_ABOUT].strip() + self.agent_feeds.append(agent_feed) + + def start_ya_feed(self, attrs): + if attrs.get(RDF_RESOURCE, '').strip(): + # This is a feed URL + agent_feed = attrs[RDF_RESOURCE].strip() + self.agent_feeds.append(agent_feed) + + def _clean_found_objs(self): + if self.foaf_name: + title = self.foaf_name[-1] + else: + title = '' + for url in self.agent_feeds: + obj = common.SuperDict({'url': url, 'title': title}) + self.group_objs.append(('feeds', obj)) + for url in self.agent_lists: + obj = common.SuperDict({'url': url, 'title': title}) + self.group_objs.append(('lists', obj)) + for url in self.agent_opps: + obj = common.SuperDict({'url': url, 'title': title}) + self.group_objs.append(('opportunities', obj)) + + def start_foaf_Agent(self, _): + self.flag_agent = True + self.flag_feed = True + self.flag_new_title = True + + def end_foaf_Agent(self): + if self.flag_agent: + self.flag_agent = False + self._clean_found_objs() + if self.foaf_name: + self.foaf_name.pop() + self.agent_feeds = [] + self.agent_lists = [] + self.agent_opps = [] + self.flag_agent = False + self.flag_feed = False + self.flag_opportunity = False + + def start_foaf_Person(self, _): + self.flag_feed = True + self.flag_new_title = True + self._clean_found_objs() + end_foaf_Person = end_foaf_Agent + + def start_rdfs_seeAlso(self, attrs): + if attrs.get(RDF_RESOURCE, '').strip(): + # This is a subscription list URL + agent_list = attrs[RDF_RESOURCE].strip() + self.agent_lists.append(agent_list) + + def start_foaf_Group(self, _): + self.flag_group = True + + def end_foaf_Group(self): + self.flag_group = False + for key, obj in self.group_objs: + # Check for duplicates + if obj['url'] in self.found_urls: + obj = self.found_urls[obj['url']][1] + else: + self.found_urls[obj['url']] = (key, obj) + self.harvest[key].append(obj) + # Create or consolidate categories and tags + obj.setdefault('categories', []) + obj.setdefault('tags', []) + if self.hierarchy and self.hierarchy not in obj['categories']: + obj['categories'].append(copy.copy(self.hierarchy)) + if ( + len(self.hierarchy) == 1 + and self.hierarchy[0] not in obj['tags'] + ): + obj['tags'].extend(copy.copy(self.hierarchy)) + self.group_objs = [] + # Maintain the hierarchy + if self.hierarchy: + self.hierarchy.pop() + end_rdf_RDF = end_foaf_Group + + start_foaf_name = common.CommonMixin.expect_text + + def end_foaf_name(self): + value = self.get_text() + if self.flag_feed and self.flag_new_title: + self.foaf_name.append(value) + self.flag_new_title = False + elif self.flag_group and value: + self.hierarchy.append(value) + self.flag_group = False + + start_foaf_member_name = common.CommonMixin.expect_text + end_foaf_member_name = end_foaf_name + + def start_foaf_Document(self, attrs): + if attrs.get(RDF_ABOUT, '').strip(): + # Flag this as an opportunity (but ignore if a feed URL is found). + self.flag_opportunity = True + agent_opp = attrs[RDF_ABOUT].strip() + self.agent_opps.append(agent_opp) diff --git a/src/listparser/igoogle.py b/src/listparser/igoogle.py new file mode 100644 index 0000000..0ada11d --- /dev/null +++ b/src/listparser/igoogle.py @@ -0,0 +1,38 @@ +# This file is part of listparser. +# Copyright 2009-2022 Kurt McKee +# SPDX-License-Identifier: MIT +# + +import copy + +from . import common + + +class IgoogleMixin(common.CommonMixin): + def start_gtml_GadgetTabML(self, _): + self.harvest['version'] = 'igoogle' + + def start_gtml_Tab(self, attrs): + if attrs.get('title', '').strip(): + self.hierarchy.append(attrs['title'].strip()) + + def end_gtml_Tab(self): + if self.hierarchy: + self.hierarchy.pop() + + def start_iGoogle_Module(self, attrs): + if attrs.get('type', '').strip().lower() == 'rss': + self.flag_feed = True + + def end_iGoogle_Module(self): + self.flag_feed = False + + def start_iGoogle_ModulePrefs(self, attrs): + if self.flag_feed and attrs.get('xmlUrl', '').strip(): + obj = common.SuperDict({'url': attrs['xmlUrl'].strip()}) + obj['title'] = '' + if self.hierarchy: + obj['categories'] = [copy.copy(self.hierarchy)] + if len(self.hierarchy) == 1: + obj['tags'] = copy.copy(self.hierarchy) + self.harvest['feeds'].append(obj) diff --git a/src/listparser/opml.py b/src/listparser/opml.py new file mode 100644 index 0000000..c912738 --- /dev/null +++ b/src/listparser/opml.py @@ -0,0 +1,140 @@ +# This file is part of listparser. +# Copyright 2009-2022 Kurt McKee +# SPDX-License-Identifier: MIT +# + +import copy + +from . import common +from . import dates + + +class OpmlMixin(common.CommonMixin): + def start_opml_opml(self, attrs): + self.harvest['version'] = 'opml' + if attrs.get('version') in ('1.0', '1.1'): + self.harvest['version'] = 'opml1' + elif attrs.get('version') == '2.0': + self.harvest['version'] = 'opml2' + + def start_opml_outline(self, attrs): + url = None + # Find an appropriate title in @text or @title (else empty) + if attrs.get('text', '').strip(): + title = attrs['text'].strip() + else: + title = attrs.get('title', '').strip() + + # Search for the URL regardless of xmlUrl's case + for k, v in attrs.items(): + if k.lower() == 'xmlurl': + url = v.strip() + break + + append_to = None + + # Determine whether the outline is a feed or subscription list + if url is not None: + # It's a feed + append_to = 'feeds' + if attrs.get('type', '').strip().lower() == 'source': + # Actually, it's a subscription list! + append_to = 'lists' + elif attrs.get('type', '').lower() in ('link', 'include'): + # It's a subscription list + append_to = 'lists' + url = attrs.get('url', '').strip() + elif title: + # Assume that this is a grouping node + self.hierarchy.append(title) + return + # Look for an opportunity URL + if not url and 'htmlurl' in (k.lower() for k in attrs.keys()): + for k, v in attrs.items(): + if k.lower() == 'htmlurl': + url = v.strip() + append_to = 'opportunities' + if not url: + # Maintain the hierarchy + self.hierarchy.append('') + return + if url not in self.found_urls and append_to: + # This is a brand new URL + obj = common.SuperDict({'url': url, 'title': title}) + self.found_urls[url] = (append_to, obj) + self.harvest[append_to].append(obj) + else: + obj = self.found_urls[url][1] + + # Handle categories and tags + obj.setdefault('categories', []) + if 'category' in attrs.keys(): + for i in attrs['category'].split(','): + tmp = [j.strip() for j in i.split('/') if j.strip()] + if tmp and tmp not in obj['categories']: + obj['categories'].append(tmp) + # Copy the current hierarchy into `categories` + if self.hierarchy and self.hierarchy not in obj['categories']: + obj['categories'].append(copy.copy(self.hierarchy)) + # Copy all single-element `categories` into `tags` + obj['tags'] = [i[0] for i in obj['categories'] if len(i) == 1] + + self.hierarchy.append('') + + def end_opml_outline(self): + self.hierarchy.pop() + + start_opml_title = common.CommonMixin.expect_text + + def end_opml_title(self): + value = self.get_text() + if value: + self.harvest['meta']['title'] = value + + start_opml_ownerId = common.CommonMixin.expect_text + + def end_opml_ownerId(self): + value = self.get_text() + if value: + self.harvest['meta'].setdefault('author', common.SuperDict()) + self.harvest['meta']['author']['url'] = value + + start_opml_ownerEmail = common.CommonMixin.expect_text + + def end_opml_ownerEmail(self): + value = self.get_text() + if value: + self.harvest['meta'].setdefault('author', common.SuperDict()) + self.harvest['meta']['author']['email'] = value + + start_opml_ownerName = common.CommonMixin.expect_text + + def end_opml_ownerName(self): + value = self.get_text() + if value: + self.harvest['meta'].setdefault('author', common.SuperDict()) + self.harvest['meta']['author']['name'] = value + + start_opml_dateCreated = common.CommonMixin.expect_text + + def end_opml_dateCreated(self): + value = self.get_text() + if value: + self.harvest['meta']['created'] = value + timestamp = dates.parse_rfc822(value) + if timestamp: + self.harvest['meta']['created_parsed'] = timestamp + else: + self.raise_bozo('dateCreated is not an RFC 822 datetime') + + start_opml_dateModified = common.CommonMixin.expect_text + + def end_opml_dateModified(self): + value = self.get_text() + if value: + self.harvest['meta']['modified'] = value + timestamp = dates.parse_rfc822(value) + if timestamp: + self.harvest['meta']['modified_parsed'] = timestamp + else: + self.raise_bozo('dateModified is not an RFC 822 datetime') diff --git a/src/listparser/parsers.py b/src/listparser/parsers.py new file mode 100644 index 0000000..535c1fb --- /dev/null +++ b/src/listparser/parsers.py @@ -0,0 +1,145 @@ +# This file is part of listparser. +# Copyright 2009-2022 Kurt McKee +# SPDX-License-Identifier: MIT +# + +from typing import Dict, Tuple +import xml.sax + +try: + import lxml.etree +except ImportError: + lxml = None + +from . import common +from . import foaf +from . import igoogle +from . import opml + + +class LxmlHandler(foaf.FoafMixin, igoogle.IgoogleMixin, opml.OpmlMixin): + def start(self, name: str, attrs: Dict): + """Handle the start of an XML element.""" + + try: + method = self.start_methods[name] + except KeyError: + namespace, _, tag = name.rpartition('}') + namespace = namespace[1:] + try: + function = f'start_{common.namespaces[namespace]}_{tag}' + except KeyError: + function = f'start_opml_{tag}' + self.start_methods[name] = method = getattr(self, function, None) + + if method: + method(attrs) + + def end(self, name: str): + """Handle the end of an XML element.""" + + try: + method = self.end_methods[name] + except KeyError: + namespace, _, tag = name.rpartition('}') + namespace = namespace[1:] + try: + function = f'end_{common.namespaces[namespace]}_{tag}' + except KeyError: + function = f'end_opml_{tag}' + self.end_methods[name] = method = getattr(self, function, None) + + if method: + method() + + def data(self, data: str): + """Handle text content of an element.""" + + if self.flag_expect_text: + self.text.append(data) + + def close(self): + pass + + +class XmlSaxHandler( + foaf.FoafMixin, + igoogle.IgoogleMixin, + opml.OpmlMixin, + xml.sax.handler.ContentHandler, + xml.sax.handler.ErrorHandler, +): + def __init__(self): + super().__init__() + xml.sax.handler.ContentHandler.__init__(self) + xml.sax.handler.ErrorHandler.__init__(self) + + # ErrorHandler methods + # -------------------- + + def warning(self, exception): + self.raise_bozo(exception) + + error = warning + fatalError = warning + + # ContentHandler methods + # ---------------------- + + def startElementNS(self, name: Tuple[str, str], qname: str, attrs): + """Handle the start of an XML element. + + Attribute keys will be converted from tuples of strings + to strings to match the format that lxml uses. + """ + + try: + method = self.start_methods[name] + except KeyError: + fn = '' + if name[0] in common.namespaces: + fn = f'start_{common.namespaces[name[0]]}_{name[1]}' + elif name[0] is None: + fn = f'start_opml_{name[1]}' + self.start_methods[name] = method = getattr(self, fn, None) + + if not method: + return + + # Convert the keys in *attrs* from tuples to strings: + # + # {(uri, localname): value} + # {"{uri}localname": value} + # + attributes = {} + for (uri, localname), value in attrs.items(): + if uri: + attributes[f'{{{uri}}}{localname}'] = value + else: + attributes[localname] = value + + method(attributes) + + def endElementNS(self, name: Tuple[str, str], qname: str): + try: + method = self.end_methods[name] + except KeyError: + fn = '' + if name[0] in common.namespaces: + fn = f'end_{common.namespaces[name[0]]}_{name[1]}' + elif name[0] is None: + fn = f'end_opml_{name[1]}' + self.end_methods[name] = method = getattr(self, fn, None) + + if method: + method() + + def characters(self, content): + if self.flag_expect_text: + self.text.append(content) + + +if lxml: + Handler = LxmlHandler +else: + Handler = XmlSaxHandler diff --git a/tests/1x1.gif b/tests/1x1.gif deleted file mode 100644 index 1d11fa9..0000000 Binary files a/tests/1x1.gif and /dev/null differ diff --git a/tests/bad_bytes-00ff.xml b/tests/bad_bytes-00ff.xml deleted file mode 100644 index f93220e..0000000 Binary files a/tests/bad_bytes-00ff.xml and /dev/null differ diff --git a/tests/filename.xml b/tests/filename.xml deleted file mode 100644 index 97e4f42..0000000 --- a/tests/filename.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - filename - diff --git a/tests/http/destination.xml b/tests/http/destination.xml deleted file mode 100644 index 8ffeaea..0000000 --- a/tests/http/destination.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - Redirection destination - - - - - diff --git a/tests/http/http-bad_last_modified.xml b/tests/http/http-bad_last_modified.xml deleted file mode 100644 index 6efa7f9..0000000 --- a/tests/http/http-bad_last_modified.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - diff --git a/tests/http/http-bad_status.xml b/tests/http/http-bad_status.xml deleted file mode 100644 index 5c1b0db..0000000 --- a/tests/http/http-bad_status.xml +++ /dev/null @@ -1,5 +0,0 @@ - diff --git a/tests/http/http_301.xml b/tests/http/http_301.xml deleted file mode 100644 index 0952af3..0000000 --- a/tests/http/http_301.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - diff --git a/tests/http/http_302.xml b/tests/http/http_302.xml deleted file mode 100644 index 1ee5449..0000000 --- a/tests/http/http_302.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - diff --git a/tests/http/http_303.xml b/tests/http/http_303.xml deleted file mode 100644 index ac27cc1..0000000 --- a/tests/http/http_303.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - diff --git a/tests/http/http_304-etag.xml b/tests/http/http_304-etag.xml deleted file mode 100644 index cf12abe..0000000 --- a/tests/http/http_304-etag.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - diff --git a/tests/http/http_304-last_modified.xml b/tests/http/http_304-last_modified.xml deleted file mode 100644 index cc1613c..0000000 --- a/tests/http/http_304-last_modified.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - diff --git a/tests/http/http_307.xml b/tests/http/http_307.xml deleted file mode 100644 index 00690f8..0000000 --- a/tests/http/http_307.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - diff --git a/tests/http/http_404.xml b/tests/http/http_404.xml deleted file mode 100644 index 0e6f512..0000000 --- a/tests/http/http_404.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - Found despite an HTTP 404 - - - - - diff --git a/tests/http/http_etag.xml b/tests/http/http_etag.xml deleted file mode 100644 index c4ef3e8..0000000 --- a/tests/http/http_etag.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - diff --git a/tests/http/http_last_modified.xml b/tests/http/http_last_modified.xml deleted file mode 100644 index 0c45233..0000000 --- a/tests/http/http_last_modified.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - diff --git a/tests/http/useragent.xml b/tests/http/useragent.xml deleted file mode 100644 index 85868c8..0000000 --- a/tests/http/useragent.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - Test customized User-Agent - - - - - diff --git a/tests/igoogle/GadgetTabML.xml b/tests/igoogle/GadgetTabML.xml index c819f7e..6e269c3 100644 --- a/tests/igoogle/GadgetTabML.xml +++ b/tests/igoogle/GadgetTabML.xml @@ -1,8 +1,8 @@ diff --git a/tests/igoogle/ModulePrefs_xmlUrl-wrong_type.xml b/tests/igoogle/ModulePrefs_xmlUrl-wrong_type.xml index 81a5f82..9228dc5 100644 --- a/tests/igoogle/ModulePrefs_xmlUrl-wrong_type.xml +++ b/tests/igoogle/ModulePrefs_xmlUrl-wrong_type.xml @@ -1,8 +1,8 @@ diff --git a/tests/igoogle/ModulePrefs_xmlUrl.xml b/tests/igoogle/ModulePrefs_xmlUrl.xml index e58a808..c0b6ac2 100644 --- a/tests/igoogle/ModulePrefs_xmlUrl.xml +++ b/tests/igoogle/ModulePrefs_xmlUrl.xml @@ -1,8 +1,8 @@ diff --git a/tests/igoogle/hierarchy-bad.xml b/tests/igoogle/hierarchy-bad.xml index c690e0b..65bdef5 100644 --- a/tests/igoogle/hierarchy-bad.xml +++ b/tests/igoogle/hierarchy-bad.xml @@ -1,9 +1,9 @@ diff --git a/tests/igoogle/hierarchy.xml b/tests/igoogle/hierarchy.xml index df43403..824b575 100644 --- a/tests/igoogle/hierarchy.xml +++ b/tests/igoogle/hierarchy.xml @@ -1,9 +1,9 @@ diff --git a/tests/injection/attribute-node.xml b/tests/injection/attribute-node.xml deleted file mode 100644 index 76d0e02..0000000 --- a/tests/injection/attribute-node.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - diff --git a/tests/injection/still-undefined.xml b/tests/injection/still-undefined.xml deleted file mode 100644 index 7dce69d..0000000 --- a/tests/injection/still-undefined.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - arch&egregiouslyundefined;ology - - - - - diff --git a/tests/injection/text-node-1.xml b/tests/injection/text-node-1.xml deleted file mode 100644 index f5b85e4..0000000 --- a/tests/injection/text-node-1.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - archæology - archæology - - - - - diff --git a/tests/injection/text-node-2.xml b/tests/injection/text-node-2.xml deleted file mode 100644 index 386318d..0000000 --- a/tests/injection/text-node-2.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - 1 μs is brief - 1 μs is brief - - - - - diff --git a/tests/malformed.xml b/tests/malformed.xml new file mode 100644 index 0000000..d377fb5 --- /dev/null +++ b/tests/malformed.xml @@ -0,0 +1,11 @@ + + + + + + + diff --git a/tests/opml/categories/cats-3-multiple.xml b/tests/opml/categories/cats-3-multiple.xml index e4e1dac..6b13ef4 100644 --- a/tests/opml/categories/cats-3-multiple.xml +++ b/tests/opml/categories/cats-3-multiple.xml @@ -1,11 +1,11 @@ diff --git a/tests/opml/categories/cats-4-bad.xml b/tests/opml/categories/cats-4-bad.xml index 046069c..4d694bc 100644 --- a/tests/opml/categories/cats-4-bad.xml +++ b/tests/opml/categories/cats-4-bad.xml @@ -2,12 +2,12 @@ diff --git a/tests/opml/categories/hier-2-nested.xml b/tests/opml/categories/hier-2-nested.xml index 0fd0e85..4a53ed4 100644 --- a/tests/opml/categories/hier-2-nested.xml +++ b/tests/opml/categories/hier-2-nested.xml @@ -2,9 +2,9 @@ diff --git a/tests/opml/categories/hier-3-whitespace.xml b/tests/opml/categories/hier-3-whitespace.xml index 189bd8c..0c0ae2e 100644 --- a/tests/opml/categories/hier-3-whitespace.xml +++ b/tests/opml/categories/hier-3-whitespace.xml @@ -2,8 +2,8 @@ diff --git a/tests/opml/categories/tags-1-single.xml b/tests/opml/categories/tags-1-single.xml index 52eadc2..1656626 100644 --- a/tests/opml/categories/tags-1-single.xml +++ b/tests/opml/categories/tags-1-single.xml @@ -2,10 +2,10 @@ diff --git a/tests/opml/categories/tags-2-multiple.xml b/tests/opml/categories/tags-2-multiple.xml index 74e59ff..ac6a239 100644 --- a/tests/opml/categories/tags-2-multiple.xml +++ b/tests/opml/categories/tags-2-multiple.xml @@ -2,12 +2,12 @@ diff --git a/tests/opml/categories/tags-3-cats_mixed.xml b/tests/opml/categories/tags-3-cats_mixed.xml index 06d7529..dd3a07b 100644 --- a/tests/opml/categories/tags-3-cats_mixed.xml +++ b/tests/opml/categories/tags-3-cats_mixed.xml @@ -2,11 +2,11 @@ diff --git a/tests/opml/categories/tags-4-bad.xml b/tests/opml/categories/tags-4-bad.xml index 3303737..64d2fbe 100644 --- a/tests/opml/categories/tags-4-bad.xml +++ b/tests/opml/categories/tags-4-bad.xml @@ -2,12 +2,12 @@ diff --git a/tests/opml/head-empty_tags.xml b/tests/opml/head-empty_tags.xml index 77c2e7e..195c96d 100644 --- a/tests/opml/head-empty_tags.xml +++ b/tests/opml/head-empty_tags.xml @@ -1,11 +1,11 @@ diff --git a/tests/opml/opportunities/opml-htmlUrl-empty.xml b/tests/opml/opportunities/opml-htmlUrl-empty.xml index 5717286..94bce18 100644 --- a/tests/opml/opportunities/opml-htmlUrl-empty.xml +++ b/tests/opml/opportunities/opml-htmlUrl-empty.xml @@ -1,8 +1,8 @@ diff --git a/tests/opml/opportunities/opml-htmlUrl-miscapitalized.xml b/tests/opml/opportunities/opml-htmlUrl-miscapitalized.xml index 351cb70..648e0ea 100644 --- a/tests/opml/opportunities/opml-htmlUrl-miscapitalized.xml +++ b/tests/opml/opportunities/opml-htmlUrl-miscapitalized.xml @@ -1,10 +1,10 @@ diff --git a/tests/opml/opportunities/opml-htmlUrl-valid_feed.xml b/tests/opml/opportunities/opml-htmlUrl-valid_feed.xml index 267afcd..90f63e7 100644 --- a/tests/opml/opportunities/opml-htmlUrl-valid_feed.xml +++ b/tests/opml/opportunities/opml-htmlUrl-valid_feed.xml @@ -1,8 +1,8 @@ diff --git a/tests/opml/opportunities/opml-htmlUrl.xml b/tests/opml/opportunities/opml-htmlUrl.xml index f492841..4af97f1 100644 --- a/tests/opml/opportunities/opml-htmlUrl.xml +++ b/tests/opml/opportunities/opml-htmlUrl.xml @@ -1,10 +1,10 @@ diff --git a/tests/opml/opportunities/opml-htmlUrl_alone.xml b/tests/opml/opportunities/opml-htmlUrl_alone.xml index 4a81417..5fe7ec0 100644 --- a/tests/opml/opportunities/opml-htmlUrl_alone.xml +++ b/tests/opml/opportunities/opml-htmlUrl_alone.xml @@ -1,9 +1,9 @@ diff --git a/tests/opml/outline-duplication-1.xml b/tests/opml/outline-duplication-1.xml index d5cb3d6..e7a237b 100644 --- a/tests/opml/outline-duplication-1.xml +++ b/tests/opml/outline-duplication-1.xml @@ -1,8 +1,8 @@ diff --git a/tests/opml/outline-duplication-2.xml b/tests/opml/outline-duplication-2.xml index d5711a2..17f4465 100644 --- a/tests/opml/outline-duplication-2.xml +++ b/tests/opml/outline-duplication-2.xml @@ -1,12 +1,12 @@ diff --git a/tests/opml/outline_type-source.xml b/tests/opml/outline_type-source.xml index e2168dd..dc51b4a 100644 --- a/tests/opml/outline_type-source.xml +++ b/tests/opml/outline_type-source.xml @@ -5,9 +5,9 @@ useful for differentiation between feeds and subscription lists. Description: //outline[type="source"] indicates a subscription list - Eval: result.bozo == 0 - Eval: len(result.feeds) == 0 - Eval: result.lists[0].url == "http://localhost/list" + Eval: result['bozo'] == 0 + Eval: len(result['feeds']) == 0 + Eval: result['lists'][0]['url'] == "http://localhost/list" --> diff --git a/tests/rdf/foaf_agent-multiple_weblogs.xml b/tests/rdf/foaf_agent-multiple_weblogs.xml index 0c90682..e1ab61d 100644 --- a/tests/rdf/foaf_agent-multiple_weblogs.xml +++ b/tests/rdf/foaf_agent-multiple_weblogs.xml @@ -1,14 +1,14 @@ diff --git a/tests/rdf/yandex/ya_blogActivity-ensure_name.xml b/tests/rdf/yandex/ya_blogActivity-ensure_name.xml index 577b743..bb341e7 100644 --- a/tests/rdf/yandex/ya_blogActivity-ensure_name.xml +++ b/tests/rdf/yandex/ya_blogActivity-ensure_name.xml @@ -1,13 +1,13 @@ + + + + + + + + + + + + diff --git a/tests/test_dates.py b/tests/test_dates.py new file mode 100644 index 0000000..34c9d02 --- /dev/null +++ b/tests/test_dates.py @@ -0,0 +1,122 @@ +# This file is part of listparser. +# Copyright 2009-2022 Kurt McKee +# SPDX-License-Identifier: MIT +# + +import datetime + +import pytest + +import listparser.dates + + +@pytest.mark.parametrize('date, expected_values', [ + ('Sun, 14 Jun 2009 11:47:32 GMT', (2009, 6, 14, 11, 47, 32)), + ('Sun, Dec 16 2012 11:15:01 GMT', (2012, 12, 16, 11, 15, 1)), + ('Sun, Dec 16 2012', (2012, 12, 16, 0, 0, 0)), + ('Thu, 5 Apr 2012 10:00:00 GMT', (2012, 4, 5, 10, 0, 0)), + ('Sun, 21 Jun 2009 12:00 GMT', (2009, 6, 21, 12, 0, 0)), +]) +def test_format_variations(date, expected_values): + keys = ('year', 'month', 'day', 'hour', 'minute', 'second') + result = listparser.dates.parse_rfc822(date) + for key, expected_value in zip(keys, expected_values): + assert getattr(result, key) == expected_value + assert result.tzinfo == datetime.timezone(datetime.timedelta(0)) + + +@pytest.mark.parametrize('date, expected_year', [ + ('Wed, 21 Jun 00 12:00:00 GMT', 2000), + ('Wed, 21 Jun 89 12:00:00 GMT', 2089), + ('Thu, 21 Jun 90 12:00:00 GMT', 1990), + ('Mon, 21 Jun 99 12:00:00 GMT', 1999), +]) +def test_two_digit_years(date, expected_year): + assert listparser.dates.parse_rfc822(date).year == expected_year + + +@pytest.mark.parametrize('date, expected_month', [ + ('21 Jan 2009 12:00:00 GMT', 1), + ('21 Feb 2009 12:00:00 GMT', 2), + ('21 Mar 2009 12:00:00 GMT', 3), + ('21 Apr 2009 12:00:00 GMT', 4), + ('21 May 2009 12:00:00 GMT', 5), + ('21 Jun 2009 12:00:00 GMT', 6), + ('21 Jul 2009 12:00:00 GMT', 7), + ('21 Aug 2009 12:00:00 GMT', 8), + ('21 Sep 2009 12:00:00 GMT', 9), + ('21 Oct 2009 12:00:00 GMT', 10), + ('21 Nov 2009 12:00:00 GMT', 11), + ('21 Dec 2009 12:00:00 GMT', 12), +]) +def test_month_names(date, expected_month): + assert listparser.dates.parse_rfc822(date).month == expected_month + + +@pytest.mark.parametrize('date, hour, minute, offset', [ + # Universal timezones + ('Mon, 22 Jun 2009 13:15:17 UT', 13, 15, 0), + ('Mon, 22 Jun 2009 13:15:17 GMT', 13, 15, 0), + + # North American timezones + ('Mon, 22 Jun 2009 13:15:17 EST', 13, 15, -5 * 60), + ('Mon, 22 Jun 2009 13:15:17 EDT', 13, 15, -4 * 60), + ('Mon, 22 Jun 2009 13:15:17 CST', 13, 15, -6 * 60), + ('Mon, 22 Jun 2009 13:15:17 CDT', 13, 15, -5 * 60), + ('Mon, 22 Jun 2009 13:15:17 MST', 13, 15, -7 * 60), + ('Mon, 22 Jun 2009 13:15:17 MDT', 13, 15, -6 * 60), + ('Mon, 22 Jun 2009 13:15:17 PST', 13, 15, -8 * 60), + ('Mon, 22 Jun 2009 13:15:17 PDT', 13, 15, -7 * 60), + + # Military timezones + ('Mon, 22 Jun 2009 13:15:17 Z', 13, 15, 0), + ('Mon, 22 Jun 2009 13:15:17 A', 13, 15, -1 * 60), + ('Mon, 22 Jun 2009 13:15:17 N', 13, 15, +1 * 60), + ('Mon, 22 Jun 2009 13:15:17 M', 13, 15, -12 * 60), + ('Mon, 22 Jun 2009 13:15:17 Y', 13, 15, +12 * 60), + + # Numeric timezones + ('Mon, 22 Jun 2009 13:15:17 -0430', 13, 15, (-4 * 60) - 30), + ('Mon, 22 Jun 2009 13:15:17 +0545', 13, 15, (5 * 60) + 45), + ('Mon, 22 Jun 2009 13:15:17 0545', 13, 15, (5 * 60) + 45), + + # Non-standard timezones + ('Mon, 22 Jun 2009 13:15:17 UTC', 13, 15, 0), + ('Mon, 22 Jun 2009 13:15:17 Etc/GMT', 13, 15, 0), + ('Mon, 22 Jun 2009 13:15:17 Etc/', 13, 15, 0), +]) +def test_timezones(date, hour, minute, offset): + result = listparser.dates.parse_rfc822(date) + assert result.hour == hour + assert result.minute == minute + tz_info = datetime.timezone(datetime.timedelta(minutes=offset)) + assert result.tzinfo == tz_info + + +@pytest.mark.parametrize('date', [ + 'Sun, 99 Jun 2009 12:00:00 GMT', # range day high + 'Sun, 00 Jun 2009 12:00:00 GMT', # range day low + 'Sun, 01 Jun 2009 99:00:00 GMT', # range hour + 'Sun, 01 Jun 2009 00:99:00 GMT', # range minute + 'Sun, 01 Jun 2009 00:00:99 GMT', # range second + 'Sun, 31 Dec 9999 23:59:59 -9999', # range year high + 'Sun, 01 Jan 0000 00:00:00 +9999', # range year low + 'yesterday', # too few parts + 'Sun, 16 Dec 2012 1:2:3:4 GMT', # too many time parts + 'Sun, 16 zzz 2012 11:47:32 GMT', # bad month name + 'Sun, Dec xx 2012 11:47:32 GMT', # swapped bad day + 'Sun, zzz 16 2012 11:47:32 GMT', # swapped bad month + 'Sun, 16 Dec zz 11:47:32 GMT', # bad year + + # Corrupt timezones + 'Sun, 31 Dec 9999 23:59:59 -999999999999999999999', # timezone range + 'Sun, 16 Dec 2012 11:47:32 +$$:00', # bad timezone hour with colon + 'Sun, 16 Dec 2012 11:47:32 -00:$$', # bad timezone minute with colon + 'Sun, 16 Dec 2012 11:47:32 :', # bad timezone minute with only a colon + 'Sun, 16 Dec 2012 11:47:32 -00:00:00', # bad timezone with extra colons + 'Sun, 16 Dec 2012 11:47:32 +$$00', # bad timezone hour without colon + 'Sun, 16 Dec 2012 11:47:32 +00$$', # bad timezone minute without colon + 'Sun, 16 Dec 2012 11:47:32 $', # bad negative timezone minute +]) +def test_invalid_dates(date): + assert listparser.dates.parse_rfc822(date) is None diff --git a/tests/test_http.py b/tests/test_http.py new file mode 100644 index 0000000..0172350 --- /dev/null +++ b/tests/test_http.py @@ -0,0 +1,54 @@ +# This file is part of listparser. +# Copyright 2009-2022 Kurt McKee +# SPDX-License-Identifier: MIT +# + +import unittest.mock + +import pytest + +import listparser + +try: + import requests +except ImportError: + requests = None + + +empty_doc = '' + + +@pytest.fixture +def http(): + def get(url, *args, **kwargs): + if url == 'http://': + raise requests.exceptions.InvalidURL('no host supplied') + else: + mock = unittest.mock.Mock() + mock.text = empty_doc + return mock + + with unittest.mock.patch('listparser.requests.get', get): + yield + + +@pytest.mark.skipif(requests is None, reason='requests must be installed') +def test_requests_success(http): + content, info = listparser.get_content('http://example') + assert content + assert not info['bozo'] + + +@pytest.mark.skipif(requests is None, reason='requests must be installed') +def test_requests_error(http): + content, info = listparser.get_content('http://') + assert not content + assert info['bozo'] + + +@pytest.mark.skipif(requests, reason='requests must NOT be installed') +def test_requests_not_present(): + content, info = listparser.get_content('http://example') + assert not content + assert info['bozo'] + assert isinstance(info['bozo_exception'], listparser.ListparserError) diff --git a/tests/test_super_dict.py b/tests/test_super_dict.py new file mode 100644 index 0000000..a10fee6 --- /dev/null +++ b/tests/test_super_dict.py @@ -0,0 +1,19 @@ +# This file is part of listparser. +# Copyright 2009-2022 Kurt McKee +# SPDX-License-Identifier: MIT +# + +import pytest + +from listparser.common import SuperDict + + +def test_attr_get(): + sample = SuperDict() + dict.__setitem__(sample, 'a', 1) + assert sample.a == 1 + + +def test_attr_get_error(): + with pytest.raises(AttributeError): + assert SuperDict().bogus diff --git a/tests/test_xml.py b/tests/test_xml.py new file mode 100644 index 0000000..0ffefd3 --- /dev/null +++ b/tests/test_xml.py @@ -0,0 +1,82 @@ +# This file is part of listparser. +# Copyright 2009-2022 Kurt McKee +# SPDX-License-Identifier: MIT +# + +import datetime # noqa: F401 (required by evals) +import pathlib +import unittest.mock + +import pytest + +import listparser + + +tests_path = pathlib.Path(__file__).parent + + +@pytest.fixture(scope='module') +def use_dict(): + with unittest.mock.patch('listparser.common.SuperDict', dict): + yield + + +def test_return_guarantees(use_dict): + result = listparser.parse(0) + assert result['bozo'] + + +empty_doc = '' + + +@pytest.mark.parametrize('src', [ + empty_doc, # str + empty_doc.encode('utf8'), # bytes +]) +def test_get_content_good(use_dict, src): + content, info = listparser.get_content(src) + assert content is not None + assert not info['bozo'] + + +def test_get_content_bad(use_dict): + content, info = listparser.get_content(123) + assert content is None + assert info['bozo'] + + +tests = [] +for _file in tests_path.rglob('**/*.xml'): + _info = {} + _assertions = [] + blob = _file.read_text('utf8', errors='replace') + for _line in blob.splitlines(): # pragma: no branch + if '-->' in _line: + break + if _line.lstrip().startswith('Eval:'): + _assertions.append(_line.partition(':')[2].strip()) + elif ': ' in _line: + _key, _, _value = _line.strip().partition(': ') + _info[_key] = _value + description = _info.get('Description', '') + + if not description: # pragma: no cover + message = 'Description not found in test {}'.format(_file) + raise ValueError(message) + if not _assertions: # pragma: no cover + message = 'Eval not found in test {}'.format(_file) + raise ValueError(message) + + tests.append(pytest.param( + blob, _assertions, + id=str(_file.relative_to(tests_path)), + )) + + +@pytest.mark.parametrize('src, assertions', tests) +def test_file(use_dict, src, assertions): + # `result` must exist in the local scope for the assertions to run. + result = listparser.parse(src) # noqa: F841 + lxml = listparser.parsers.lxml # noqa: F841 + for assertion in assertions: + assert eval(assertion) diff --git a/tests/unknown-namespace.xml b/tests/unknown-namespace.xml index feb7ba9..e0eaa1e 100644 --- a/tests/unknown-namespace.xml +++ b/tests/unknown-namespace.xml @@ -1,7 +1,7 @@