pax_global_header00006660000000000000000000000064137433312130014512gustar00rootroot0000000000000052 comment=da75637f8edde839bca41a030ec0d03e4c93cf55 python-rt-2.0.1/000077500000000000000000000000001374333121300134565ustar00rootroot00000000000000python-rt-2.0.1/AUTHORS000066400000000000000000000003471374333121300145320ustar00rootroot00000000000000Development Lead: community Someone with write permissions - Edvard Rejthar Patches and Suggestions: - Stewart Perrygrove - Georges Toth Original Author: - Jiří Machálek python-rt-2.0.1/CHANGES000066400000000000000000000064441374333121300144610ustar00rootroot00000000000000v2.0.0, 2020-02-11 - Drop Python2 support - Adjust Travis tests for Python3-only, and add v3.8 - Add inline typing - Remove "debug_mode" parameter - Add "logging" support (basically replacing "debug_mode" and the various "print"s) - Fix "no-else-after-return" and "no-else-after-raise" - Fix "startswitch" typos / bugs - Removed deprecated "basic_auth" and "digest_auth" paramters. The same functionality is given by specifying the "http_auth" with an instance of either object. This allows for more flexibility with various other alternative authentication methods. v1.0.13, 2020-02-06 - Add deprecation warning for in the next major release unsupported parameters (basic_auth, digest_auth). They are now replaced with http_auth. - Fix problematic default method parameters ("{}" and "[]"). v1.0.12, 2019-10-25 - Travis CI Docker tests - RT 4.4 fixes - Support multiline CF values in create_ticket and edit_ticket. - Fix support for custom field names containing colons - In search(), replace splitlines() with lines array split on \n. - Add debug_mode flag for response logging - Add platform independent url joining / Allow testing on Windows - Add numerical_id to get_ticket result v1.0.11, 2018-07-16 - Added parameter to set the content type in reply() and comment() (#12). - Added parameter Format to search() (#17). - Tests: Update to new demo instance, fixing tests. - Tests: Disable tests in Travis, the existing test instance closed the REST interface (#28). - Fix support for custom field names containing colons (#37). - Fix support for custom field values containing newlines (#11). v1.0.10, 2017-02-22 - PEP8 fixes - update .travis.yml to update python interpreter list and some other small changes - prefer format over % (PEP 3101) - Add patch from https://gitlab.labs.nic.cz/labs/python-rt/issues/9 "Support CF search where special chars or spaces in CF names" - Implement a fix for the issue suggested in https://gitlab.labs.nic.cz/labs/python-rt/issues/10 (can't create ticket with multi-line message) - Implement fix for https://gitlab.labs.nic.cz/labs/python-rt/issues/7 "returned types inconsistent in get_ticket" Add splitting for Cc and AdminCc v1.0.9, 2016-06-22 - added ability to steal, untake, and explicitly take tickets - fixed create_ticket return value when provided an invalid custom field v1.0.8, 2014-05-29 - added ability to search all queues - added RtError super class - fixed compatibility issues with Python 2.6 v1.0.7, 2013-10-01 - unit tests - own exceptions - added create_user, create_queue, edit_user, edit_queue methods - added edit_link (replaces buggy edit_ticket_links) - added get_attachments, get_short_history methods - support merge_ticket in RT4 - custom query to search method - strict binary handling with attachments v1.0.6, 2013-09-05 - added support for HTTP basic and digest authentication - specification of errors to different exceptions v1.0.5, 2013-04-26 - fixed decoding of utf-8 only when needed - updated search function to support various lookup operators and sorting v1.0.4, 2013-03-21 - default queue added to init parameters v1.0.3, 2013-03-06 - python-requests 1.x compatible v1.0.2, 2013-02-18 - HTTP proxy support - Support for multilinks in get_links v1.0.1, 2013-01-10 - Updated docstrings - Added Sphinx documentation v1.0.0, 2012-08-03 - Initial release python-rt-2.0.1/COPYING000066400000000000000000001045131374333121300145150ustar00rootroot00000000000000 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 . python-rt-2.0.1/MANIFEST.in000066400000000000000000000001571374333121300152170ustar00rootroot00000000000000include AUTHORS include CHANGES include COPYING include README.rst include test_rt.py recursive-include doc * python-rt-2.0.1/PKG-INFO000066400000000000000000000113351374333121300145560ustar00rootroot00000000000000Metadata-Version: 1.2 Name: rt Version: 2.0.1 Summary: Python interface to Request Tracker API Home-page: https://github.com/CZ-NIC/python-rt Author: Jiri Machalek Author-email: edvard.rejthar@nic.cz License: GNU General Public License (GPL) Description: .. image:: https://travis-ci.org/CZ-NIC/python-rt.svg?branch=master :target: https://travis-ci.org/CZ-NIC/python-rt .. image:: https://readthedocs.org/projects/python-rt/badge/?version=latest :target: https://python-rt.readthedocs.io/en/latest/?badge=latest :alt: Documentation Status ============================================== Rt - Python interface to Request Tracker API ============================================== Python implementation of REST API described here: https://rt-wiki.bestpractical.com/wiki/REST **Note:** Please note that starting with the major release of v2.0.0, this library requires a Python version >= 3.5. In case you still require a Python 2 version or one compatible with Python < 3.5, please use a version < 2.0.0 of this library. REQUIREMENTS ============ This module uses following Python modules: - requests (http://docs.python-requests.org/) Unit-tests are implemented using: - nose (http://nose.readthedocs.org) INSTALLATION ============ Install the python-rt package using:: pip install rt LICENCE ======= This module is distributed under the terms of GNU General Public Licence v3 and was developed by CZ.NIC Labs - research and development department of CZ.NIC association - top level domain registy for .CZ. Copy of the GNU General Public License is distributed along with this module. USAGE ===== An example is worth a thousand words:: >>> import rt >>> tracker = rt.Rt('http://localhost/rt/REST/1.0/', 'user_login', 'user_pass') >>> tracker.login() True >>> map(lambda x: x['id'], tracker.search(Queue='helpdesk', Status='open')) ['ticket/1', 'ticket/2', 'ticket/10', 'ticket/15'] >>> tracker.create_ticket(Queue='helpdesk', \ ... Subject='Coffee (important)', Text='Help I Ran Out of Coffee!') 19 >>> tracker.edit_ticket(19, Requestors='addicted@example.com') True >>> tracker.reply(19, text='Do you know Starbucks?') True >>> tracker.logout() True Get the last important updates from a specific queue that have been updated recently:: >>> import rt >>> tracker = rt.Rt('http://localhost/rt/REST/1.0/', http_auth=HTTPBasicAuth(os.environ['rtuser'], os.environ['rtpasswd'])) >>> tracker.default_queue = "my-queue" >>> fifteen_minutes_ago = str(datetime.datetime.now() - datetime.timedelta(minutes=15)) >>> tickets = tracker.last_updated(since=fifteen_minutes_ago) >>> for ticket in tickets: >>> id = ticket['id'][7:] >>> history = tracker.get_short_history(id) >>> last_update = list(reversed([h for h in history if h[1].startswith('Correspondence added') or h[1].startswith('Comments added')])) >>> hid = tracker.get_history(id, last_update[0][0] if last_update else history[0][0])[0] >>> print("http://localhost/rt/Ticket/Display.html?id=%s" % id) >>> print(hid['Content']) >>> print("\n") Please use docstrings to see how to use different functions. They are written in ReStructuredText. You can also generate HTML documentation by running ``make html`` in doc directory (Sphinx required). OFFICIAL SITE ============= Project site and issue tracking: https://github.com/CZ-NIC/python-rt Git repository: git://github.com/CZ-NIC/python-rt.git Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3) Classifier: Operating System :: POSIX Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 :: Only Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Software Development :: Libraries :: Python Modules Requires-Python: >=3.5 python-rt-2.0.1/README.rst000066400000000000000000000063461374333121300151560ustar00rootroot00000000000000 .. image:: https://travis-ci.org/CZ-NIC/python-rt.svg?branch=master :target: https://travis-ci.org/CZ-NIC/python-rt .. image:: https://readthedocs.org/projects/python-rt/badge/?version=latest :target: https://python-rt.readthedocs.io/en/latest/?badge=latest :alt: Documentation Status ============================================== Rt - Python interface to Request Tracker API ============================================== Python implementation of REST API described here: https://rt-wiki.bestpractical.com/wiki/REST **Note:** Please note that starting with the major release of v2.0.0, this library requires a Python version >= 3.5. In case you still require a Python 2 version or one compatible with Python < 3.5, please use a version < 2.0.0 of this library. REQUIREMENTS ============ This module uses following Python modules: - requests (http://docs.python-requests.org/) Unit-tests are implemented using: - nose (http://nose.readthedocs.org) INSTALLATION ============ Install the python-rt package using:: pip install rt LICENCE ======= This module is distributed under the terms of GNU General Public Licence v3 and was developed by CZ.NIC Labs - research and development department of CZ.NIC association - top level domain registy for .CZ. Copy of the GNU General Public License is distributed along with this module. USAGE ===== An example is worth a thousand words:: >>> import rt >>> tracker = rt.Rt('http://localhost/rt/REST/1.0/', 'user_login', 'user_pass') >>> tracker.login() True >>> map(lambda x: x['id'], tracker.search(Queue='helpdesk', Status='open')) ['ticket/1', 'ticket/2', 'ticket/10', 'ticket/15'] >>> tracker.create_ticket(Queue='helpdesk', \ ... Subject='Coffee (important)', Text='Help I Ran Out of Coffee!') 19 >>> tracker.edit_ticket(19, Requestors='addicted@example.com') True >>> tracker.reply(19, text='Do you know Starbucks?') True >>> tracker.logout() True Get the last important updates from a specific queue that have been updated recently:: >>> import rt >>> tracker = rt.Rt('http://localhost/rt/REST/1.0/', http_auth=HTTPBasicAuth(os.environ['rtuser'], os.environ['rtpasswd'])) >>> tracker.default_queue = "my-queue" >>> fifteen_minutes_ago = str(datetime.datetime.now() - datetime.timedelta(minutes=15)) >>> tickets = tracker.last_updated(since=fifteen_minutes_ago) >>> for ticket in tickets: >>> id = ticket['id'][7:] >>> history = tracker.get_short_history(id) >>> last_update = list(reversed([h for h in history if h[1].startswith('Correspondence added') or h[1].startswith('Comments added')])) >>> hid = tracker.get_history(id, last_update[0][0] if last_update else history[0][0])[0] >>> print("http://localhost/rt/Ticket/Display.html?id=%s" % id) >>> print(hid['Content']) >>> print("\n") Please use docstrings to see how to use different functions. They are written in ReStructuredText. You can also generate HTML documentation by running ``make html`` in doc directory (Sphinx required). OFFICIAL SITE ============= Project site and issue tracking: https://github.com/CZ-NIC/python-rt Git repository: git://github.com/CZ-NIC/python-rt.git python-rt-2.0.1/doc/000077500000000000000000000000001374333121300142235ustar00rootroot00000000000000python-rt-2.0.1/doc/Makefile000066400000000000000000000126541374333121300156730ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/rt.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/rt.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/rt" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/rt" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." python-rt-2.0.1/doc/conf.py000066400000000000000000000171251374333121300155300ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # rt documentation build configuration file, created by # sphinx-quickstart on Thu Jan 10 16:31:25 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os sys.path.insert(0, os.path.abspath('..')) # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] # 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-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'rt' copyright = u'2013, Jiri Machalek' # 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 = '2.0.0' # The full version, including alpha/beta/rc tags. release = '2.0.0' # 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 patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # 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' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # 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_domain_indices = 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, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = 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 = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'rtdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'rt.tex', u'rt Documentation', u'Jiri Machalek', '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 # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'rt', u'rt Documentation', [u'Jiri Machalek'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'rt', u'rt Documentation', u'Jiri Machalek', 'rt', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' python-rt-2.0.1/doc/glossary.rst000066400000000000000000000006161374333121300166230ustar00rootroot00000000000000Glossary ======== .. glossary:: :sorted: API An application programming interface, a source code based specification intended to be used as an interface by software components to communicate with each other. REST Representational state transfer, a style of software architecture for distributed hypermedia systems such as the World Wide Web python-rt-2.0.1/doc/index.rst000066400000000000000000000012231374333121300160620ustar00rootroot00000000000000.. rt documentation master file, created by sphinx-quickstart on Thu Jan 10 16:31:25 2013. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to rt's documentation! ============================== Contents: .. toctree:: :maxdepth: 2 glossary .. automodule:: rt.rt :members: .. automodule:: rt.exceptions :members: Get rt module ============= Using pip:: $ pip install rt Using project git repository:: $ git clone https://github.com/CZ-NIC/python-rt Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` python-rt-2.0.1/rt.egg-info/000077500000000000000000000000001374333121300155755ustar00rootroot00000000000000python-rt-2.0.1/rt.egg-info/PKG-INFO000066400000000000000000000113351374333121300166750ustar00rootroot00000000000000Metadata-Version: 1.2 Name: rt Version: 2.0.1 Summary: Python interface to Request Tracker API Home-page: https://github.com/CZ-NIC/python-rt Author: Jiri Machalek Author-email: edvard.rejthar@nic.cz License: GNU General Public License (GPL) Description: .. image:: https://travis-ci.org/CZ-NIC/python-rt.svg?branch=master :target: https://travis-ci.org/CZ-NIC/python-rt .. image:: https://readthedocs.org/projects/python-rt/badge/?version=latest :target: https://python-rt.readthedocs.io/en/latest/?badge=latest :alt: Documentation Status ============================================== Rt - Python interface to Request Tracker API ============================================== Python implementation of REST API described here: https://rt-wiki.bestpractical.com/wiki/REST **Note:** Please note that starting with the major release of v2.0.0, this library requires a Python version >= 3.5. In case you still require a Python 2 version or one compatible with Python < 3.5, please use a version < 2.0.0 of this library. REQUIREMENTS ============ This module uses following Python modules: - requests (http://docs.python-requests.org/) Unit-tests are implemented using: - nose (http://nose.readthedocs.org) INSTALLATION ============ Install the python-rt package using:: pip install rt LICENCE ======= This module is distributed under the terms of GNU General Public Licence v3 and was developed by CZ.NIC Labs - research and development department of CZ.NIC association - top level domain registy for .CZ. Copy of the GNU General Public License is distributed along with this module. USAGE ===== An example is worth a thousand words:: >>> import rt >>> tracker = rt.Rt('http://localhost/rt/REST/1.0/', 'user_login', 'user_pass') >>> tracker.login() True >>> map(lambda x: x['id'], tracker.search(Queue='helpdesk', Status='open')) ['ticket/1', 'ticket/2', 'ticket/10', 'ticket/15'] >>> tracker.create_ticket(Queue='helpdesk', \ ... Subject='Coffee (important)', Text='Help I Ran Out of Coffee!') 19 >>> tracker.edit_ticket(19, Requestors='addicted@example.com') True >>> tracker.reply(19, text='Do you know Starbucks?') True >>> tracker.logout() True Get the last important updates from a specific queue that have been updated recently:: >>> import rt >>> tracker = rt.Rt('http://localhost/rt/REST/1.0/', http_auth=HTTPBasicAuth(os.environ['rtuser'], os.environ['rtpasswd'])) >>> tracker.default_queue = "my-queue" >>> fifteen_minutes_ago = str(datetime.datetime.now() - datetime.timedelta(minutes=15)) >>> tickets = tracker.last_updated(since=fifteen_minutes_ago) >>> for ticket in tickets: >>> id = ticket['id'][7:] >>> history = tracker.get_short_history(id) >>> last_update = list(reversed([h for h in history if h[1].startswith('Correspondence added') or h[1].startswith('Comments added')])) >>> hid = tracker.get_history(id, last_update[0][0] if last_update else history[0][0])[0] >>> print("http://localhost/rt/Ticket/Display.html?id=%s" % id) >>> print(hid['Content']) >>> print("\n") Please use docstrings to see how to use different functions. They are written in ReStructuredText. You can also generate HTML documentation by running ``make html`` in doc directory (Sphinx required). OFFICIAL SITE ============= Project site and issue tracking: https://github.com/CZ-NIC/python-rt Git repository: git://github.com/CZ-NIC/python-rt.git Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3) Classifier: Operating System :: POSIX Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 :: Only Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Software Development :: Libraries :: Python Modules Requires-Python: >=3.5 python-rt-2.0.1/rt.egg-info/SOURCES.txt000066400000000000000000000005231374333121300174610ustar00rootroot00000000000000AUTHORS CHANGES COPYING MANIFEST.in README.rst setup.cfg setup.py test_rt.py doc/Makefile doc/conf.py doc/glossary.rst doc/index.rst rt/__init__.py rt/exceptions.py rt/py.typed rt/rt.py rt.egg-info/PKG-INFO rt.egg-info/SOURCES.txt rt.egg-info/dependency_links.txt rt.egg-info/not-zip-safe rt.egg-info/requires.txt rt.egg-info/top_level.txtpython-rt-2.0.1/rt.egg-info/dependency_links.txt000066400000000000000000000000011374333121300216430ustar00rootroot00000000000000 python-rt-2.0.1/rt.egg-info/not-zip-safe000066400000000000000000000000011374333121300200230ustar00rootroot00000000000000 python-rt-2.0.1/rt.egg-info/requires.txt000066400000000000000000000000111374333121300201650ustar00rootroot00000000000000requests python-rt-2.0.1/rt.egg-info/top_level.txt000066400000000000000000000000031374333121300203200ustar00rootroot00000000000000rt python-rt-2.0.1/rt/000077500000000000000000000000001374333121300141035ustar00rootroot00000000000000python-rt-2.0.1/rt/__init__.py000066400000000000000000000000541374333121300162130ustar00rootroot00000000000000from .rt import * from .exceptions import * python-rt-2.0.1/rt/exceptions.py000066400000000000000000000031061374333121300166360ustar00rootroot00000000000000"""Exceptions collection for the rt library.""" class RtError(Exception): """ Super class of all Rt Errors """ class AuthorizationError(RtError): """ Exception raised when module cannot access :term:`API` due to invalid or missing credentials. """ class NotAllowed(RtError): """ Exception raised when request cannot be finished due to insufficient privileges. """ class UnexpectedResponse(RtError): """ Exception raised when unexpected HTTP code is received. """ class UnexpectedMessageFormat(RtError): """ Exception raised when response has bad status code (not the HTTP code, but code in the first line of the body as 200 in `RT/4.0.7 200 Ok`) or message parsing fails because of unexpected format. """ class APISyntaxError(RtError): """ Exception raised when syntax error is received. """ class InvalidUse(RtError): """ Exception raised when API method is not used correctly. """ class BadRequest(RtError): """ Exception raised when HTTP code 400 (Bad Request) is received. """ class ConnectionError(RtError): """ Encapsulation of various exceptions indicating network problems. """ def __init__(self, message: str, cause: Exception) -> None: """ Initialization of exception extented by cause parameter. :keyword message: Exception details :keyword cause: Cause exception """ super().__init__(message + ' (Caused by ' + repr(cause) + ")") self.cause = cause class InvalidQueryError(RtError): """ Exception raised when attempting to search RT with an invalid raw query. """ python-rt-2.0.1/rt/py.typed000066400000000000000000000000001374333121300155700ustar00rootroot00000000000000python-rt-2.0.1/rt/rt.py000066400000000000000000001760711374333121300151160ustar00rootroot00000000000000""" ====================================================== Rt - Python interface to Request Tracker :term:`API` ====================================================== Description of Request Tracker :term:`REST` :term:`API`: http://requesttracker.wikia.com/wiki/REST Provided functionality: * login to RT * logout * getting, creating and editing tickets * getting attachments * getting history of ticket * replying to ticket requestors * adding comments * getting and editing ticket links * searching * providing lists of last updated tickets * providing tickets with new correspondence * merging tickets * take tickets * steal tickets * untake tickets """ import datetime import logging import re import typing import warnings from urllib.parse import urljoin import requests import requests.auth from .exceptions import * __license__ = """ Copyright (C) 2012 CZ.NIC, z.s.p.o. Copyright (c) 2015 Genome Research Ltd. 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 . """ __docformat__ = "reStructuredText en" __authors__ = [ '"Jiri Machalek" ', '"Joshua C. randall" ' ] DEFAULT_QUEUE = 'General' """ Default queue used. """ ALL_QUEUES = object() class Rt: """ :term:`API` for Request Tracker according to http://requesttracker.wikia.com/wiki/REST. Interface is based on :term:`REST` architecture, which is based on HTTP/1.1 protocol. This module is therefore mainly sending and parsing special HTTP messages. .. note:: Use only ASCII LF as newline (``\\n``). Time is returned in UTC. All strings returned are encoded in UTF-8 and the same is expected as input for string values. """ RE_PATTERNS = { 'not_allowed_pattern': re.compile('^# You are not allowed to'), 'credentials_required_pattern': re.compile('.* 401 Credentials required$'), 'syntax_error_pattern': re.compile('.* 409 Syntax Error$'), 'requestors_pattern': re.compile('Requestors:'), 'update_pattern': re.compile('^# Ticket [0-9]+ updated.$'), 'content_pattern': re.compile('Content:'), 'content_pattern_bytes': re.compile(b'Content:'), 'attachments_pattern': re.compile('Attachments:'), 'attachments_list_pattern': re.compile(r'[^0-9]*(\d+): (.+) \((.+) / (.+)\),?$'), 'headers_pattern_bytes': re.compile(b'Headers:'), 'links_updated_pattern': re.compile('^# Links for ticket [0-9]+ updated.$'), 'created_link_pattern': re.compile('.* Created link '), 'deleted_link_pattern': re.compile('.* Deleted link '), 'merge_successful_pattern': re.compile('^# Merge completed.|^Merge Successful$'), 'bad_request_pattern': re.compile('.* 400 Bad Request$'), 'user_pattern': re.compile(r'^# User ([0-9]*) (?:updated|created)\.$'), 'queue_pattern': re.compile(r'^# Queue (\w*) (?:updated|created)\.$'), 'ticket_created_pattern': re.compile(r'^# Ticket ([0-9]+) created\.$'), 'does_not_exist_pattern': re.compile(r'^# (?:Queue|User|Ticket) \w* does not exist\.$'), 'does_not_exist_pattern_bytes': re.compile(br'^# (?:Queue|User|Ticket) \w* does not exist\.$'), 'not_related_pattern': re.compile(r'^# Transaction \d+ is not related to Ticket \d+'), 'invalid_attachment_pattern_bytes': re.compile(br'^# Invalid attachment id: \d+$'), } # type: typing.Dict[str, re.Pattern] def __init__(self, url: str, default_login: typing.Optional[str] = None, default_password: typing.Optional[str] = None, proxy: typing.Optional[str] = None, default_queue: str = DEFAULT_QUEUE, skip_login: bool = False, verify_cert: typing.Optional[typing.Union[str, bool]] = True, http_auth: requests.auth.AuthBase = None) -> None: """ API initialization. :keyword url: Base URL for Request Tracker API. E.g.: http://tracker.example.com/REST/1.0/ :keyword default_login: Default RT login used by self.login if no other credentials are provided :keyword default_password: Default RT password :keyword proxy: Proxy server (string with http://user:password@host/ syntax) :keyword default_queue: Default RT queue :keyword skip_login: Set this option True when HTTP Basic authentication credentials for RT are in .netrc file. You do not need to call login, because it is managed by requests library instantly. :keyword http_auth: Specify a http authentication instance, e.g. HTTPBasicAuth(), HTTPDigestAuth(), etc. to be used for authenticating to RT """ self.logger = logging.getLogger(__name__) # ensure trailing slash if not url.endswith("/"): url = url + "/" self.url = url self.default_login = default_login self.default_password = default_password self.default_queue = default_queue self.login_result = None self.session = requests.session() self.session.verify = verify_cert if proxy is not None: if url.lower().startswith("https://"): self.session.proxies = {"https": proxy} else: self.session.proxies = {"http": proxy} if http_auth: self.session.auth = http_auth if skip_login or http_auth: # Assume valid credentials, because we do not need to call login() # explicitly with basic or digest authentication (or if this is # assured, that we are login in instantly) self.login_result = True def __request(self, selector, get_params=None, post_data=None, files=None, without_login=False, text_response=True): """ General request for :term:`API`. :keyword selector: End part of URL which completes self.url parameter set during class initialization. E.g.: ``ticket/123456/show`` :keyword post_data: Dictionary with POST method fields :keyword files: List of pairs (filename, file-like object) describing files to attach as multipart/form-data (list is necessary to keep files ordered) :keyword without_login: Turns off checking last login result (usually needed just for login itself) :keyword text_response: If set to false the received message will be returned without decoding (useful for attachments) :returns: Requested messsage including state line in form ``RT/3.8.7 200 Ok\\n`` :rtype: string or bytes if text_response is False :raises AuthorizationError: In case that request is called without previous login or login attempt failed. :raises ConnectionError: In case of connection error. """ try: if (not self.login_result) and (not without_login): raise AuthorizationError('First login by calling method `login`.') url = str(urljoin(self.url, selector)) if not files: if post_data: response = self.session.post(url, data=post_data) else: response = self.session.get(url, params=get_params) else: files_data = {} for i, file_pair in enumerate(files): files_data['attachment_{:d}'.format(i + 1)] = file_pair response = self.session.post(url, data=post_data, files=files_data) method = "GET" if post_data or files: method = "POST" self.logger.debug("### %s", datetime.datetime.now().isoformat()) self.logger.debug("Request URL: %s", url) self.logger.debug("Request method: %s", method) self.logger.debug("Respone status code: %s", str(response.status_code)) self.logger.debug("Response content:") self.logger.debug(response.content.decode(errors='ignore')) if response.status_code == 401: raise AuthorizationError('Server could not verify that you are authorized to access the requested document.') if response.status_code != 200: raise UnexpectedResponse('Received status code {:d} instead of 200.'.format(response.status_code)) try: if response.encoding: result = response.content.decode(response.encoding.lower()) else: # try utf-8 if encoding is not filled result = response.content.decode('utf-8') except LookupError: raise UnexpectedResponse('Unknown response encoding: {}.'.format(response.encoding)) except UnicodeError: if text_response: raise UnexpectedResponse('Unknown response encoding (UTF-8 does not work).') # replace errors - we need decoded content just to check for error codes in __check_response result = response.content.decode('utf-8', 'replace') self.__check_response(result) if not text_response: return response.content return result except requests.exceptions.ConnectionError as e: raise ConnectionError("Connection error", e) @staticmethod def __get_status_code(msg: str) -> typing.Optional[int]: """ Select status code given message. :keyword msg: Result message :returns: Status code :rtype: int """ try: return int(msg.split('\n')[0].split(' ')[1]) except Exception: return None def __check_response(self, msg: typing.Union[str, list]) -> None: """ Search general errors in server response and raise exceptions when found. :keyword msg: Result message :raises NotAllowed: Exception raised when operation was called with insufficient privileges :raises AuthorizationError: Credentials are invalid or missing :raises APISyntaxError: Syntax error """ if not isinstance(msg, list): msg = msg.split("\n") if (len(msg) > 2) and self.RE_PATTERNS['not_allowed_pattern'].match(msg[2]): raise NotAllowed(msg[2][2:]) if self.RE_PATTERNS['credentials_required_pattern'].match(msg[0]): raise AuthorizationError('Credentials required.') if self.RE_PATTERNS['syntax_error_pattern'].match(msg[0]): raise APISyntaxError(msg[2][2:] if len(msg) > 2 else 'Syntax error.') if self.RE_PATTERNS['bad_request_pattern'].match(msg[0]): raise BadRequest(msg[3] if len(msg) > 2 else 'Bad request.') @staticmethod def __normalize_list(msg): """Split message to list by commas and trim whitespace.""" if isinstance(msg, list): msg = "".join(msg) return list(map(lambda x: x.strip(), msg.split(","))) def login(self, login: typing.Optional[str] = None, password: typing.Optional[str] = None) -> bool: """ Login with default or supplied credetials. .. note:: Calling this method is not necessary when HTTP basic or HTTP digest_auth authentication is used and RT accepts it as external authentication method, because the login in this case is done transparently by requests module. Anyway this method can be useful to check whether given credentials are valid or not. :keyword login: Username used for RT, if not supplied together with *password* :py:attr:`~Rt.default_login` and :py:attr:`~Rt.default_password` are used instead :keyword password: Similarly as *login* :returns: ``True`` Successful login ``False`` Otherwise :raises AuthorizationError: In case that credentials are not supplied neither during inicialization or call of this method. """ if (login is not None) and (password is not None): login_data = {'user': login, 'pass': password} # type: typing.Optional[typing.Dict[str, str]] elif (self.default_login is not None) and (self.default_password is not None): login_data = {'user': self.default_login, 'pass': self.default_password} elif self.session.auth: login_data = None else: raise AuthorizationError('Credentials required, fill login and password.') try: self.login_result = self.__get_status_code(self.__request('', post_data=login_data, without_login=True)) == 200 except AuthorizationError: # This happens when HTTP Basic or Digest authentication fails, but # we will not raise the error but just return False to indicate # invalid credentials return False else: return bool(self.login_result) def logout(self) -> bool: """ Logout of user. :returns: ``True`` Successful logout ``False`` Logout failed (mainly because user was not login) """ ret = False if self.login_result is True: ret = self.__get_status_code(self.__request('logout')) == 200 self.login_result = None return ret def new_correspondence(self, queue: typing.Optional[typing.Union[str, object]] = None) -> typing.List[dict]: """ Obtains tickets changed by other users than the system one. :keyword queue: Queue where to search :returns: List of tickets which were last updated by other user than the system one ordered in decreasing order by LastUpdated. Each ticket is dictionary, the same as in :py:meth:`~Rt.get_ticket`. """ return self.search(Queue=queue, order='-LastUpdated', LastUpdatedBy__notexact=self.default_login) def last_updated(self, since: str, queue: typing.Optional[typing.Union[str, object]] = None) -> typing.List[dict]: """ Obtains tickets changed after given date. :param since: Date as string in form '2011-02-24' :keyword queue: Queue where to search :returns: List of tickets with LastUpdated parameter later than *since* ordered in decreasing order by LastUpdated. Each tickets is dictionary, the same as in :py:meth:`~Rt.get_ticket`. """ return self.search(Queue=queue, order='-LastUpdated', LastUpdatedBy__notexact=self.default_login, LastUpdated__gt=since) def search(self, Queue: typing.Optional[typing.Union[str, object]] = None, order: typing.Optional[str] = None, raw_query: typing.Optional[str] = None, Format: str = 'l', **kwargs: typing.Any) -> typing.List[dict]: """ Search arbitrary needles in given fields and queue. Example:: >>> tracker = Rt('http://tracker.example.com/REST/1.0/', 'rt-username', 'top-secret') >>> tracker.login() >>> tickets = tracker.search(CF_Domain='example.com', Subject__like='warning') >>> tickets = tracker.search(Queue='General', order='Status', raw_query="id='1'+OR+id='2'+OR+id='3'") :keyword Queue: Queue where to search. If you wish to search across all of your queues, pass the ALL_QUEUES object as the argument. :keyword order: Name of field sorting result list, for descending order put - before the field name. E.g. -Created will put the newest tickets at the beginning :keyword raw_query: A raw query to provide to RT if you know what you are doing. You may still pass Queue and order kwargs, so use these instead of including them in the raw query. You can refer to the RT query builder. If passing raw_query, all other **kwargs will be ignored. :keyword Format: Format of the query: - i: only `id' fields are populated - s: only `id' and `subject' fields are populated - l: multi-line format, all fields are populated :keyword kwargs: Other arguments possible to set if not passing raw_query: Requestors, Subject, Cc, AdminCc, Owner, Status, Priority, InitialPriority, FinalPriority, TimeEstimated, Starts, Due, Text,... (according to RT fields) Custom fields CF.{} could be set with keywords CF_CustomFieldName. To alter lookup operators you can append one of the following endings to each keyword: __exact for operator = (default) __notexact for operator != __gt for operator > __lt for operator < __like for operator LIKE __notlike for operator NOT LIKE Setting values to keywords constrain search result to the tickets satisfying all of them. :returns: List of matching tickets. Each ticket is the same dictionary as in :py:meth:`~Rt.get_ticket`. :raises: UnexpectedMessageFormat: Unexpected format of returned message. InvalidQueryError: If raw query is malformed """ get_params = {} query = [] url = 'search/ticket' if Queue is not ALL_QUEUES: query.append("Queue=\'{}\'".format(Queue or self.default_queue)) if not raw_query: operators_map = { 'gt': '>', 'lt': '<', 'exact': '=', 'notexact': '!=', 'like': ' LIKE ', 'notlike': ' NOT LIKE ' } for key, value in kwargs.items(): op = '=' key_parts = key.split('__') if len(key_parts) > 1: key = '__'.join(key_parts[:-1]) op = operators_map.get(key_parts[-1], '=') if key[:3] != 'CF_': query.append("{}{}\'{}\'".format(key, op, value)) else: query.append("'CF.{{{}}}'{}\'{}\'".format(key[3:], op, value)) else: query.append(raw_query) get_params['query'] = ' AND '.join('(' + part + ')' for part in query) if order: get_params['orderby'] = order get_params['format'] = Format msg = self.__request(url, get_params=get_params) lines = msg.split('\n') if len(lines) > 2: if self.__get_status_code(lines[0]) != 200 and lines[2].startswith('Invalid query: '): raise InvalidQueryError(lines[2]) if lines[2].startswith('No matching results.'): return [] if Format == 'l': msgs = map(lambda x: x.split('\n'), msg.split('\n--\n')) items = [] for msg in msgs: pairs = {} req_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['requestors_pattern'].match(m)] req_id = req_matching[0] if req_matching else None if not req_id: raise UnexpectedMessageFormat('Missing line starting with `Requestors:`.') for i in range(req_id): if ': ' in msg[i]: header, content = self.split_header(msg[i]) pairs[header.strip()] = content.strip() requestors = [msg[req_id][12:]] req_id += 1 while (req_id < len(msg)) and (msg[req_id][:12] == ' ' * 12): requestors.append(msg[req_id][12:]) req_id += 1 pairs['Requestors'] = self.__normalize_list(requestors) for i in range(req_id, len(msg)): if ': ' in msg[i]: header, content = self.split_header(msg[i]) pairs[header.strip()] = content.strip() if pairs: items.append(pairs) if 'Cc' in pairs: pairs['Cc'] = self.__normalize_list(pairs['Cc']) if 'AdminCc' in pairs: pairs['AdminCc'] = self.__normalize_list(pairs['AdminCc']) if 'id' not in pairs and not pairs['id'].startswith('ticket/'): raise UnexpectedMessageFormat('Response from RT didn\'t contain a valid ticket_id') pairs['numerical_id'] = pairs['id'].split('ticket/')[1] return items if Format == 's': items = [] msgs = lines[2:] for msg in msgs: if msg == '': # Ignore blank line at the end continue ticket_id, subject = self.split_header(msg) items.append({'id': 'ticket/' + ticket_id, 'numerical_id': ticket_id, 'Subject': subject}) return items if Format == 'i': items = [] msgs = lines[2:] for msg in msgs: if msg == '': # Ignore blank line at the end continue _, ticket_id = msg.split('/', 1) items.append({'id': 'ticket/' + ticket_id, 'numerical_id': ticket_id}) return items return [] def get_ticket(self, ticket_id: typing.Union[str, int]) -> typing.Optional[dict]: """ Fetch ticket by its ID. :param ticket_id: ID of demanded ticket :returns: Dictionary with key, value pairs for ticket with *ticket_id* or None if ticket does not exist. List of keys: * id * numerical_id * Queue * Owner * Creator * Subject * Status * Priority * InitialPriority * FinalPriority * Requestors * Cc * AdminCc * Created * Starts * Started * Due * Resolved * Told * TimeEstimated * TimeWorked * TimeLeft :raises UnexpectedMessageFormat: Unexpected format of returned message. """ msg = self.__request('ticket/{}/show'.format(str(ticket_id), )) status_code = self.__get_status_code(msg) if status_code is not None and status_code == 200: pairs = {} msg = msg.split('\n') if (len(msg) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(msg[2]): return None req_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['requestors_pattern'].match(m)] req_id = req_matching[0] if req_matching else None if not req_id: raise UnexpectedMessageFormat('Missing line starting with `Requestors:`.') for i in range(req_id): if ': ' in msg[i]: header, content = self.split_header(msg[i]) pairs[header.strip()] = content.strip() requestors = [msg[req_id][12:]] req_id += 1 while (req_id < len(msg)) and (msg[req_id][:12] == ' ' * 12): requestors.append(msg[req_id][12:]) req_id += 1 pairs['Requestors'] = self.__normalize_list(requestors) for i in range(req_id, len(msg)): if ': ' in msg[i]: header, content = self.split_header(msg[i]) pairs[header.strip()] = content.strip() if 'Cc' in pairs: pairs['Cc'] = self.__normalize_list(pairs['Cc']) if 'AdminCc' in pairs: pairs['AdminCc'] = self.__normalize_list(pairs['AdminCc']) if 'id' not in pairs and not pairs['id'].startswith('ticket/'): raise UnexpectedMessageFormat('Response from RT didn\'t contain a valid ticket_id') pairs['numerical_id'] = pairs['id'].split('ticket/')[1] return pairs raise UnexpectedMessageFormat('Received status code is {} instead of 200.'.format(status_code)) @staticmethod def __ticket_post_data(data_source: dict) -> str: """Convert a dictionary of RT ticket data into a REST POST data string. :param data_source: Dictionary with ticket fields and values. :returns: Equivalent string to POST to the RT REST interface. """ post_data = [] for key in data_source: if key.startswith('CF_'): rt_key = 'CF.{{{}}}'.format(key[3:]) else: rt_key = key value = data_source[key] if isinstance(value, (list, tuple)): value = ', '.join(value) value_lines = iter(value.splitlines()) post_data.append('{}: {}'.format(rt_key, next(value_lines, ''))) post_data.extend(' ' + line for line in value_lines) return '\n'.join(post_data) def create_ticket(self, Queue: typing.Optional[typing.Union[str, object]] = None, files: typing.Optional[typing.List[typing.Tuple[str, typing.IO, typing.Optional[str]]]] = None, **kwargs: typing.Any) -> int: """ Create new ticket and set given parameters. Example of message sended to ``http://tracker.example.com/REST/1.0/ticket/new``:: content=id: ticket/new Queue: General Owner: Nobody Requestors: somebody@example.com Subject: Ticket created through REST API Text: Lorem Ipsum In case of success returned message has this form:: RT/3.8.7 200 Ok # Ticket 123456 created. # Ticket 123456 updated. Otherwise:: RT/3.8.7 200 Ok # Required: id, Queue + list of some key, value pairs, probably default values. :keyword Queue: Queue where to create ticket :keyword files: Files to attach as multipart/form-data List of 2/3 tuples: (filename, file-like object, [content type]) :keyword kwargs: Other arguments possible to set: Requestors, Subject, Cc, AdminCc, Owner, Status, Priority, InitialPriority, FinalPriority, TimeEstimated, Starts, Due, Text,... (according to RT fields) Custom fields CF.{} could be set with keywords CF_CustomFieldName. :returns: ID of new ticket or ``-1``, if creating failed """ kwargs['id'] = 'ticket/new' kwargs['Queue'] = Queue or self.default_queue post_data = self.__ticket_post_data(kwargs) if files: for file_info in files: post_data += "\nAttachment: {}".format(file_info[0], ) msg = self.__request('ticket/new', post_data={'content': post_data}, files=files) for line in msg.split('\n')[2:-1]: res = self.RE_PATTERNS['ticket_created_pattern'].match(line) if res is not None: return int(res.group(1)) warnings.warn(line[2:]) return -1 def edit_ticket(self, ticket_id: typing.Union[str, int], **kwargs: typing.Any) -> bool: """ Edit ticket values. :param ticket_id: ID of ticket to edit :keyword kwargs: Other arguments possible to set: Requestors, Subject, Cc, AdminCc, Owner, Status, Priority, InitialPriority, FinalPriority, TimeEstimated, Starts, Due, Text,... (according to RT fields) Custom fields CF.{} could be set with keywords CF_CustomFieldName. :returns: ``True`` Operation was successful ``False`` Ticket with given ID does not exist or unknown parameter was set (in this case all other valid fields are changed) """ post_data = self.__ticket_post_data(kwargs) msg = self.__request('ticket/{}/edit'.format(str(ticket_id)), post_data={'content': post_data}) if "" == msg: # Ticket not modified return True state = msg.split('\n')[2] return self.RE_PATTERNS['update_pattern'].match(state) is not None def get_history(self, ticket_id: typing.Union[str, int], transaction_id: typing.Optional[typing.Union[str, int]] = None) -> typing.Optional[typing.List[dict]]: """ Get set of history items. :param ticket_id: ID of ticket :keyword transaction_id: If set to None, all history items are returned, if set to ID of valid transaction just one history item is returned :returns: List of history items ordered increasingly by time of event. Each history item is dictionary with following keys: Description, Creator, Data, Created, TimeTaken, NewValue, Content, Field, OldValue, Ticket, Type, id, Attachments All these fields are strings, just 'Attachments' holds list of pairs (attachment_id,filename_with_size). Returns None if ticket or transaction does not exist. :raises UnexpectedMessageFormat: Unexpected format of returned message. """ if transaction_id is None: # We are using "long" format to get all history items at once. # Each history item is then separated by double dash. msgs = self.__request('ticket/{}/history?format=l'.format(str(ticket_id), )) else: msgs = self.__request('ticket/{}/history/id/{}'.format(str(ticket_id), str(transaction_id))) lines = msgs.split('\n') if (len(lines) > 2) and ( self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]) or self.RE_PATTERNS['not_related_pattern'].match( lines[2])): return None msgs = msgs.split('\n--\n') items = [] for msg in msgs: pairs = {} # type: dict msg = msg.split('\n') cont_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['content_pattern'].match(m)] cont_id = cont_matching[0] if cont_matching else None if not cont_id: raise UnexpectedMessageFormat('Unexpected history entry. \ Missing line starting with `Content:`.') atta_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['attachments_pattern'].match(m)] atta_id = atta_matching[0] if atta_matching else None if not atta_id: raise UnexpectedMessageFormat('Unexpected attachment part of history entry. \ Missing line starting with `Attachements:`.') for i in range(cont_id): if ': ' in msg[i]: header, content = self.split_header(msg[i]) pairs[header.strip()] = content.strip() content = msg[cont_id][9:] cont_id += 1 while (cont_id < len(msg)) and (msg[cont_id][:9] == ' ' * 9): content += '\n' + msg[cont_id][9:] cont_id += 1 pairs['Content'] = content for i in range(cont_id, atta_id): if ': ' in msg[i]: header, content = self.split_header(msg[i]) pairs[header.strip()] = content.strip() attachments = [] for i in range(atta_id + 1, len(msg)): if ': ' in msg[i]: header, content = self.split_header(msg[i]) attachments.append((int(header), content.strip())) pairs['Attachments'] = attachments items.append(pairs) return items def get_short_history(self, ticket_id: typing.Union[str, int]) -> typing.Optional[typing.List[typing.Tuple[int, str]]]: """ Get set of short history items :param ticket_id: ID of ticket :returns: List of history items ordered increasingly by time of event. Each history item is a tuple containing (id, Description). Returns None if ticket does not exist. """ msg = self.__request('ticket/{}/history'.format(str(ticket_id), )) items = [] lines = msg.split('\n') multiline_buffer = "" in_multiline = False if self.__get_status_code(lines[0]) == 200: if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]): return None if len(lines) >= 4: for line in lines[4:]: if line == "": if not in_multiline: # start of multiline block in_multiline = True else: # end of multiline block line = multiline_buffer multiline_buffer = "" in_multiline = False else: if in_multiline: multiline_buffer += line line = "" if ': ' in line: hist_id, desc = line.split(': ', 1) items.append((int(hist_id), desc)) return items def __correspond(self, ticket_id: typing.Union[str, int], text: str = '', action: str = 'correspond', cc: str = '', bcc: str = '', content_type: str = 'text/plain', files: typing.Optional[typing.List[typing.Tuple[str, typing.IO, typing.Optional[str]]]] = None): """ Sends out the correspondence :param ticket_id: ID of ticket to which message belongs :keyword text: Content of email message :keyword action: correspond or comment :keyword content_type: Content type of email message, default to text/plain :keyword cc: Carbon copy just for this reply :keyword bcc: Blind carbon copy just for this reply :keyword files: Files to attach as multipart/form-data List of 2/3 tuples: (filename, file-like object, [content type]) :returns: ``True`` Operation was successful ``False`` Sending failed (status code != 200) :raises BadRequest: When ticket does not exist """ post_data = {'content': """id: {} Action: {} Text: {} Cc: {} Bcc: {} Content-Type: {}""".format(str(ticket_id), action, re.sub(r'\n', r'\n ', text), cc, bcc, content_type)} if files: for file_info in files: post_data['content'] += "\nAttachment: {}".format(file_info[0], ) msg = self.__request('ticket/{}/comment'.format(str(ticket_id), ), post_data=post_data, files=files) return self.__get_status_code(msg) == 200 def reply(self, ticket_id: typing.Union[str, int], text: str = '', cc: str = '', bcc: str = '', content_type: str = 'text/plain', files: typing.Optional[typing.List[typing.Tuple[str, typing.IO, typing.Optional[str]]]] = None) -> bool: """ Sends email message to the contacts in ``Requestors`` field of given ticket with subject as is set in ``Subject`` field. Form of message according to documentation:: id: Action: correspond Text: the text comment second line starts with the same indentation as first Cc: <...> Bcc: <...> TimeWorked: <...> Attachment: an attachment filename/path :param ticket_id: ID of ticket to which message belongs :keyword text: Content of email message :keyword content_type: Content type of email message, default to text/plain :keyword cc: Carbon copy just for this reply :keyword bcc: Blind carbon copy just for this reply :keyword files: Files to attach as multipart/form-data List of 2/3 tuples: (filename, file-like object, [content type]) :returns: ``True`` Operation was successful ``False`` Sending failed (status code != 200) :raises BadRequest: When ticket does not exist """ return self.__correspond(ticket_id, text, 'correspond', cc, bcc, content_type, files) def comment(self, ticket_id: typing.Union[str, int], text: str = '', cc: str = '', bcc: str = '', content_type: str = 'text/plain', files: typing.Optional[typing.List[typing.Tuple[str, typing.IO, typing.Optional[str]]]] = None) -> bool: """ Adds comment to the given ticket. Form of message according to documentation:: id: Action: comment Text: the text comment second line starts with the same indentation as first Attachment: an attachment filename/path Example:: >>> tracker = Rt('http://tracker.example.com/REST/1.0/', 'rt-username', 'top-secret') >>> attachment_name = sys.argv[1] >>> message_text = ' '.join(sys.argv[2:]) >>> ret = tracker.comment(ticket_id, text=message_text, ... files=[(attachment_name, open(attachment_name, 'rb'))]) >>> if not ret: ... print('Error: could not send attachment', file=sys.stderr) ... exit(1) :param ticket_id: ID of ticket to which comment belongs :keyword text: Content of comment :keyword content_type: Content type of comment, default to text/plain :keyword files: Files to attach as multipart/form-data List of 2/3 tuples: (filename, file-like object, [content type]) :returns: ``True`` Operation was successful ``False`` Sending failed (status code != 200) :raises BadRequest: When ticket does not exist """ return self.__correspond(ticket_id, text, 'comment', cc, bcc, content_type, files) def get_attachments(self, ticket_id: typing.Union[str, int]) -> typing.Optional[typing.List[typing.Tuple[str, str, str, str]]]: """ Get attachment list for a given ticket :param ticket_id: ID of ticket :returns: List of tuples for attachments belonging to given ticket. Tuple format: (id, name, content_type, size) Returns None if ticket does not exist. """ msg = self.__request('ticket/{}/attachments'.format(str(ticket_id), )) lines = msg.split('\n') if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]): return None attachment_infos = [] if (self.__get_status_code(lines[0]) == 200) and (len(lines) >= 4): for line in lines[4:]: info = self.RE_PATTERNS['attachments_list_pattern'].match(line) if info: attachment_infos.append(info.groups()) return attachment_infos # type: ignore # type returned by the regex, if it matches, is as defined above def get_attachments_ids(self, ticket_id: typing.Union[str, int]) -> typing.Optional[typing.List[int]]: """ Get IDs of attachments for given ticket. :param ticket_id: ID of ticket :returns: List of IDs (type int) of attachments belonging to given ticket. Returns None if ticket does not exist. """ attachments = self.get_attachments(ticket_id) return [int(at[0]) for at in attachments] if attachments is not None else None def get_attachment(self, ticket_id: typing.Union[str, int], attachment_id: typing.Union[str, int]) -> \ typing.Optional[dict]: """ Get attachment. :param ticket_id: ID of ticket :param attachment_id: ID of attachment for obtain :returns: Attachment as dictionary with these keys: * Transaction * ContentType * Parent * Creator * Created * Filename * Content (bytes type) * Headers * MessageId * ContentEncoding * id * Subject All these fields are strings, just 'Headers' holds another dictionary with attachment headers as strings e.g.: * Delivered-To * From * Return-Path * Content-Length * To * X-Seznam-User * X-QM-Mark * Domainkey-Signature * RT-Message-ID * X-RT-Incoming-Encryption * X-Original-To * Message-ID * X-Spam-Status * In-Reply-To * Date * Received * X-Country * X-Spam-Checker-Version * X-Abuse * MIME-Version * Content-Type * Subject .. warning:: Content-Length parameter is set after opening ticket in web interface! Set of headers available depends on mailservers sending emails not on Request Tracker! Returns None if ticket or attachment does not exist. :raises UnexpectedMessageFormat: Unexpected format of returned message. """ msg = self.__request('ticket/{}/attachments/{}'.format(str(ticket_id), str(attachment_id)), text_response=False) msg = msg.split(b'\n') if (len(msg) > 2) and ( self.RE_PATTERNS['invalid_attachment_pattern_bytes'].match(msg[2]) or self.RE_PATTERNS['does_not_exist_pattern_bytes'].match(msg[2])): return None msg = msg[2:] head_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['headers_pattern_bytes'].match(m)] head_id = head_matching[0] if head_matching else None if not head_id: raise UnexpectedMessageFormat('Unexpected headers part of attachment entry. \ Missing line starting with `Headers:`.') msg[head_id] = re.sub(b'^Headers: (.*)$', r'\1', msg[head_id]) cont_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['content_pattern_bytes'].match(m)] if not cont_matching: raise UnexpectedMessageFormat('Unexpected content part of attachment entry. \ Missing line starting with `Content:`.') cont_id = cont_matching[0] pairs = {} for i in range(head_id): if b': ' in msg[i]: header, content = msg[i].split(b': ', 1) pairs[header.strip().decode('utf-8')] = content.strip().decode('utf-8') headers = {} for i in range(head_id, cont_id): if b': ' in msg[i]: header, content = msg[i].split(b': ', 1) headers[header.strip().decode('utf-8')] = content.strip().decode('utf-8') pairs['Headers'] = headers content = msg[cont_id][9:] for i in range(cont_id + 1, len(msg)): if msg[i][:9] == (b' ' * 9): content += b'\n' + msg[i][9:] pairs['Content'] = content return pairs def get_attachment_content(self, ticket_id: typing.Union[str, int], attachment_id: typing.Union[str, int]) -> \ typing.Optional[bytes]: """ Get content of attachment without headers. This function is necessary to use for binary attachment, as it can contain ``\\n`` chars, which would disrupt parsing of message if :py:meth:`~Rt.get_attachment` is used. Format of message:: RT/3.8.7 200 Ok\n\nStart of the content...End of the content\n\n\n :param ticket_id: ID of ticket :param attachment_id: ID of attachment Returns: Bytes with content of attachment or None if ticket or attachment does not exist. """ msg = self.__request('ticket/{}/attachments/{}/content'.format (str(ticket_id), str(attachment_id)), text_response=False) lines = msg.split(b'\n', 3) if (len(lines) == 4) and ( self.RE_PATTERNS['invalid_attachment_pattern_bytes'].match(lines[2]) or self.RE_PATTERNS['does_not_exist_pattern_bytes'].match(lines[2])): return None return msg[msg.find(b'\n') + 2:-3] def get_user(self, user_id) -> typing.Optional[typing.Dict[str, str]]: """ Get user details. :param user_id: Identification of user by username (str) or user ID (int) :returns: User details as strings in dictionary with these keys for RT users: * Lang * RealName * Privileged * Disabled * Gecos * EmailAddress * Password * id * Name Or these keys for external users (e.g. Requestors replying to email from RT: * RealName * Disabled * EmailAddress * Password * id * Name None is returned if user does not exist. :raises UnexpectedMessageFormat: In case that returned status code is not 200 """ msg = self.__request('user/{}'.format(str(user_id), )) status_code = self.__get_status_code(msg) if status_code is not None and status_code == 200: pairs = {} lines = msg.split('\n') if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]): return None for line in lines[2:]: if ': ' in line: header, content = line.split(': ', 1) pairs[header.strip()] = content.strip() return pairs raise UnexpectedMessageFormat('Received status code is {} instead of 200.'.format(status_code)) def create_user(self, Name: str, EmailAddress: str, **kwargs: typing.Any) -> typing.Union[int, bool]: """ Create user (undocumented API feature). :param Name: User name (login for privileged, required) :param EmailAddress: Email address (required) :param kwargs: Optional fields to set (see edit_user) :returns: ID of new user or False when create fails :raises BadRequest: When user already exists :raises InvalidUse: When invalid fields are set """ return self.edit_user('new', Name=Name, EmailAddress=EmailAddress, **kwargs) def edit_user(self, user_id: typing.Union[str, int], **kwargs: typing.Any) -> typing.Union[int, bool]: """ Edit user profile (undocumented API feature). :param user_id: Identification of user by username (str) or user ID (int) :param kwargs: Other fields to edit from the following list: * Name * Password * EmailAddress * RealName * NickName * Gecos * Organization * Address1 * Address2 * City * State * Zip * Country * HomePhone * WorkPhone * MobilePhone * PagerPhone * ContactInfo * Comments * Signature * Lang * EmailEncoding * WebEncoding * ExternalContactInfoId * ContactInfoSystem * ExternalAuthId * AuthSystem * Privileged * Disabled :returns: ID of edited user or False when edit fails :raises BadRequest: When user does not exist :raises InvalidUse: When invalid fields are set """ valid_fields = {'name', 'password', 'emailaddress', 'realname', 'nickname', 'gecos', 'organization', 'address1', 'address2', 'city', 'state', 'zip', 'country', 'homephone', 'workphone', 'mobilephone', 'pagerphone', 'contactinfo', 'comments', 'signature', 'lang', 'emailencoding', 'webencoding', 'externalcontactinfoid', 'contactinfosystem', 'externalauthid', 'authsystem', 'privileged', 'disabled'} used_fields = set(map(lambda x: x.lower(), kwargs.keys())) if not used_fields <= valid_fields: invalid_fields = ", ".join(list(used_fields - valid_fields)) raise InvalidUse("Unsupported names of fields: {}.".format(invalid_fields)) post_data = 'id: user/{}\n'.format(str(user_id)) for key, val in kwargs.items(): post_data += '{}: {}\n'.format(key, val) msg = self.__request('edit', post_data={'content': post_data}) msgs = msg.split('\n') if (self.__get_status_code(msg) == 200) and (len(msgs) > 2): match = self.RE_PATTERNS['user_pattern'].match(msgs[2]) if match: return int(match.group(1)) return False def get_queue(self, queue_id: typing.Union[str, int]) -> typing.Optional[typing.Dict[str, str]]: """ Get queue details. :param queue_id: Identification of queue by name (str) or queue ID (int) :returns: Queue details as strings in dictionary with these keys if queue exists (otherwise None): * id * Name * Description * CorrespondAddress * CommentAddress * InitialPriority * FinalPriority * DefaultDueIn :raises UnexpectedMessageFormat: In case that returned status code is not 200 """ msg = self.__request('queue/{}'.format(str(queue_id))) status_code = self.__get_status_code(msg) if status_code is not None and status_code == 200: pairs = {} lines = msg.split('\n') if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]): return None for line in lines[2:]: if ': ' in line: header, content = line.split(': ', 1) pairs[header.strip()] = content.strip() return pairs raise UnexpectedMessageFormat('Received status code is {} instead of 200.'.format(status_code)) def edit_queue(self, queue_id: typing.Union[str, int], **kwargs: typing.Any) -> typing.Union[str, bool]: """ Edit queue (undocumented API feature). :param queue_id: Identification of queue by name (str) or ID (int) :param kwargs: Other fields to edit from the following list: * Name * Description * CorrespondAddress * CommentAddress * InitialPriority * FinalPriority * DefaultDueIn :returns: ID or name of edited queue or False when edit fails :raises BadRequest: When queue does not exist :raises InvalidUse: When invalid fields are set """ valid_fields = {'name', 'description', 'correspondaddress', 'commentaddress', 'initialpriority', 'finalpriority', 'defaultduein'} used_fields = set(map(lambda x: x.lower(), kwargs.keys())) if not used_fields <= valid_fields: invalid_fields = ", ".join(list(used_fields - valid_fields)) raise InvalidUse("Unsupported names of fields: {}.".format(invalid_fields)) post_data = 'id: queue/{}\n'.format(str(queue_id)) for key, val in kwargs.items(): post_data += '{}: {}\n'.format(key, val) msg = self.__request('edit', post_data={'content': post_data}) msgs = msg.split('\n') if (self.__get_status_code(msg) == 200) and (len(msgs) > 2): match = self.RE_PATTERNS['queue_pattern'].match(msgs[2]) if match: return match.group(1) return False def create_queue(self, Name: str, **kwargs: typing.Any) -> int: """ Create queue (undocumented API feature). :param Name: Queue name (required) :param kwargs: Optional fields to set (see edit_queue) :returns: ID of new queue or False when create fails :raises BadRequest: When queue already exists :raises InvalidUse: When invalid fields are set """ return int(self.edit_queue('new', Name=Name, **kwargs)) def get_links(self, ticket_id: typing.Union[str, int]) -> typing.Optional[typing.Dict[str, typing.List[str]]]: """ Gets the ticket links for a single ticket. :param ticket_id: ticket ID :returns: Links as lists of strings in dictionary with these keys (just those which are defined): * id * Members * MemberOf * RefersTo * ReferredToBy * DependsOn * DependedOnBy None is returned if ticket does not exist. :raises UnexpectedMessageFormat: In case that returned status code is not 200 """ msg = self.__request('ticket/{}/links/show'.format(str(ticket_id), )) status_code = self.__get_status_code(msg) if status_code is not None and status_code == 200: pairs = {} msg = msg.split('\n') if (len(msg) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(msg[2]): return None i = 2 while i < len(msg): if ': ' in msg[i]: key, link = self.split_header(msg[i]) links = [link.strip()] j = i + 1 pad = len(key) + 2 # loop over next lines for the same key while (j < len(msg)) and msg[j].startswith(' ' * pad): links[-1] = links[-1][:-1] # remove trailing comma from previous item links.append(msg[j][pad:].strip()) j += 1 pairs[key] = links i = j - 1 i += 1 return pairs raise UnexpectedMessageFormat('Received status code is {} instead of 200.'.format(status_code)) def edit_ticket_links(self, ticket_id: typing.Union[str, int], **kwargs: typing.Any) -> bool: """ Edit ticket links. .. warning:: This method is deprecated in favour of edit_link method, because there exists bug in RT 3.8 REST API causing mapping created links to ticket/1. The only drawback is that edit_link cannot process multiple links all at once. :param ticket_id: ID of ticket to edit :keyword kwargs: Other arguments possible to set: DependsOn, DependedOnBy, RefersTo, ReferredToBy, Members, MemberOf. Each value should be either ticker ID or external link. Int types are converted. Use empty string as value to delete existing link. :returns: ``True`` Operation was successful ``False`` Ticket with given ID does not exist or unknown parameter was set (in this case all other valid fields are changed) """ post_data = '' for key in kwargs: post_data += "{}: {}\n".format(key, str(kwargs[key])) msg = self.__request('ticket/{}/links'.format(str(ticket_id), ), post_data={'content': post_data}) state = msg.split('\n')[2] return self.RE_PATTERNS['links_updated_pattern'].match(state) is not None def edit_link(self, ticket_id: typing.Union[str, int], link_name: str, link_value: typing.Union[str, int], delete: bool = False) -> bool: """ Creates or deletes a link between the specified tickets (undocumented API feature). :param ticket_id: ID of ticket to edit :param link_name: Name of link to edit (DependsOn, DependedOnBy, RefersTo, ReferredToBy, HasMember or MemberOf) :param link_value: Either ticker ID or external link. :param delete: if True the link is deleted instead of created :returns: ``True`` Operation was successful ``False`` Ticket with given ID does not exist or link to delete is not found :raises InvalidUse: When none or more then one links are specified. Also when wrong link name is used. """ valid_link_names = {'dependson', 'dependedonby', 'refersto', 'referredtoby', 'hasmember', 'memberof'} if not link_name.lower() in valid_link_names: raise InvalidUse("Unsupported name of link.") post_data = {'rel': link_name.lower(), 'to': link_value, 'id': ticket_id, 'del': 1 if delete else 0 } msg = self.__request('ticket/link', post_data=post_data) state = msg.split('\n')[2] if delete: return self.RE_PATTERNS['deleted_link_pattern'].match(state) is not None return self.RE_PATTERNS['created_link_pattern'].match(state) is not None def merge_ticket(self, ticket_id: typing.Union[str, int], into_id: typing.Union[str, int]) -> bool: """ Merge ticket into another (undocumented API feature). :param ticket_id: ID of ticket to be merged :param into: ID of destination ticket :returns: ``True`` Operation was successful ``False`` Either origin or destination ticket does not exist or user does not have ModifyTicket permission. """ msg = self.__request('ticket/{}/merge/{}'.format(str(ticket_id), str(into_id))) state = msg.split('\n')[2] return self.RE_PATTERNS['merge_successful_pattern'].match(state) is not None def take(self, ticket_id: typing.Union[str, int]) -> bool: """ Take ticket :param ticket_id: ID of ticket to be merged :returns: ``True`` Operation was successful ``False`` Either the ticket does not exist or user does not have TakeTicket permission. """ post_data = {'content': "Ticket: {}\nAction: take".format(str(ticket_id))} msg = self.__request('ticket/{}/take'.format(str(ticket_id)), post_data=post_data) return self.__get_status_code(msg) == 200 def steal(self, ticket_id: typing.Union[str, int]) -> bool: """ Steal ticket :param ticket_id: ID of ticket to be merged :returns: ``True`` Operation was successful ``False`` Either the ticket does not exist or user does not have StealTicket permission. """ post_data = {'content': "Ticket: {}\nAction: steal".format(str(ticket_id))} msg = self.__request('ticket/{}/take'.format(str(ticket_id)), post_data=post_data) return self.__get_status_code(msg) == 200 def untake(self, ticket_id: typing.Union[str, int]) -> bool: """ Untake ticket :param ticket_id: ID of ticket to be merged :returns: ``True`` Operation was successful ``False`` Either the ticket does not exist or user does not own the ticket. """ post_data = {'content': "Ticket: {}\nAction: untake".format(str(ticket_id))} msg = self.__request('ticket/{}/take'.format(str(ticket_id)), post_data=post_data) return self.__get_status_code(msg) == 200 @staticmethod def split_header(line: str) -> typing.Sequence[str]: """ Split a header line into field name and field value. Note that custom fields may contain colons inside the curly braces, so we need a special test for them. :param line: A message line to be split. :returns: (Field name, field value) tuple. """ match = re.match(r'^(CF\.\{.*?}): (.*)$', line) if match: return (match.group(1), match.group(2)) return line.split(': ', 1) python-rt-2.0.1/setup.cfg000066400000000000000000000001641374333121300153000ustar00rootroot00000000000000[bdist_wheel] universal = 0 [pycodestyle] filename = rt/rt.py ignore = E501 [egg_info] tag_build = tag_date = 0 python-rt-2.0.1/setup.py000066400000000000000000000021401374333121300151650ustar00rootroot00000000000000import os from setuptools import setup here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() setup(name='rt', version='2.0.1', description='Python interface to Request Tracker API', long_description=README, license='GNU General Public License (GPL)', author='Jiri Machalek', author_email='edvard.rejthar@nic.cz', url='https://github.com/CZ-NIC/python-rt', install_requires=['requests'], packages=['rt'], package_data={'rt': ['py.typed']}, zip_safe=False, python_requires='>=3.5', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules' ] ) python-rt-2.0.1/test_rt.py000066400000000000000000000242231374333121300155170ustar00rootroot00000000000000"""Tests for Rt - Python interface to Request Tracker :term:`API`""" __license__ = """ Copyright (C) 2013 CZ.NIC, z.s.p.o. 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 . """ __docformat__ = "reStructuredText en" __authors__ = [ '"Jiri Machalek" ' ] import random import string import unittest import rt class RtTestCase(unittest.TestCase): rt.DEBUG_MODE = True RT_VALID_CREDENTIALS = { 'RT4.4 stable': { 'url': "http://localhost:8080/REST/1.0/", 'support': { 'default_login': 'root', 'default_password': 'password', }, }, # HTTP timeout # 'RT4.6 dev': { # 'url': 'http://rt.easter-eggs.org/demos/4.6/REST/1.0', # 'admin': { # 'default_login': 'administrateur', # 'default_password': 'administrateur', # }, # 'john.foo': { # 'default_login': 'support', # 'default_password': 'support', # } # }, } RT_INVALID_CREDENTIALS = { 'RT4.4 stable (bad credentials)': { 'url': "http://localhost:8080/REST/1.0/", 'default_login': 'idontexist', 'default_password': 'idonthavepassword', }, } RT_MISSING_CREDENTIALS = { 'RT4.4 stable (missing credentials)': { 'url': "http://localhost:8080/REST/1.0/", }, } RT_BAD_URL = { 'RT (bad url)': { 'url': 'http://httpbin.org/status/404', 'default_login': 'idontexist', 'default_password': 'idonthavepassword', }, } def _have_creds(*creds_seq): return all(creds[name].get('url') for creds in creds_seq for name in creds) @unittest.skipUnless(_have_creds(RT_VALID_CREDENTIALS, RT_INVALID_CREDENTIALS, RT_MISSING_CREDENTIALS, RT_BAD_URL), "missing credentials required to run test") def test_login_and_logout(self): for name in self.RT_VALID_CREDENTIALS: tracker = rt.Rt(self.RT_VALID_CREDENTIALS[name]['url'], **self.RT_VALID_CREDENTIALS[name]['support']) self.assertTrue(tracker.login(), 'Invalid login to RT demo site ' + name) self.assertTrue(tracker.logout(), 'Invalid logout from RT demo site ' + name) for name, params in self.RT_INVALID_CREDENTIALS.items(): tracker = rt.Rt(**params) self.assertFalse(tracker.login(), 'Login to RT demo site ' + name + ' should fail but did not') self.assertRaises(rt.AuthorizationError, lambda: tracker.search()) for name, params in self.RT_MISSING_CREDENTIALS.items(): tracker = rt.Rt(**params) self.assertRaises(rt.AuthorizationError, lambda: tracker.login()) for name, params in self.RT_BAD_URL.items(): tracker = rt.Rt(**params) self.assertRaises(rt.UnexpectedResponse, lambda: tracker.login()) @unittest.skipUnless(_have_creds(RT_VALID_CREDENTIALS), "missing credentials required to run test") def test_ticket_operations(self): ticket_subject = 'Testing issue ' + "".join([random.choice(string.ascii_letters) for i in range(15)]) ticket_text = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' for name in ('RT4.4 stable',): url = self.RT_VALID_CREDENTIALS[name]['url'] default_login = self.RT_VALID_CREDENTIALS[name]['support']['default_login'] default_password = self.RT_VALID_CREDENTIALS[name]['support']['default_password'] tracker = rt.Rt(url, default_login=default_login, default_password=default_password) self.assertTrue(tracker.login(), 'Invalid login to RT demo site ' + name) # empty search result search_result = tracker.search(Subject=ticket_subject) self.assertEqual(search_result, [], 'Search for ticket with random subject returned non empty list.') # create ticket_id = tracker.create_ticket(Subject=ticket_subject, Text=ticket_text) self.assertTrue(ticket_id > -1, 'Creating ticket failed.') # search search_result = tracker.search(Subject=ticket_subject) self.assertEqual(len(search_result), 1, 'Created ticket is not found by the subject.') self.assertEqual(search_result[0]['id'], 'ticket/' + str(ticket_id), 'Bad id in search result of just created ticket.') self.assertEqual(search_result[0]['Status'], 'new', 'Bad status in search result of just created ticket.') # search all queues search_result = tracker.search(Queue=rt.ALL_QUEUES, Subject=ticket_subject) self.assertEqual(search_result[0]['id'], 'ticket/' + str(ticket_id), 'Bad id in search result of just created ticket.') # raw search search_result = tracker.search(raw_query='Subject="{}"'.format(ticket_subject)) self.assertEqual(len(search_result), 1, 'Created ticket is not found by the subject.') self.assertEqual(search_result[0]['id'], 'ticket/' + str(ticket_id), 'Bad id in search result of just created ticket.') self.assertEqual(search_result[0]['Status'], 'new', 'Bad status in search result of just created ticket.') # raw search all queues search_result = tracker.search(Queue=rt.ALL_QUEUES, raw_query='Subject="{}"'.format(ticket_subject)) self.assertEqual(search_result[0]['id'], 'ticket/' + str(ticket_id), 'Bad id in search result of just created ticket.') # get ticket ticket = tracker.get_ticket(ticket_id) self.assertEqual(ticket, search_result[0], 'Ticket get directly by its id is not equal to previous search result.') # edit ticket requestors = ['tester1@example.com', 'tester2@example.com'] tracker.edit_ticket(ticket_id, Status='open', Requestors=requestors) # get ticket (edited) ticket = tracker.get_ticket(ticket_id) self.assertEqual(ticket['Status'], 'open', 'Ticket status was not changed to open.') self.assertEqual(ticket['Requestors'], requestors, 'Ticket requestors were not added properly.') # get history hist = tracker.get_history(ticket_id) self.assertTrue(len(hist) > 0, 'Empty ticket history.') self.assertEqual(hist[0]['Content'], ticket_text, 'Ticket text was not receives is it was submited.') # get_short_history short_hist = tracker.get_short_history(ticket_id) self.assertTrue(len(short_hist) > 0, 'Empty ticket short history.') self.assertEqual(short_hist[0][1], 'Ticket created by %s' % default_login) # create 2nd ticket ticket2_subject = 'Testing issue ' + "".join([random.choice(string.ascii_letters) for i in range(15)]) ticket2_id = tracker.create_ticket(Subject=ticket2_subject) self.assertTrue(ticket2_id > -1, 'Creating 2nd ticket failed.') # edit link self.assertTrue(tracker.edit_link(ticket_id, 'DependsOn', ticket2_id)) # get links links1 = tracker.get_links(ticket_id) self.assertTrue('DependsOn' in links1, 'Missing just created link DependsOn.') self.assertTrue(links1['DependsOn'][0].endswith('ticket/' + str(ticket2_id)), 'Unexpected value of link DependsOn.') links2 = tracker.get_links(ticket2_id) self.assertTrue('DependedOnBy' in links2, 'Missing just created link DependedOnBy.') self.assertTrue(links2['DependedOnBy'][0].endswith('ticket/' + str(ticket_id)), 'Unexpected value of link DependedOnBy.') # reply with attachment attachment_content = b'Content of attachment.' attachment_name = 'attachment-name.txt' reply_text = 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' # should provide a content type as RT 4.0 type guessing is broken (missing use statement for guess_media_type in REST.pm) self.assertTrue(tracker.reply(ticket_id, text=reply_text, files=[(attachment_name, attachment_content, 'text/plain')]), 'Reply to ticket returned False indicating error.') # attachments list at_list = tracker.get_attachments(ticket_id) self.assertTrue(at_list, 'Empty list with attachment ids, something went wrong.') at_names = [at[1] for at in at_list] self.assertTrue(attachment_name in at_names, 'Attachment name is not in the list of attachments.') # get the attachment and compare it's content at_id = at_list[at_names.index(attachment_name)][0] at_content = tracker.get_attachment_content(ticket_id, at_id) self.assertEqual(at_content, attachment_content, 'Recorded attachment is not equal to the original file.') # merge tickets self.assertTrue(tracker.merge_ticket(ticket2_id, ticket_id), 'Merging tickets failed.') # delete ticket self.assertTrue(tracker.edit_ticket(ticket_id, Status='deleted'), 'Ticket delete failed.') # get user self.assertIn('@', tracker.get_user(default_login)['EmailAddress']) if __name__ == '__main__': unittest.main()