pax_global_header00006660000000000000000000000064125155420120014507gustar00rootroot0000000000000052 comment=2110e5f9e83b04ded238918e0ef6b44d103897f6 listparser-0.18/000077500000000000000000000000001251554201200136275ustar00rootroot00000000000000listparser-0.18/.gitignore000066400000000000000000000000561251554201200156200ustar00rootroot00000000000000*.pyc MANIFEST dist build listparser$py.class listparser-0.18/COPYING000066400000000000000000001045131251554201200146660ustar00rootroot00000000000000 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 . listparser-0.18/COPYING.LESSER000066400000000000000000000167431251554201200156710ustar00rootroot00000000000000 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. listparser-0.18/MANIFEST.in000066400000000000000000000002551251554201200153670ustar00rootroot00000000000000include COPYING include COPYING.LESSER include NEWS include README include lptest.py include project.opml recursive-include docs *.rst conf.py recursive-include tests *.xml listparser-0.18/NEWS000066400000000000000000000100351251554201200143250ustar00rootroot00000000000000v0.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 listparser-0.18/README.rst000066400000000000000000000030471251554201200153220ustar00rootroot00000000000000What is 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. 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') 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 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' More extensive documentation is available in the docs/ directory, or online at . Bugs ==== There are going to be bugs. The best way to handle them will be to isolate the simplest possible document that susses out the bug, add 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 . listparser-0.18/docs/000077500000000000000000000000001251554201200145575ustar00rootroot00000000000000listparser-0.18/docs/conf.py000066400000000000000000000136751251554201200160720ustar00rootroot00000000000000# -*- 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 sys, os # 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'] # 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' # 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 = [] # 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 listparser-0.18/docs/detection-algorithm.rst000066400000000000000000000034521251554201200212570ustar00rootroot00000000000000Feed 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. 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. 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. listparser-0.18/docs/getting-started.rst000066400000000000000000000046061251554201200204240ustar00rootroot00000000000000Getting 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`. :: >>> import listparser >>> result = listparser.parse('http://github.com/kurtmckee/listparser/raw/master/project.opml') :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 ``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:: >>> result.meta.title u'listparser project feeds' >>> result.meta.author.keys() ['url', 'name', 'email'] The ``feeds`` key ----------------- The ``feeds`` key is a list of dictionaries. The title and the URL are stored in keys of the same names:: >>> for i in result.feeds: ... print "%s <%s>" % (i.title, i.url) ... listparser blog listparser releases 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. 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. 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:: :doc:`reference/meta`, :doc:`reference/feeds`, :doc:`reference/lists`, :doc:`reference/opportunities` listparser-0.18/docs/http-features.rst000066400000000000000000000065211251554201200201100ustar00rootroot00000000000000HTTP Features ============= listparser supports several HTTP features, both to identify itself to webservers and to save bandwidth. User-Agent ---------- 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. To change the User-Agent for only one request, call :py:func:`~listparser.parse` with an ``agent`` argument:: >>> listparser.parse('http://localhost/list', agent='PowerfulSoftware/1.0') 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-0.18/docs/index.rst000066400000000000000000000017461251554201200164300ustar00rootroot00000000000000Welcome to listparser's documentation! ====================================== 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. 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: 2 getting-started http-features detection-algorithm reference/objects Reference --------- .. toctree:: :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 listparser-0.18/docs/reference/000077500000000000000000000000001251554201200165155ustar00rootroot00000000000000listparser-0.18/docs/reference/bozo.rst000066400000000000000000000004021251554201200202140ustar00rootroot00000000000000bozo ==== 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. .. seealso:: :doc:`bozo_exception` listparser-0.18/docs/reference/bozo_exception.rst000066400000000000000000000004651251554201200223030ustar00rootroot00000000000000bozo_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. .. seealso:: :doc:`bozo` listparser-0.18/docs/reference/etag.rst000066400000000000000000000005041251554201200201660ustar00rootroot00000000000000etag ==== 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 listparser-0.18/docs/reference/feeds.rst000066400000000000000000000004431251554201200203360ustar00rootroot00000000000000feeds ===== The ``feeds`` attribute contains a list of all of the feeds in the subscription list. .. seealso:: * :doc:`feeds[i].categories ` * :doc:`feeds[i].tags ` * :doc:`feeds[i].title ` * :doc:`feeds[i].url ` listparser-0.18/docs/reference/headers.rst000066400000000000000000000005731251554201200206670ustar00rootroot00000000000000headers ======= 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. listparser-0.18/docs/reference/href.rst000066400000000000000000000004651251554201200202000ustar00rootroot00000000000000href ==== 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` listparser-0.18/docs/reference/lists.rst000066400000000000000000000004671251554201200204140ustar00rootroot00000000000000lists ===== The ``lists`` attribute contains a list of all of the subscription lists in the parsed subscription list. .. seealso:: * :doc:`lists[i].categories ` * :doc:`lists[i].tags ` * :doc:`lists[i].title ` * :doc:`lists[i].url ` listparser-0.18/docs/reference/meta-author-email.rst000066400000000000000000000004571251554201200225700ustar00rootroot00000000000000meta.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. .. rubric:: Comes from * ``/opml/head/ownerEmail`` listparser-0.18/docs/reference/meta-author-name.rst000066400000000000000000000003741251554201200224170ustar00rootroot00000000000000meta.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. .. rubric:: Comes from * ``/opml/head/ownerName`` listparser-0.18/docs/reference/meta-author-url.rst000066400000000000000000000004321251554201200222740ustar00rootroot00000000000000meta.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. .. rubric:: Comes from * ``/opml/head/ownerId`` listparser-0.18/docs/reference/meta-created.rst000066400000000000000000000005351251554201200216050ustar00rootroot00000000000000meta.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. .. seealso:: :doc:`meta-created_parsed` .. rubric:: Comes from * ``/opml/head/dateCreated`` listparser-0.18/docs/reference/meta-created_parsed.rst000066400000000000000000000005341251554201200231420ustar00rootroot00000000000000meta.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. .. seealso:: :doc:`meta-created` .. rubric:: Comes from * ``/opml/head/dateCreated`` listparser-0.18/docs/reference/meta-modified.rst000066400000000000000000000011461251554201200217550ustar00rootroot00000000000000meta.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. .. seealso:: * :doc:`meta-modified_parsed` * :doc:`modified` .. rubric:: Comes from * ``/opml/head/dateModified`` listparser-0.18/docs/reference/meta-modified_parsed.rst000066400000000000000000000004431251554201200233120ustar00rootroot00000000000000meta.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. .. seealso:: :doc:`meta-modified` listparser-0.18/docs/reference/meta.rst000066400000000000000000000004001251554201200201670ustar00rootroot00000000000000meta ==== 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: :maxdepth: 1 meta-* listparser-0.18/docs/reference/modified.rst000066400000000000000000000010721251554201200210270ustar00rootroot00000000000000modified ======== 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 listparser-0.18/docs/reference/modified_parsed.rst000066400000000000000000000004301251554201200223620ustar00rootroot00000000000000modified_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` listparser-0.18/docs/reference/object-categories.rst000066400000000000000000000022401251554201200226360ustar00rootroot00000000000000objects[i].categories ===================== 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: .. highlight:: xml :: 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` .. rubric:: Comes from * ``/opml/body//outline/@category`` [#slashes]_ * ``/opml/body//outline/ancestor::outline/@text`` * ``/opml/body//outline/ancestor::outline/@title`` * ``/gtml:GadgetTabML//gtml:Tab/@title`` * ``/rdf:RDF/foaf:Group/foaf:name`` * ``/rdf:RDF//foaf:Agent/foaf:name`` .. rubric:: Footnotes .. [#slashes] The ``category`` attribute is a comma-separated string. listparser-0.18/docs/reference/object-tags.rst000066400000000000000000000015351251554201200214550ustar00rootroot00000000000000objects[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: .. highlight:: xml :: In this example, there is one tag: ``sports``. .. seealso:: :doc:`object-categories` .. rubric:: Comes from * ``/opml/body//outline/@category`` [#noslashes]_ * ``/opml/body/outline/outline/parent::outline/@text`` * ``/opml/body/outline/outline/parent::outline/@title`` * ``/gtml:GadgetTabML//gtml:Tab/@title`` * ``/rdf:RDF/foaf:Group/foaf:name`` * ``/rdf:RDF//foaf:Agent/foaf:name`` .. rubric:: Footnotes .. [#noslashes] The ``category`` attribute is a comma-separated string. listparser-0.18/docs/reference/object-title.rst000066400000000000000000000024371251554201200216420ustar00rootroot00000000000000objects[i].title ================ 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. 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: .. highlight:: xml :: And here is the title returned by listparser: .. highlight:: python :: >>> result.feeds[0].title u'Hal Tucker' .. rubric:: Comes from * ``/opml/body//outline/@text`` * ``/opml/body//outline/@title`` * ``/rdf:RDF//foaf:Agent/foaf:name`` * ``/rdf:RDF//foaf:Agent/foaf:member_name`` listparser-0.18/docs/reference/object-url.rst000066400000000000000000000015101251554201200213120ustar00rootroot00000000000000objects[i].url ============== 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. .. rubric:: Feed URLs come from * ``/opml/body//outline/@xmlUrl`` * ``/gtml:GadgetTabML//iGoogle:Module[@type="RSS"]/iGoogle:ModulePrefs/@xmlUrl`` * ``/rdf:RDF//foaf:Agent//rss:channel/@rdf:about`` * ``/rdf:RDF//ya:feed/@rdf:resource`` .. rubric:: Subscription list URLs come from * ``/opml/body//outline/@url`` * ``/opml/body//outline[type="source"]/@xmlUrl`` * ``/rdf:RDF//rdfs:seeAlso/@rdf:resource`` .. rubric:: Opportunity URLs come from * ``/opml/body//outline/@htmlUrl`` * ``/rdf:RDF//foaf:Agent//foaf:Document/@rdf:about`` listparser-0.18/docs/reference/objects.rst000066400000000000000000000005001251554201200206730ustar00rootroot00000000000000Shared 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. .. toctree:: :glob: :maxdepth: 1 object-* listparser-0.18/docs/reference/opportunities.rst000066400000000000000000000011151251554201200221710ustar00rootroot00000000000000opportunities ============= 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. .. seealso:: * :doc:`opportunities[i].categories ` * :doc:`opportunities[i].tags ` * :doc:`opportunities[i].title ` * :doc:`opportunities[i].url ` listparser-0.18/docs/reference/parse.rst000066400000000000000000000025341251554201200203650ustar00rootroot00000000000000parse() ======= .. 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. listparser-0.18/docs/reference/status.rst000066400000000000000000000010041251554201200205650ustar00rootroot00000000000000status ====== 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 `_ listparser-0.18/docs/reference/user_agent.rst000066400000000000000000000006161251554201200214060ustar00rootroot00000000000000USER_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. listparser-0.18/docs/reference/version.rst000066400000000000000000000015001251554201200207300ustar00rootroot00000000000000version ======= ``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]_ opml2 `OPML version 2.0 `_ opml An OPML file with an unknown or unspecified version rdf `RDF+FOAF `_ igoogle iGoogle exported settings format [#igoog_export]_ .. rubric:: Footnotes .. [#opml11] `OPML 1.1 files are treated as OPML 1.0 files. `_ .. [#igoog_export] `How to export your iGoogle page settings `_ listparser-0.18/listparser.py000066400000000000000000000635721251554201200164060ustar00rootroot00000000000000# 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 listparser-0.18/lptest.py000066400000000000000000000425431251554201200155240ustar00rootroot00000000000000# 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()) listparser-0.18/project.opml000066400000000000000000000010671251554201200161720ustar00rootroot00000000000000 listparser project feeds Kurt McKee contactme@kurtmckee.org http://kurtmckee.org/ listparser-0.18/setup.py000066400000000000000000000032121251554201200153370ustar00rootroot00000000000000from 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', ] ) listparser-0.18/tests/000077500000000000000000000000001251554201200147715ustar00rootroot00000000000000listparser-0.18/tests/1x1.gif000066400000000000000000000000531251554201200160670ustar00rootroot00000000000000GIF89a€ÿÀÀÀ!ù,D;listparser-0.18/tests/bad_bytes-00ff.xml000066400000000000000000000002731251554201200202020ustar00rootroot00000000000000 �ÿ listparser-0.18/tests/filename.xml000066400000000000000000000002711251554201200172730ustar00rootroot00000000000000 filename listparser-0.18/tests/http/000077500000000000000000000000001251554201200157505ustar00rootroot00000000000000listparser-0.18/tests/http/destination.xml000066400000000000000000000007021251554201200210120ustar00rootroot00000000000000 Redirection destination listparser-0.18/tests/http/http-bad_last_modified.xml000066400000000000000000000005671251554201200230700ustar00rootroot00000000000000 listparser-0.18/tests/http/http-bad_status.xml000066400000000000000000000001261251554201200215770ustar00rootroot00000000000000 listparser-0.18/tests/http/http_301.xml000066400000000000000000000006411251554201200200350ustar00rootroot00000000000000 listparser-0.18/tests/http/http_302.xml000066400000000000000000000006411251554201200200360ustar00rootroot00000000000000 listparser-0.18/tests/http/http_303.xml000066400000000000000000000006411251554201200200370ustar00rootroot00000000000000 listparser-0.18/tests/http/http_304-etag.xml000066400000000000000000000004001251554201200207470ustar00rootroot00000000000000 listparser-0.18/tests/http/http_304-last_modified.xml000066400000000000000000000007321251554201200226420ustar00rootroot00000000000000 listparser-0.18/tests/http/http_307.xml000066400000000000000000000006411251554201200200430ustar00rootroot00000000000000 listparser-0.18/tests/http/http_404.xml000066400000000000000000000005101251554201200200340ustar00rootroot00000000000000 Found despite an HTTP 404 listparser-0.18/tests/http/http_etag.xml000066400000000000000000000003751251554201200204560ustar00rootroot00000000000000 listparser-0.18/tests/http/http_last_modified.xml000066400000000000000000000005711251554201200223370ustar00rootroot00000000000000 listparser-0.18/tests/http/useragent.xml000066400000000000000000000004631251554201200204720ustar00rootroot00000000000000 Test customized User-Agent listparser-0.18/tests/igoogle/000077500000000000000000000000001251554201200164165ustar00rootroot00000000000000listparser-0.18/tests/igoogle/GadgetTabML.xml000066400000000000000000000003401251554201200212100ustar00rootroot00000000000000 listparser-0.18/tests/igoogle/ModulePrefs_xmlUrl-wrong_type.xml000066400000000000000000000005771251554201200251340ustar00rootroot00000000000000 listparser-0.18/tests/igoogle/ModulePrefs_xmlUrl.xml000066400000000000000000000005511251554201200227310ustar00rootroot00000000000000 listparser-0.18/tests/igoogle/hierarchy-bad.xml000066400000000000000000000006721251554201200216470ustar00rootroot00000000000000 listparser-0.18/tests/igoogle/hierarchy.xml000066400000000000000000000007051251554201200211200ustar00rootroot00000000000000 listparser-0.18/tests/injection/000077500000000000000000000000001251554201200167535ustar00rootroot00000000000000listparser-0.18/tests/injection/attribute-node.xml000066400000000000000000000006421251554201200224250ustar00rootroot00000000000000 listparser-0.18/tests/injection/still-undefined.xml000066400000000000000000000004371251554201200225670ustar00rootroot00000000000000 arch&egregiouslyundefined;ology listparser-0.18/tests/injection/text-node-1.xml000066400000000000000000000005551251554201200215470ustar00rootroot00000000000000 archæology archæology listparser-0.18/tests/injection/text-node-2.xml000066400000000000000000000005601251554201200215440ustar00rootroot00000000000000 1 μs is brief 1 μs is brief listparser-0.18/tests/opml/000077500000000000000000000000001251554201200157405ustar00rootroot00000000000000listparser-0.18/tests/opml/categories/000077500000000000000000000000001251554201200200655ustar00rootroot00000000000000listparser-0.18/tests/opml/categories/cats-1-single_standalone.xml000066400000000000000000000006611251554201200253710ustar00rootroot00000000000000 listparser-0.18/tests/opml/categories/cats-2-single_hierarchy.xml000066400000000000000000000006711251554201200252210ustar00rootroot00000000000000 listparser-0.18/tests/opml/categories/cats-3-multiple.xml000066400000000000000000000007621251554201200235370ustar00rootroot00000000000000 listparser-0.18/tests/opml/categories/cats-4-bad.xml000066400000000000000000000011661251554201200224320ustar00rootroot00000000000000 listparser-0.18/tests/opml/categories/duplication.xml000066400000000000000000000010411251554201200231160ustar00rootroot00000000000000 listparser-0.18/tests/opml/categories/hier-1-single.xml000066400000000000000000000010151251554201200231500ustar00rootroot00000000000000 listparser-0.18/tests/opml/categories/hier-2-nested.xml000066400000000000000000000010251251554201200231530ustar00rootroot00000000000000 listparser-0.18/tests/opml/categories/hier-3-whitespace.xml000066400000000000000000000006361251554201200240350ustar00rootroot00000000000000 listparser-0.18/tests/opml/categories/hier-4-mixed.xml000066400000000000000000000011001251554201200227730ustar00rootroot00000000000000 listparser-0.18/tests/opml/categories/hier-5-title.xml000066400000000000000000000007651251554201200230270ustar00rootroot00000000000000 listparser-0.18/tests/opml/categories/tags-1-single.xml000066400000000000000000000006761251554201200231730ustar00rootroot00000000000000 listparser-0.18/tests/opml/categories/tags-2-multiple.xml000066400000000000000000000010351251554201200235340ustar00rootroot00000000000000 listparser-0.18/tests/opml/categories/tags-3-cats_mixed.xml000066400000000000000000000010231251554201200240170ustar00rootroot00000000000000 listparser-0.18/tests/opml/categories/tags-4-bad.xml000066400000000000000000000010461251554201200224330ustar00rootroot00000000000000 listparser-0.18/tests/opml/head-empty_tags.xml000066400000000000000000000010561251554201200215370ustar00rootroot00000000000000 listparser-0.18/tests/opml/head_dateCreated-invalid.xml000066400000000000000000000005251251554201200232760ustar00rootroot00000000000000 sometime last week-ish, I think listparser-0.18/tests/opml/head_dateCreated-whitespace.xml000066400000000000000000000006731251554201200240100ustar00rootroot00000000000000 Sun, 21 Jun 2009 12:00:00 GMT listparser-0.18/tests/opml/head_dateCreated.xml000066400000000000000000000006161251554201200216530ustar00rootroot00000000000000 Sun, 21 Jun 2009 12:00:00 GMT listparser-0.18/tests/opml/head_dateModified-invalid.xml000066400000000000000000000005311251554201200234440ustar00rootroot00000000000000 sometime last week-ish, I think listparser-0.18/tests/opml/head_dateModified-whitespace.xml000066400000000000000000000007001251554201200241500ustar00rootroot00000000000000 Sun, 21 Jun 2009 12:00:00 GMT listparser-0.18/tests/opml/head_dateModified.xml000066400000000000000000000006231251554201200220220ustar00rootroot00000000000000 Sun, 21 Jun 2009 12:00:00 GMT listparser-0.18/tests/opml/head_ownerEmail-whitespace.xml000066400000000000000000000005741251554201200237050ustar00rootroot00000000000000 ownerEmail@example.com listparser-0.18/tests/opml/head_ownerEmail.xml000066400000000000000000000005171251554201200215500ustar00rootroot00000000000000 ownerEmail@example.com listparser-0.18/tests/opml/head_ownerId-whitespace.xml000066400000000000000000000005711251554201200232070ustar00rootroot00000000000000 http://example.com/contact listparser-0.18/tests/opml/head_ownerId.xml000066400000000000000000000005141251554201200210520ustar00rootroot00000000000000 http://example.com/contact listparser-0.18/tests/opml/head_ownerName-whitespace.xml000066400000000000000000000005401251554201200235270ustar00rootroot00000000000000 authorname listparser-0.18/tests/opml/head_ownerName.xml000066400000000000000000000004631251554201200214010ustar00rootroot00000000000000 authorname listparser-0.18/tests/opml/head_title-whitespace.xml000066400000000000000000000005111251554201200227130ustar00rootroot00000000000000 listtitle listparser-0.18/tests/opml/head_title.xml000066400000000000000000000004341251554201200205650ustar00rootroot00000000000000 listtitle listparser-0.18/tests/opml/include/000077500000000000000000000000001251554201200173635ustar00rootroot00000000000000listparser-0.18/tests/opml/include/outline_text-whitespace.xml000066400000000000000000000005601251554201200247630ustar00rootroot00000000000000 listparser-0.18/tests/opml/include/outline_text.xml000066400000000000000000000005031251554201200226260ustar00rootroot00000000000000 listparser-0.18/tests/opml/include/outline_type-case_insensitive.xml000066400000000000000000000004601251554201200261560ustar00rootroot00000000000000 listparser-0.18/tests/opml/include/outline_type-include.xml000066400000000000000000000004521251554201200242470ustar00rootroot00000000000000 listparser-0.18/tests/opml/include/outline_type-no_url.xml000066400000000000000000000003331251554201200241200ustar00rootroot00000000000000 listparser-0.18/tests/opml/include/outline_url-whitespace.xml000066400000000000000000000005501251554201200246000ustar00rootroot00000000000000 listparser-0.18/tests/opml/include/outline_url.xml000066400000000000000000000005171251554201200224510ustar00rootroot00000000000000 listparser-0.18/tests/opml/link/000077500000000000000000000000001251554201200166755ustar00rootroot00000000000000listparser-0.18/tests/opml/link/outline_text-whitespace.xml000066400000000000000000000005561251554201200243020ustar00rootroot00000000000000 listparser-0.18/tests/opml/link/outline_text.xml000066400000000000000000000005011251554201200221360ustar00rootroot00000000000000 listparser-0.18/tests/opml/link/outline_type-case_insensitive.xml000066400000000000000000000004611251554201200254710ustar00rootroot00000000000000 listparser-0.18/tests/opml/link/outline_type-link.xml000066400000000000000000000004501251554201200230710ustar00rootroot00000000000000 listparser-0.18/tests/opml/link/outline_type-no_url.xml000066400000000000000000000003251251554201200234330ustar00rootroot00000000000000 listparser-0.18/tests/opml/link/outline_url-whitespace.xml000066400000000000000000000005521251554201200241140ustar00rootroot00000000000000 listparser-0.18/tests/opml/link/outline_url.xml000066400000000000000000000005211251554201200217560ustar00rootroot00000000000000 listparser-0.18/tests/opml/opml_version-1.xml000066400000000000000000000003431251554201200213340ustar00rootroot00000000000000 listparser-0.18/tests/opml/opml_version-11.xml000066400000000000000000000003451251554201200214170ustar00rootroot00000000000000 listparser-0.18/tests/opml/opml_version-2.xml000066400000000000000000000003431251554201200213350ustar00rootroot00000000000000 listparser-0.18/tests/opml/opml_version-missing.xml000066400000000000000000000003411251554201200226430ustar00rootroot00000000000000 listparser-0.18/tests/opml/opml_version-unknown.xml000066400000000000000000000003641251554201200226760ustar00rootroot00000000000000 listparser-0.18/tests/opml/opportunities/000077500000000000000000000000001251554201200206645ustar00rootroot00000000000000listparser-0.18/tests/opml/opportunities/opml-htmlUrl-empty.xml000066400000000000000000000004421251554201200251360ustar00rootroot00000000000000 listparser-0.18/tests/opml/opportunities/opml-htmlUrl-miscapitalized.xml000066400000000000000000000006771251554201200270140ustar00rootroot00000000000000 listparser-0.18/tests/opml/opportunities/opml-htmlUrl-valid_feed.xml000066400000000000000000000004751251554201200260700ustar00rootroot00000000000000 listparser-0.18/tests/opml/opportunities/opml-htmlUrl.xml000066400000000000000000000006371251554201200240100ustar00rootroot00000000000000 listparser-0.18/tests/opml/opportunities/opml-htmlUrl_alone.xml000066400000000000000000000004761251554201200251670ustar00rootroot00000000000000 listparser-0.18/tests/opml/outline-duplication-1.xml000066400000000000000000000005511251554201200226110ustar00rootroot00000000000000 listparser-0.18/tests/opml/outline-duplication-2.xml000066400000000000000000000012451251554201200226130ustar00rootroot00000000000000 listparser-0.18/tests/opml/outline_text-overrides_title.xml000066400000000000000000000005041251554201200244050ustar00rootroot00000000000000 listparser-0.18/tests/opml/outline_text-whitespace.xml000066400000000000000000000005411251554201200233370ustar00rootroot00000000000000 listparser-0.18/tests/opml/outline_text.xml000066400000000000000000000004431251554201200212060ustar00rootroot00000000000000 listparser-0.18/tests/opml/outline_title-text_empty.xml000066400000000000000000000005271251554201200235460ustar00rootroot00000000000000 listparser-0.18/tests/opml/outline_title-text_missing-whitespace.xml000066400000000000000000000005651251554201200262150ustar00rootroot00000000000000 listparser-0.18/tests/opml/outline_title-text_missing.xml000066400000000000000000000005041251554201200240540ustar00rootroot00000000000000 listparser-0.18/tests/opml/outline_type-case_insensitive.xml000066400000000000000000000004441251554201200245350ustar00rootroot00000000000000 listparser-0.18/tests/opml/outline_type-link.xml000066400000000000000000000006561251554201200221440ustar00rootroot00000000000000 listparser-0.18/tests/opml/outline_type-missing.xml000066400000000000000000000005051251554201200226510ustar00rootroot00000000000000 listparser-0.18/tests/opml/outline_type-pie.xml000066400000000000000000000005301251554201200217530ustar00rootroot00000000000000 listparser-0.18/tests/opml/outline_type-rss.xml000066400000000000000000000004321251554201200220060ustar00rootroot00000000000000 listparser-0.18/tests/opml/outline_type-source.xml000066400000000000000000000011341251554201200224770ustar00rootroot00000000000000 listparser-0.18/tests/opml/outline_type-unknown.xml000066400000000000000000000004441251554201200227010ustar00rootroot00000000000000 listparser-0.18/tests/opml/outline_xmlUrl-empty.xml000066400000000000000000000005141251554201200226400ustar00rootroot00000000000000 listparser-0.18/tests/opml/outline_xmlUrl-miscapitalized.xml000066400000000000000000000005621251554201200245070ustar00rootroot00000000000000 listparser-0.18/tests/opml/outline_xmlUrl-whitespace.xml000066400000000000000000000005061251554201200236370ustar00rootroot00000000000000 listparser-0.18/tests/opml/outline_xmlUrl.xml000066400000000000000000000004551251554201200215100ustar00rootroot00000000000000 listparser-0.18/tests/rdf/000077500000000000000000000000001251554201200155445ustar00rootroot00000000000000listparser-0.18/tests/rdf/foaf_agent-multiple_weblogs.xml000066400000000000000000000031321251554201200237310ustar00rootroot00000000000000 User listparser-0.18/tests/rdf/foaf_agent-title-1.xml000066400000000000000000000013331251554201200216340ustar00rootroot00000000000000 User listparser-0.18/tests/rdf/foaf_agent-title-2.xml000066400000000000000000000013331251554201200216350ustar00rootroot00000000000000 User listparser-0.18/tests/rdf/foaf_agent-title-whitespace.xml000066400000000000000000000013561251554201200236350ustar00rootroot00000000000000 User listparser-0.18/tests/rdf/foaf_agent-url-2.xml000066400000000000000000000014301251554201200213140ustar00rootroot00000000000000 listparser-0.18/tests/rdf/foaf_agent-url-whitespace.xml000066400000000000000000000013761251554201200233200ustar00rootroot00000000000000 listparser-0.18/tests/rdf/foaf_agent-url.xml000066400000000000000000000013471251554201200211640ustar00rootroot00000000000000 listparser-0.18/tests/rdf/foaf_group-1.xml000066400000000000000000000017251251554201200205600ustar00rootroot00000000000000 Planet X User listparser-0.18/tests/rdf/foaf_group-2.xml000066400000000000000000000017251251554201200205610ustar00rootroot00000000000000 User Planet X listparser-0.18/tests/rdf/foaf_group-duplication-1.xml000066400000000000000000000027521251554201200230720ustar00rootroot00000000000000 i18n User L10n User listparser-0.18/tests/rdf/foaf_group-duplication-2.xml000066400000000000000000000027501251554201200230710ustar00rootroot00000000000000 i18n User i18n User listparser-0.18/tests/rdf/foaf_group-no_name.xml000066400000000000000000000017011251554201200220260ustar00rootroot00000000000000 User listparser-0.18/tests/rdf/foaf_knows-foaf_membername.xml000066400000000000000000000011571251554201200235270ustar00rootroot00000000000000 Bogus member listparser-0.18/tests/rdf/foaf_knows-foaf_name.xml000066400000000000000000000011501251554201200223300ustar00rootroot00000000000000 Bogus member listparser-0.18/tests/rdf/opportunities/000077500000000000000000000000001251554201200204705ustar00rootroot00000000000000listparser-0.18/tests/rdf/opportunities/rdf-foaf_Document-empty.xml000066400000000000000000000012051251554201200256660ustar00rootroot00000000000000 listparser-0.18/tests/rdf/opportunities/rdf-foaf_Document-missing.xml000066400000000000000000000011711251554201200262030ustar00rootroot00000000000000 listparser-0.18/tests/rdf/opportunities/rdf-foaf_Document-woven-1.xml000066400000000000000000000026241251554201200260320ustar00rootroot00000000000000 opp feed opp listparser-0.18/tests/rdf/opportunities/rdf-foaf_Document-woven-2.xml000066400000000000000000000026241251554201200260330ustar00rootroot00000000000000 feed opp feed listparser-0.18/tests/rdf/opportunities/rdf-foaf_Document.xml000066400000000000000000000014471251554201200245420ustar00rootroot00000000000000 opportunity listparser-0.18/tests/rdf/rss_channel-empty.xml000066400000000000000000000011711251554201200217210ustar00rootroot00000000000000 listparser-0.18/tests/rdf/version.xml000066400000000000000000000003201251554201200177460ustar00rootroot00000000000000 listparser-0.18/tests/rdf/yandex/000077500000000000000000000000001251554201200170345ustar00rootroot00000000000000listparser-0.18/tests/rdf/yandex/ya_blogActivity-ensure_name.xml000066400000000000000000000021271251554201200252100ustar00rootroot00000000000000 name friend listparser-0.18/tests/rdf/yandex/ya_blogActivity-ya_Comments-url.xml000066400000000000000000000013701251554201200257640ustar00rootroot00000000000000 listparser-0.18/tests/rdf/yandex/ya_blogActivity-ya_Posts-url.xml000066400000000000000000000013571251554201200253140ustar00rootroot00000000000000 listparser-0.18/tests/unknown-namespace.xml000066400000000000000000000003061251554201200211430ustar00rootroot00000000000000