././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1725658667.0468843 rt-3.2.0/0000755000175100001770000000000014666673053011566 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/.codespell_ignore0000644000175100001770000000002414666673042015076 0ustar00runnerdockerrequestor requestors././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/.editorconfig0000644000175100001770000000042014666673042014235 0ustar00runnerdockerroot = true [*] charset = utf-8 end_of_line = lf indent_style = space [{*.pyw,*.py}] indent_size = 4 tab_width = 4 max_line_length = 140 ij_continuation_indent_size = 4 ij_python_blank_line_at_file_end = true [{*.yml_sample,*.yaml_sample,*.yml,*.yaml}] indent_size = 2 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/AUTHORS0000644000175100001770000000036414666673042012637 0ustar00runnerdockerDevelopment Lead: community Maintainer: - Georges Toth Someone with write permissions - Edvard Rejthar Patches and Suggestions: - Stewart Perrygrove Original Author: - Jiří Machálek ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/CHANGELOG.md0000644000175100001770000002042514666673042013400 0ustar00runnerdocker# Changelog All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [v3.2.0], 2024-09-06 ## Added - Added option for custom list of fields to be populated for search "query_format" param to avoid unnecessary round trips to get fields like Told, Starts, Resolved, etc by returning the required fields during search. (see #97 @nerdfirefighter) ## [v3.1.4], 2024-02-16 ### Fixes - Add a workaround for a breaking change introduced in RT5.0.5 which returns undefined pages variable for non-superusers (see #93 #94). ## [v3.1.3], 2023-10-10 ### Fixes - Fix an issue where no e-mail was sent on ticket creation due to suggesting to use **Requestors** instead of **Requestor** (https://github.com/python-rt/python-rt/pull/92). ## [v3.1.2], 2023-09-25 ### Fixes - Revert breaking change for python3.8 (collections.abc.AsyncIterator is not subscriptable). ## [v3.1.1], 2023-09-25 ### Fixes - In AsyncRt, instead of returning sequences, return AsyncIterators. ## [v3.1.0], 2023-09-25 ### Changes - Replace *requests* with *httpx* for the REST2 part. ### Added - Add a new *AsyncRt* class which implements the RT REST2 API in asnyc. - Adapt tests to include thew new async parts of this library. ## [v3.0.7], 2023-07-27 ### Fixes - Fix sorting when using search() method (#90) ## [v3.0.6], 2023-06-21 ### Fixes - Fixed bug in rest1 (#86) ## [v3.0.5], 2023-02-02 ### Added - Added support for specifying custom fields on user creation/edit (#82). ## [v3.0.4], 2022-11-08 ### Fixes - Workaround for parsing issues with tickets with only 1 attachment (#80), due to probably an upstream bug. ## [v3.0.3], 2022-06-16 ### Changes - Move package metadata and configuration from setup.cfg to pyproject.toml. ## [v3.0.2], 2022-06-12 ### Fixes - Fix edit_user() response handling in case a user_id name (str) was passed instead of a number. ## [v3.0.1], 2022-05-26 ### Fixes - Make sure to include _hyperlinks in history items - On edit ticket, raise exception if user/queue does not exist ### Added - Add helper method for deleting tickets - Add tests ## [v3.0.0], 2022-05-17 The following is a major release of the `rt` library. There is support for the REST API version 1 as well as version 2. Please note that this release contains breaking changes and requires adaptations to existing code, even if you are sticking to version 1 of the API. These changes were necessary in order to properly support both API versions. ### Added - RT REST2 support was added and is mostly on par with the REST1 support (differences are a result of the REST2 API implementation differences in RT). REST2 is a modern API based on JSON exchanges and thus the complex parsing of responses and request construction are no longer needed. ### Changes - Existing exception classes were renamed to adhere to the naming convention (https://peps.python.org/pep-0008/#exception-names). - In case you do catch specific `rt` exceptions, a simple search/replace will do, see the changelog page in the documentation for details. - Importing the `rt` class changed in order to better accommodate the new `rest2` implementation. - Where one use to be able to import `rt` using: `from rt import Rt` you now have to use the following syntax: `from rt.rest1 import Rt` - Importing the `rt` module does no longer import all exceptions but only the core `RtError` exception. If you require other exceptions, please import them from `rt.exceptions`. - Use pytest instead of nose. ## [v2.2.2], 2022-04-08 - Fix bug in the get_ticket would omit certain fields in case they were empty instead of returning an empty list as was the previous behavior (#70). - Add tests for verifying correct return result for AdminCc, Cc and Requestor fields. ## [v2.2.1], 2021-11-26 - Fix bug in get_attachment_content which was a workaround for a bug in RT <=4.2 (trailing new-lines) but which was fixed in RT >=4.2. This made tests fail and return falsely stripped attachment content. ## [v2.2.0], 2021-11-15 - Search has a parameter fields that can be used to return only particular fields for tickets. In some cases I noticed it will improve the speed of the query completion if you only need specific fields (#65 by @kimmoal). ## [v2.1.1], 2021-03-23 - Fix support for custom field values containing newlines in API responses (#10, #11) (the previous change in v1.0.11 fixed API requests) (#64) ## [v2.1.0], 2021-02-25 - Add the possibility to provide cookies as dict to authenticate (#60) - Add 'Referer' header for CSRF check when cookies are used for authentication (#60) - Add IS and IS NOT operators to search (#57) ## [v2.0.1], 2020-08-07 - Fix UnicodeDecodeError in logging code for non-text attachments (#50, #51) - Documentation: Add a search example (#49) - edit_ticket: Handle possible empty responses: When a ticket is not modified, at least with RT 4.x, an empty response could be returned. Gracefully handle that as success. (#47, #48) ## [v2.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" parameters. 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 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/LICENSE0000644000175100001770000010451314666673042012575 0ustar00runnerdocker 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 . ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/MANIFEST.in0000644000175100001770000000032714666673042013324 0ustar00runnerdockerinclude AUTHORS include CHANGES include LICENSE include README.rst recursive-include doc * recursive-include tests * recursive-exclude .github * exclude .codebeatignore exclude .gitignore exclude .readthedocs.yaml ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1725658667.0468843 rt-3.2.0/PKG-INFO0000644000175100001770000001446614666673053012676 0ustar00runnerdockerMetadata-Version: 2.1 Name: rt Version: 3.2.0 Summary: Python interface to Request Tracker API Author-email: Georges Toth License: GNU General Public License v3 (GPLv3) Project-URL: Homepage, https://github.com/python-rt/python-rt Project-URL: Documentation, https://python-rt.readthedocs.io/ Project-URL: Source, https://github.com/python-rt/python-rt Project-URL: Tracker, https://github.com/python-rt/python-rt/issues Project-URL: Changelog, https://github.com/python-rt/python-rt/blob/master/CHANGELOG.md 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.8 Description-Content-Type: text/x-rst License-File: LICENSE License-File: AUTHORS Requires-Dist: requests Requires-Dist: httpx Provides-Extra: docs Requires-Dist: sphinx; extra == "docs" Requires-Dist: sphinx-autodoc-typehints; extra == "docs" Requires-Dist: sphinx-rtd-theme; extra == "docs" Requires-Dist: furo; extra == "docs" Requires-Dist: sphinx-copybutton; extra == "docs" Provides-Extra: dev Requires-Dist: mypy; extra == "dev" Requires-Dist: ruff; extra == "dev" Requires-Dist: types-requests; extra == "dev" Requires-Dist: codespell; extra == "dev" Requires-Dist: bandit; extra == "dev" Provides-Extra: test Requires-Dist: pytest; extra == "test" Requires-Dist: pytest-asyncio; extra == "test" Requires-Dist: coverage; extra == "test" .. image:: https://codebeat.co/badges/a52cfe15-b824-435b-a594-4bf2be2fb06f :target: https://codebeat.co/projects/github-com-python-rt-python-rt-master :alt: codebeat badge .. image:: https://github.com/python-rt/python-rt/actions/workflows/test_lint.yml/badge.svg :target: https://github.com/python-rt/python-rt/actions/workflows/test_lint.yml :alt: tests .. image:: https://readthedocs.org/projects/python-rt/badge/?version=stable :target: https://python-rt.readthedocs.io/en/stable/?badge=stable :alt: Documentation Status .. image:: https://badge.fury.io/py/rt.svg :target: https://badge.fury.io/py/rt ============================================== Rt - Python interface to Request Tracker API ============================================== Python implementation of REST API described here: - https://rt-wiki.bestpractical.com/wiki/REST - https://docs.bestpractical.com/rt/5.0.2/RT/REST2.html .. csv-table:: Python version compatibility: :header: "Python", "rt" :widths: 15, 15 "2.7", "< 2.0.0" ">= 3.5, <3.7", ">= 2.0.0, < 3.0.0" ">= 3.7", ">= 3.0.0, < 3.1.0" ">= 3.8", ">= 3.0.0" ℹ️ **Note**: Please note that starting with the major release of v3.0.0, this library requires Python version >= 3.8. See the *Python version compatibility* table above for more detailed information. ⚡ **Note**: As of version 3.1.0, this library is async compatible. Usage:: import rt.rest2 import httpx tracker = rt.rest2.AsyncRt('http://localhost/rt/REST/2.0/', http_auth=httpx.BasicAuth('root', 'password')) ⚠️ **Warning**: Though version 3.x still supports RT REST API version 1, it contains minor breaking changes. Please see the changelog in the documentation for details. Requirements ============ This module uses following Python modules: - requests (http://docs.python-requests.org/) - requests-toolbelt (https://pypi.org/project/requests-toolbelt/) - typing-extensions (depending on python version) Documentation ============= https://python-rt.readthedocs.io/en/latest/ 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 registry 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.rest2 >>> import httpx >>> tracker = rt.rest2.Rt('http://localhost/rt/REST/2.0/', http_auth=httpx.BasicAuth('root', 'password')) >>> map(lambda x: x['id'], tracker.search(Queue='helpdesk', Status='open')) ['1', '2', '10', '15'] >>> tracker.create_ticket(queue='helpdesk', \ ... subject='Coffee (important)', content='Help I Ran Out of Coffee!') 19 >>> tracker.edit_ticket(19, Requestor='addicted@example.com') True >>> tracker.reply(19, content='Do you know Starbucks?') True Get the last important updates from a specific queue that have been updated recently:: >>> import datetime >>> import base64 >>> import rt.rest2 >>> import httpx >>> tracker = rt.rest2.Rt('http://localhost/rt/REST/2.0/', http_auth=httpx.BasicAuth('root', 'password')) >>> 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'] >>> history = tracker.get_ticket_history(id) >>> last_update = list(reversed([h for h in history if h['Type'] in ('Correspond', 'Comment')])) >>> hid = tracker.get_transaction(last_update[0]['id'] if last_update else history[0]['id']) >>> >>> attachment_id = None >>> for k in hid['_hyperlinks']: >>> if k['ref'] == 'attachment': >>> attachment_id = k['_url'].rsplit('/', 1)[1] >>> break >>> >>> if attachment_id is not None: >>> attachment = c.get_attachment(attachment_id) >>> if attachment['Content'] is not None: >>> content = base64.b64decode(attachment['Content']).decode() >>> print(content) 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, issue tracking and git repository: https://github.com/python-rt/python-rt ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/README.rst0000644000175100001770000001110414666673042013250 0ustar00runnerdocker.. image:: https://codebeat.co/badges/a52cfe15-b824-435b-a594-4bf2be2fb06f :target: https://codebeat.co/projects/github-com-python-rt-python-rt-master :alt: codebeat badge .. image:: https://github.com/python-rt/python-rt/actions/workflows/test_lint.yml/badge.svg :target: https://github.com/python-rt/python-rt/actions/workflows/test_lint.yml :alt: tests .. image:: https://readthedocs.org/projects/python-rt/badge/?version=stable :target: https://python-rt.readthedocs.io/en/stable/?badge=stable :alt: Documentation Status .. image:: https://badge.fury.io/py/rt.svg :target: https://badge.fury.io/py/rt ============================================== Rt - Python interface to Request Tracker API ============================================== Python implementation of REST API described here: - https://rt-wiki.bestpractical.com/wiki/REST - https://docs.bestpractical.com/rt/5.0.2/RT/REST2.html .. csv-table:: Python version compatibility: :header: "Python", "rt" :widths: 15, 15 "2.7", "< 2.0.0" ">= 3.5, <3.7", ">= 2.0.0, < 3.0.0" ">= 3.7", ">= 3.0.0, < 3.1.0" ">= 3.8", ">= 3.0.0" ℹ️ **Note**: Please note that starting with the major release of v3.0.0, this library requires Python version >= 3.8. See the *Python version compatibility* table above for more detailed information. ⚡ **Note**: As of version 3.1.0, this library is async compatible. Usage:: import rt.rest2 import httpx tracker = rt.rest2.AsyncRt('http://localhost/rt/REST/2.0/', http_auth=httpx.BasicAuth('root', 'password')) ⚠️ **Warning**: Though version 3.x still supports RT REST API version 1, it contains minor breaking changes. Please see the changelog in the documentation for details. Requirements ============ This module uses following Python modules: - requests (http://docs.python-requests.org/) - requests-toolbelt (https://pypi.org/project/requests-toolbelt/) - typing-extensions (depending on python version) Documentation ============= https://python-rt.readthedocs.io/en/latest/ 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 registry 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.rest2 >>> import httpx >>> tracker = rt.rest2.Rt('http://localhost/rt/REST/2.0/', http_auth=httpx.BasicAuth('root', 'password')) >>> map(lambda x: x['id'], tracker.search(Queue='helpdesk', Status='open')) ['1', '2', '10', '15'] >>> tracker.create_ticket(queue='helpdesk', \ ... subject='Coffee (important)', content='Help I Ran Out of Coffee!') 19 >>> tracker.edit_ticket(19, Requestor='addicted@example.com') True >>> tracker.reply(19, content='Do you know Starbucks?') True Get the last important updates from a specific queue that have been updated recently:: >>> import datetime >>> import base64 >>> import rt.rest2 >>> import httpx >>> tracker = rt.rest2.Rt('http://localhost/rt/REST/2.0/', http_auth=httpx.BasicAuth('root', 'password')) >>> 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'] >>> history = tracker.get_ticket_history(id) >>> last_update = list(reversed([h for h in history if h['Type'] in ('Correspond', 'Comment')])) >>> hid = tracker.get_transaction(last_update[0]['id'] if last_update else history[0]['id']) >>> >>> attachment_id = None >>> for k in hid['_hyperlinks']: >>> if k['ref'] == 'attachment': >>> attachment_id = k['_url'].rsplit('/', 1)[1] >>> break >>> >>> if attachment_id is not None: >>> attachment = c.get_attachment(attachment_id) >>> if attachment['Content'] is not None: >>> content = base64.b64decode(attachment['Content']).decode() >>> print(content) 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, issue tracking and git repository: https://github.com/python-rt/python-rt ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1725658667.0428843 rt-3.2.0/doc/0000755000175100001770000000000014666673053012333 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/doc/Makefile0000644000175100001770000001265414666673042014001 0ustar00runnerdocker# 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." ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/doc/changelog.rst0000644000175100001770000000777214666673042015027 0ustar00runnerdockerChange Log ========== Version 3.2.0 (2024-09-06) ---------------------------- Added ^^^^^ - Added option for custom list of fields to be populated for search "query_format" param to avoid unnecessary round trips to get fields like Told, Starts, Resolved, etc by returning the required fields during search. (see #97 @nerdfirefighter) Version 3.1.4 (2024-02-16) ---------------------------- Fixes ^^^^^ - Add a workaround for a breaking change introduced in RT5.0.5 which returns undefined pages variable for non-superusers (see #93 #94). Version 3.1.3 (2023-10-10) ---------------------------- Fixes ^^^^^ - Fix an issue where no e-mail was sent on ticket creation due to suggesting to use *Requestors* instead of *Requestor* (https://github.com/python-rt/python-rt/pull/92). Version 3.1.2 (2023-09-25) ---------------------------- Fixes ^^^^^ - Revert breaking change for python3.8 (collections.abc.AsyncIterator is not subscriptable). Version 3.1.1 (2023-09-25) ---------------------------- Fixes ^^^^^ - In AsyncRt, instead of returning sequences, return AsyncIterators. Version 3.1.0 (2023-09-25) ---------------------------- Changes ^^^^^^^ - Replace *requests* with *httpx* for the REST2 part. Added ^^^^^ - Add a new *AsyncRt* class which implements the RT REST2 API in asnyc. - Adapt tests to include thew new async parts of this library. Version 3.0.7 (2023-07-27) ---------------------------- Fixes ^^^^^ - Fix sorting when using search() method (#90) Version 3.0.6 (2023-06-21) ---------------------------- Fixes ^^^^^ - Fixed bug in rest1 (#86) Version 3.0.5 (2023-02-02) ---------------------------- Fixes ^^^^^ - Added support for specifying custom fields on user creation/edit (#82). Version 3.0.4 (2022-11-08) ---------------------------- Fixes ^^^^^ - Workaround for parsing issues with tickets with only 1 attachment (#80), due to probably an upstream bug. Version 3.0.3 (2022-06-16) ---------------------------- Changes ^^^^^^^ - Move package metadata and configuration from setup.cfg to pyproject.toml. Version 3.0.2 (2022-06-12) ---------------------------- Fixes ^^^^^ - Fix edit_user() response handling in case a user_id name (str) was passed instead of a number. Version 3.0.1 (2022-05-26) ---------------------------- Fixes ^^^^^ - Make sure to include _hyperlinks in history items - On edit ticket, raise exception if user/queue does not exist Added ^^^^^ - Add helper method for deleting tickets - Add tests Version 3.0.0 (2022-05-17) ---------------------------- The following is a major release of the `rt` library. There is support for the REST API version 1 as well as version 2. Please note that this release contains breaking changes and requires adaptations to existing code, even if you are sticking to version 1 of the API. These changes were necessary in order to properly support both API versions. Importing ^^^^^^^^^ Previously doing: .. code-block:: python import rt c = rt.Rt(...) was enough to import the main class `Rt` as well as all exception classes. Starting with version 3, only the main exception class `RtError` is imported when importing the `rt` module. In order to continue using the API version 1 you need to explicitly import it from the `rest1` submodule: .. code-block:: python import rt.rest1 c = rt.rest1.Rt(...) If you need access to specific exception class, make sure to import the exceptions module: .. code-block:: python import rt.exceptions Everything else is the same as with version 2 of the library. .. WARNING:: The minimum supported version of python has been raised to 3.7. Exception classes ^^^^^^^^^^^^^^^^^^ Some exception classes were renamed to follow proper naming scheme (https://peps.python.org/pep-0008/#exception-names): .. csv-table:: :header: "<3.0.0", ">=3.0.0" :widths: 15, 15 "NotAllowed", "NotAllowedError" "UnexpectedResponse", "UnexpectedResponseError" "UnexpectedMessageFormat", "UnexpectedMessageFormatError" "InvalidUseError", "InvalidUseError" "BadRequestError", "BadRequestError" ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/doc/conf.py0000644000175100001770000002004514666673042013631 0ustar00runnerdocker# -*- 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 os import sys from pkg_resources import get_distribution 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', 'sphinx_copybutton'] autodoc_default_options = { 'member-order': 'alphabetical', 'special-members': '__init__', 'undoc-members': True, 'exclude-members': '__weakref__' } # 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-present, A project founded by Jiri Machalek and maintained by the python-rt community.' # 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 full version, including alpha/beta/rc tags. release = get_distribution('rt').version # The short X.Y version. version = '.'.join(release.split('.')[:2]) # 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 = 'sphinx_rtd_theme' html_theme = 'furo' # 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 = False # 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' ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/doc/exceptions.rst0000644000175100001770000000012614666673042015243 0ustar00runnerdockerExceptions ============================== .. automodule:: rt.exceptions :members: ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/doc/glossary.rst0000644000175100001770000000061614666673042014731 0ustar00runnerdockerGlossary ======== .. 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 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/doc/index.rst0000644000175100001770000000231214666673042014170 0ustar00runnerdocker.. 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: 1 rest1 rest2 usage changelog exceptions glossary .. csv-table:: Python version compatibility: :header: "Python", "rt" :widths: 15, 15 "2.7", "< 2.0.0" ">= 3.5, <3.7", ">= 2.0.0, < 3.0.0" ">= 3.7", ">= 3.0.0, < 3.1.0" ">= 3.8", ">= 3.0.0" .. note:: Please note that starting with the major release of v3.0.0, this library requires Python version >= 3.8. See the *Python version compatibility* table above for more detailed information. .. warning:: Although version 3.x still supports RT REST API version 1, it contains minor breaking changes. Please see the :doc:`changelog` in the documentation for details. Get the rt module ================= Using pip:: pip install rt Using project git repository:: git clone https://github.com/python-rt/python-rt Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/doc/rest1.rst0000644000175100001770000000011414666673042014115 0ustar00runnerdockerREST1 ============================== .. automodule:: rt.rest1 :members: ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/doc/rest2.rst0000644000175100001770000000011414666673042014116 0ustar00runnerdockerREST2 ============================== .. automodule:: rt.rest2 :members: ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/doc/usage.rst0000644000175100001770000001502714666673042014174 0ustar00runnerdockerUsage ===== REST API version 2 ------------------- Creating a Connection ````````````````````` :: import rt.rest2 import httpx api_url = 'http://localhost:8080/REST/2.0/' username = 'root' password = 'password' c = rt.rest2.Rt(url=baseurl, http_auth=httpx.BasicAuth('root', 'password')) Ticket Operations ````````````````` Fetching a ticket:: c.get_ticket(1) which gives: .. code-block:: json { "Due": "1970-01-01T00:00:00Z", "Status": "new", "Created": "2022-05-02T18:54:36Z", "CustomFields": [], "TimeEstimated": "0", "LastUpdatedBy": { "id": "root", "type": "user", "_url": "http://localhost:8080/REST/2.0/user/root" }, "Type": "ticket", "Owner": { "id": "Nobody", "_url": "http://localhost:8080/REST/2.0/user/Nobody", "type": "user" }, "Cc": [], "Started": "1970-01-01T00:00:00Z", "AdminCc": [], "Priority": "0", "LastUpdated": "2022-05-02T19:21:30Z", "Subject": "Testing issue wvbocycTSwmNTAX", "FinalPriority": "0", "Queue": { "id": "1", "type": "queue", "_url": "http://localhost:8080/REST/2.0/queue/1", "Name": "General" }, "InitialPriority": "0", "Resolved": "1970-01-01T00:00:00Z", "Creator": { "type": "user", "_url": "http://localhost:8080/REST/2.0/user/root", "id": "root" }, "EffectiveId": { "_url": "http://localhost:8080/REST/2.0/ticket/8", "type": "ticket", "id": "8" }, "Starts": "1970-01-01T00:00:00Z", "TimeWorked": "0", "TimeLeft": "0", "Requestor": [], "_hyperlinks": [ { "id": 8, "ref": "self", "_url": "http://localhost:8080/REST/2.0/ticket/8", "type": "ticket" }, { "ref": "history", "_url": "http://localhost:8080/REST/2.0/ticket/8/history" }, { "_url": "http://localhost:8080/REST/2.0/ticket/8/correspond", "ref": "correspond" }, { "ref": "comment", "_url": "http://localhost:8080/REST/2.0/ticket/8/comment" }, { "ref": "lifecycle", "update": "Respond", "from": "new", "label": "Open It", "_url": "http://localhost:8080/REST/2.0/ticket/8/correspond", "to": "open" }, { "label": "Resolve", "to": "resolved", "_url": "http://localhost:8080/REST/2.0/ticket/8/comment", "ref": "lifecycle", "update": "Comment", "from": "new" }, { "to": "rejected", "_url": "http://localhost:8080/REST/2.0/ticket/8/correspond", "label": "Reject", "from": "new", "update": "Respond", "ref": "lifecycle" }, { "ref": "lifecycle", "label": "Delete", "_url": "http://localhost:8080/REST/2.0/ticket/8", "from": "new", "to": "deleted" } ], "id": 8 } Getting ticket links:: c.get_links(1) for a ticket with #1 having ticket #7 as parent, this would have as result: .. code-block:: json [ { "_url": "http://localhost:8080/REST/2.0/ticket/7", "type": "ticket", "ref": "parent", "id": "7" } ] Editing ticket links. Adding a dependency on another ticket:: c.edit_link(1, 'DependsOn', 7, delete=False) Creating a ticket:: new_ticket = {'Requestor': ['test@example.com'], } res = c.create_ticket('General', subject='Test subject', content='Ticket body...', **new_ticket ) This returns the ID of the created ticket. Editing a ticket:: c.edit_ticket(8, Subject='Re: Test subject', CustomFields={'CF1': 'value1', ... } ) Searching for tickets with status *NEW* in the *General* queue:: c.search(Queue='SOC', raw_query='''Status = 'NEW' ''', Format='i') gives: .. code-block:: json [ { "type": "ticket", "InitialPriority": "0", "CustomFields": "", "TimeEstimated": "0", "Due": "1970-01-01T00:00:00Z", "Priority": "0", "Status": "new", "Created": "2022-05-02T18:54:35Z", "Queue": { "Name": "General", "type": "queue", "_url": "http://localhost:8080/REST/2.0/queue/1", "id": "1" }, "Subject": "Testing issue SsOwRvDXMGnurhU", "LastUpdated": "2022-05-02T20:44:02Z", "TimeLeft": "0", "Owner": { "id": "Nobody", "_url": "http://localhost:8080/REST/2.0/user/Nobody", "type": "user" }, "Started": "1970-01-01T00:00:00Z", "Requestor": [], "Cc": [], "AdminCc": [], "id": "7", "_url": "http://localhost:8080/REST/2.0/ticket/7", "Type": "ticket" }, ... ] Do a reply on a ticket:: c.reply(1, content='test') Comment on a ticket:: c.comment(1, content='test') Merge ticket #1 into #2:: c.merge_ticket(1, 2) Comment on a ticket and add an attachment:: attachments = [] with open('README.rst', 'rb') as fhdl: attachments.append(rt.rest2.Attachment('README.rst', 'test/plain', fhdl.read())) print(json.dumps(c.comment(1, 'test', attachments=attachments), indent=4)) Get attachments for a ticket:: c.get_attachments(1) returns: .. code-block:: json [ { "type": "attachment", "_url": "http://localhost:8080/REST/2.0/attachment/34", "Filename": "README.rst", "ContentType": "test/plain", "id": "34", "ContentLength": "3578" } ] Fetch an attachment by its ID:: c.get_attachment(34) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/noxfile.py0000644000175100001770000000054414666673042013605 0ustar00runnerdocker"""Used for testing against multiple version of Python.""" import nox @nox.session(python=['3.8', '3.9', '3.10', '3.11']) def test_and_typing(session): session.install('.[test,dev]') session.run('pytest', 'tests') session.run('mypy', 'rt') @nox.session() def lint(session): session.install(".[test,dev]") session.run('ruff', 'rt') ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/pyproject.toml0000644000175100001770000001143414666673042014503 0ustar00runnerdocker[build-system] requires = ["setuptools>=65", "setuptools_scm[toml]>=7.0"] build-backend = "setuptools.build_meta" [project] name = "rt" description = "Python interface to Request Tracker API" readme = "README.rst" license = { text = "GNU General Public License v3 (GPLv3)" } authors = [{ name = "Georges Toth", email = "georges.toth@govcert.etat.lu" }] 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", ] requires-python = ">= 3.8" dependencies = [ "requests", "httpx", ] dynamic = ["version"] [project.urls] Homepage = "https://github.com/python-rt/python-rt" Documentation = "https://python-rt.readthedocs.io/" Source = "https://github.com/python-rt/python-rt" Tracker = "https://github.com/python-rt/python-rt/issues" Changelog = "https://github.com/python-rt/python-rt/blob/master/CHANGELOG.md" [project.optional-dependencies] docs = [ "sphinx", "sphinx-autodoc-typehints", "sphinx-rtd-theme", "furo", "sphinx-copybutton", ] dev = [ "mypy", "ruff", "types-requests", "codespell", "bandit", ] test = [ "pytest", "pytest-asyncio", "coverage", ] [tool.setuptools] include-package-data = true [tool.setuptools.packages.find] exclude = ["tests"] namespaces = false [tool.pycodestyle] filename = "rt/rt.py" ignore = "E501, W503, E124, E126" [tool.setuptools_scm] [tool.mypy] show_error_codes = true show_error_context = true show_column_numbers = true ignore_missing_imports = true disallow_incomplete_defs = true disallow_untyped_defs = true disallow_untyped_calls = false warn_no_return = true warn_redundant_casts = true warn_unused_ignores = true strict_optional = true check_untyped_defs = false files = [ "rt/**/*.py" ] [tool.pytest.ini_options] minversion = "6.0" testpaths = [ "tests" ] [tool.ruff] line-length = 140 indent-width = 4 target-version = "py38" [tool.ruff.lint] select = [ "E", # pycodestyle errors "W", # pycodestyle warnings "F", # pyflakes "I", # isort "C", # flake8-comprehensions "B", # flake8-bugbear "D", # pydocstyle "N", # pep8-naming "UP", # pyupgrade "YTT", # flake8-2020 "ANN", # flake8-annotations "ASYNC", # flake8-async "S", # flake8-bandit "BLE", # flake8-blind-except "B", # flake8-bugbear "A", # flake8-builtins "COM", # flake8-commas "C4", # flake8-comprehensions "DTZ", # flake8-datetimez "EM103", # flake8-errmsg - dot-format-in-exception "EXE", # flake8-executable "ISC", # flake8-implicit-str-concat "ICN", # flake8-import-conventions "G", # flake8-logging-format "INP", # flake8-no-pep420 "PIE", # flake8-pie "T20", # flake8-print "PYI", # flake8-pyi "RSE", # flake8-raise "RET", # flake8-return "SLF", # flake8-self "SLOT", # flake8-slots # "SIM", # flake8-simplify "TID", # flake8-tidy-imports "TCH", # flake8-type-checking "PTH", # flake8-use-pathlib "TD", # flake8-todos "FIX", # flake8-fixme "ERA", # eradicate "PL", # Pylint "PLC", # Convention "PLE", # Error "PLR", # Refactor "PLW", # Warning "B904", # reraise-no-cause "FLY", # flynt # "PERF", # Perflint "RUF013", # implicit-optional ] unfixable = [ 'ERA001', 'T201', # `print` found ] extend-select = ['Q', 'RUF100', 'C90'] flake8-quotes = { inline-quotes = 'single', multiline-quotes = 'single' } ignore = [ "C901", # too complex "E501", # line too long "B008", # do not perform function call in argument defaults "ANN101", # missing-type-self "ANN401", # any-type "ANN002", # missing-type-args "ANN003", # missing-type-kwargs "ANN102", # missing-type-cls "PLR0913", # Too many arguments to function call "PLR0915", # Too many statements "PLR2004", # Magic value used in comparison "PLW0603", # Using the global statement "PLR0912", # Too many branches "COM812", # missing-trailing-comma "ISC001", # single-line-implicit-string-concatenation "Q001", # bad-quotes-multiline-string "RET504", # Unnecessary assignment before `return` statement "D401", # First line of docstring should be in imperative mood "D205", # 1 blank line required between summary line and description ] [tool.ruff.lint.per-file-ignores] "tests/**" = [ "ANN", # Missing return type annotation ] "rt/rest1.py" = [ "N803", # Argument name should be lowercase ] [tool.ruff.format] quote-style = "single" [tool.ruff.lint.pydocstyle] convention = "numpy" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1725658667.0428843 rt-3.2.0/rt/0000755000175100001770000000000014666673053012213 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/rt/__init__.py0000644000175100001770000000012214666673042014315 0ustar00runnerdocker"""Module entry point.""" from .exceptions import RtError __all__ = ['RtError'] ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/rt/exceptions.py0000644000175100001770000000372014666673042014746 0ustar00runnerdocker"""Exceptions collection for the rt library.""" import typing 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 NotAllowedError(RtError): """Exception raised when request cannot be finished due to insufficient privileges.""" class UnexpectedResponseError(RtError): """Exception raised when unexpected HTTP code is received.""" def __init__(self, message: str, status_code: typing.Optional[int] = None, response_message: typing.Optional[str] = None) -> None: """Initialization.""" super().__init__(message) self.status_code = status_code self.response_message = response_message class UnexpectedMessageFormatError(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 NotFoundError(RtError): """Exception raised if requested resource is not found.""" class APISyntaxError(RtError): """Exception raised when syntax error is received.""" class InvalidUseError(RtError): """Exception raised when API method is not used correctly.""" class BadRequestError(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 extended by cause parameter. :keyword message: Exception details :keyword cause: Cause exception """ super().__init__(f'{message} (Caused by {repr(cause)})') self.cause = cause class InvalidQueryError(RtError): """Exception raised when attempting to search RT with an invalid raw query.""" ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/rt/py.typed0000644000175100001770000000000014666673042013676 0ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/rt/rest1.py0000644000175100001770000017556414666673042013643 0ustar00runnerdocker"""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 ( APISyntaxError, AuthorizationError, BadRequestError, InvalidQueryError, InvalidUseError, NotAllowedError, NotFoundError, UnexpectedMessageFormatError, UnexpectedResponseError, ) __license__ = """ Copyright (C) 2012 CZ.NIC, z.s.p.o. Copyright (c) 2015 Genome Research Ltd. Copyright (c) 2017 CERT Gouvernemental (GOVCERT.LU) 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" ', '"Georges Toth" ', ] DEFAULT_QUEUE = 'General' """ Default queue used. """ ALL_QUEUES = object() class Rt: r""":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\.$'), 'status_pattern': re.compile(r'^\S+ (\d{3}) '), 'does_not_exist_pattern_bytes': re.compile(rb'^# (?: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(rb'^# 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, cookies: typing.Optional[dict] = 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: typing.Optional[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() if cookies: self.session.headers.update({'referer': url}) self.session.cookies.update(cookies) self.login_result = True 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: str, get_params: typing.Optional[typing.Dict[str, typing.Any]] = None, post_data: typing.Optional[typing.Dict[str, typing.Any]] = None, files: typing.Optional[typing.List[typing.Tuple[str, typing.IO, typing.Optional[str]]]] = None, without_login: bool = False, text_response: bool = True, ) -> str: r"""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 message 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[f'attachment_{i + 1}'] = file_pair response = self.session.post(url, data=post_data, files=files_data) # type: ignore method = 'GET' if post_data or files: method = 'POST' self.logger.debug('### %s', datetime.datetime.now(tz=datetime.timezone.utc).isoformat()) self.logger.debug('Request URL: %s', url) self.logger.debug('Request method: %s', method) self.logger.debug('Response 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 UnexpectedResponseError(f'Received status code {response.status_code} instead of 200.') 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 as exc: raise UnexpectedResponseError(f'Unknown response encoding: {response.encoding}.') from exc except UnicodeError as exc: if text_response: raise UnexpectedResponseError('Unknown response encoding (UTF-8 does not work).') from exc # 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 # type: ignore return result except requests.exceptions.ConnectionError as exc: raise ConnectionError('Connection error', exc) from exc @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 (ValueError, AttributeError, LookupError): 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 NotAllowedError: 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 NotAllowedError(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 BadRequestError(msg[2] if len(msg) > 2 else 'Bad request.') @staticmethod def __normalize_list(msg: typing.Union[str, typing.Sequence[str]]) -> typing.Sequence[str]: """Split message to list by commas and trim whitespace.""" if isinstance(msg, list): _msg = ''.join(msg) elif isinstance(msg, str): _msg = msg else: raise ValueError('Invalid parameter type.') if not _msg: return [] return [x.strip() for x in _msg.split(',')] @classmethod def __parse_response_dict( cls, msg: typing.Iterable[str], expect_keys: typing.Iterable[str] = (), ) -> typing.Dict[str, str]: """Parse an RT API response body into a Python dictionary. This method knows the general format for key-value RT API responses, and parses them into a Python dictionary as plain string values. :keyword msg: A multiline string, or an iterable of string lines, with the RT API response body. :keyword expect_keys: An iterable of strings. If any of these strings do not appear in the response, raise an error. :raises UnexpectedMessageFormatError: The body did not follow the expected format, or an expected key was missing :returns: Dictionary mapping field names to value strings :rtype: Dictionary with string keys and string values """ if isinstance(msg, str): msg = msg.split('\n') fields = {} # type: typing.Dict[str, typing.List[str]] key = '' for line in msg: if not line or line.startswith('#') or (not fields and cls.RE_PATTERNS['status_pattern'].match(line)): key = '' elif line[0].isspace(): try: fields[key].append(line.lstrip()) except KeyError: raise UnexpectedMessageFormatError( 'Response has a continuation line with no field to continue', ) from None else: if line.startswith('CF.{'): sep = '}: ' else: sep = ': ' key, sep, value = line.partition(sep) if sep: key += sep[:-2] fields[key] = [value] elif line.endswith(':'): key = line[:-1] fields[key] = [] else: raise UnexpectedMessageFormatError(f'Response has a line without a field name: {line}') for key in expect_keys: if key not in fields: raise UnexpectedMessageFormatError(f'Missing line starting with `{key}:`.') return {key: '\n'.join(lines) for key, lines in fields.items()} @classmethod def __parse_response_numlist( cls, msg: typing.Iterable[str], ) -> typing.List[typing.Tuple[int, str]]: """Parse an RT API response body into a numbered list. The RT API for transactions and attachments returns a numbered list of items. This method returns 2-tuples to represent them, where the first item is an integer id and the second items is a string description. :keyword msg: A multiline string, or an iterable of string lines, with the RT API response body. :raises UnexpectedMessageFormatError: The body did not follow the expected format :returns: List of 2-tuples with ids and descriptions :rtype: List of 2-tuples (int, str) """ return sorted((int(key), value) for key, value in cls.__parse_response_dict(msg).items()) @classmethod def __parse_response_ticket(cls, msg: typing.Iterable[str]) -> typing.Dict[str, typing.Union[str, typing.Sequence[str]]]: """Parse an RT API ticket response into a Python dictionary. :keyword msg: A multiline string, or an iterable of string lines, with the RT API response body. :raises UnexpectedMessageFormatError: The body did not follow the expected format :returns: Dictionary mapping field names to value strings, or lists of strings for the People fields Requestors, Cc, and AdminCc :rtype: Dictionary with string keys and values that are strings or lists of strings """ pairs = cls.__parse_response_dict(msg, ['Requestors']) if not pairs.get('id', '').startswith('ticket/'): raise UnexpectedMessageFormatError("Response from RT didn't contain a valid ticket_id") _, _, numerical_id = pairs['id'].partition('/') ticket = typing.cast(typing.Dict[str, typing.Sequence[str]], pairs) ticket['numerical_id'] = numerical_id for key in ['Requestors', 'Cc', 'AdminCc']: try: ticket[key] = cls.__normalize_list(ticket[key]) except KeyError: pass return ticket def login(self, login: typing.Optional[str] = None, password: typing.Optional[str] = None) -> bool: """Login with default or supplied credentials. .. 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 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', Fields: typing.Optional[typing.List[str]] = None, **kwargs: typing.Any, ) -> typing.List[dict]: r"""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 __is for operator IS __isnot for operator IS NOT 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: UnexpectedMessageFormatError: 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(f"Queue='{Queue or self.default_queue}'") if not raw_query: operators_map = { 'gt': '>', 'lt': '<', 'exact': '=', 'notexact': '!=', 'like': ' LIKE ', 'notlike': ' NOT LIKE ', 'is': ' IS ', 'isnot': ' IS NOT ', } 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(f"{key}{op}'{value}'") else: query.append(f"'CF.{{{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 if Fields: get_params['fields'] = ''.join(Fields) 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': return [self.__parse_response_ticket(ticket_msg) for ticket_msg in msg.split('\n--\n')] if Format == 's': return [ {'id': 'ticket/' + key, 'numerical_id': key, 'Subject': value} for key, value in self.__parse_response_dict(msg).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 UnexpectedMessageFormatError: Unexpected format of returned message. """ _msg = self.__request(f'ticket/{ticket_id}/show') status_code = self.__get_status_code(_msg) if status_code is not None and status_code == 200: msg = _msg.split('\n') try: not_found = self.RE_PATTERNS['does_not_exist_pattern'].match(msg[2]) except IndexError: not_found = None if not_found: return None return self.__parse_response_ticket(msg) raise UnexpectedMessageFormatError(f'Received status code is {status_code} instead of 200.') @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 = f'CF.{{{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(f"""{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 Requestor: 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: Requestor, 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 += f'\nAttachment: {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:], stacklevel=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(f'ticket/{ticket_id}/edit', 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 UnexpectedMessageFormatError: 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(f'ticket/{ticket_id}/history?format=l') else: msgs = self.__request(f'ticket/{ticket_id}/history/id/{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 items = typing.cast( typing.List[typing.Dict[str, typing.Union[str, typing.List[typing.Tuple[int, str]]]]], [self.__parse_response_dict(msg, ['Content', 'Attachments']) for msg in msgs.split('\n--\n')], ) for body in items: attachments = typing.cast(str, body.get('Attachments', '')) body['Attachments'] = self.__parse_response_numlist(attachments) 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(f'ticket/{ticket_id}/history') lines = msg.split('\n') 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 return self.__parse_response_numlist(lines) return [] 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, ) -> bool: """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 BadRequestError: 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'] += f'\nAttachment: {file_info[0]}' msg = self.__request(f'ticket/{ticket_id}/comment', 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 BadRequestError: 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 BadRequestError: 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(f'ticket/{ticket_id}/attachments') 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): # The format of tickets with 1 attachments varies from those with >=2. # *Attachments: ...* starts at line 3 with single attachment tickets, whereas # with >=2 attachment tickets, it starts at line 4. As in the latter case, # line 3 is just an empty line, we changed this to "3:" in order to work with # single attachment tickets. # -> Bug in RT for line in lines[3:]: 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 UnexpectedMessageFormatError: Unexpected format of returned message. """ _msg = self.__request(f'ticket/{ticket_id}/attachments/{attachment_id}', text_response=False) msg = typing.cast(bytes, _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 UnexpectedMessageFormatError( 'Unexpected headers part of attachment entry. \ Missing line starting with `Headers:`.' ) msg[head_id] = re.sub(b'^Headers: (.*)$', rb'\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 UnexpectedMessageFormatError( 'Unexpected content part of attachment entry. \ Missing line starting with `Content:`.' ) cont_id = cont_matching[0] pairs: typing.Dict[str, typing.Any] = {} 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]: r"""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 = typing.cast(bytes, self.__request(f'ticket/{ticket_id}/attachments/{attachment_id}/content', 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 :] def get_user(self, user_id: typing.Union[str, int]) -> 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 UnexpectedMessageFormatError: In case that returned status code is not 200 """ msg = self.__request(f'user/{user_id}') lines = msg.split('\n') status_code = self.__get_status_code(lines[0]) if status_code is not None and status_code == 200: if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]): return None return self.__parse_response_dict(lines) raise UnexpectedMessageFormatError(f'Received status code is {status_code} instead of 200.') 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 BadRequestError: When user already exists :raises InvalidUseError: 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 BadRequestError: When user does not exist :raises InvalidUseError: 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 = {x.lower() for x in kwargs.keys()} if not used_fields <= valid_fields: invalid_fields = ', '.join(list(used_fields - valid_fields)) raise InvalidUseError(f'Unsupported names of fields: {invalid_fields}.') if isinstance(user_id, str) and not user_id.isnumeric(): _user = self.get_user(user_id) if _user is None: raise NotFoundError(f'User "{user_id}" does not exist.') user_id = _user['id'].split('/', 1)[1] post_data = f'id: user/{user_id}\n' for key, val in kwargs.items(): post_data += f'{key}: {val}\n' 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 UnexpectedMessageFormatError: In case that returned status code is not 200 """ msg = self.__request(f'queue/{queue_id}') lines = msg.split('\n') status_code = self.__get_status_code(lines[0]) if status_code is not None and status_code == 200: if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]): return None return self.__parse_response_dict(lines) raise UnexpectedMessageFormatError(f'Received status code is {status_code} instead of 200.') 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 BadRequestError: When queue does not exist :raises InvalidUseError: When invalid fields are set """ valid_fields = {'name', 'description', 'correspondaddress', 'commentaddress', 'initialpriority', 'finalpriority', 'defaultduein'} used_fields = {x.lower() for x in kwargs.keys()} if not used_fields <= valid_fields: invalid_fields = ', '.join(list(used_fields - valid_fields)) raise InvalidUseError(f'Unsupported names of fields: {invalid_fields}.') post_data = f'id: queue/{queue_id}\n' for key, val in kwargs.items(): post_data += f'{key}: {val}\n' 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 BadRequestError: When queue already exists :raises InvalidUseError: 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 UnexpectedMessageFormatError: In case that returned status code is not 200 """ msg = self.__request(f'ticket/{ticket_id}/links/show') lines = msg.split('\n') status_code = self.__get_status_code(lines[0]) if status_code is not None and status_code == 200: if (len(msg) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]): return None pairs = self.__parse_response_dict(lines) return {key: [link.rstrip(',') for link in links.split()] for key, links in pairs.items()} raise UnexpectedMessageFormatError(f'Received status code is {status_code} instead of 200.') 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, value in kwargs.items(): post_data += f'{key}: {value}\n' msg = self.__request(f'ticket/{ticket_id}/links', 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 InvalidUseError: 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 link_name.lower() not in valid_link_names: raise InvalidUseError('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: 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(f'ticket/{ticket_id}/merge/{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': f'Ticket: {ticket_id}\nAction: take'} msg = self.__request(f'ticket/{ticket_id}/take', 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': f'Ticket: {ticket_id}\nAction: steal'} msg = self.__request(f'ticket/{ticket_id}/take', 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': f'Ticket: {ticket_id}\nAction: untake'} msg = self.__request(f'ticket/{ticket_id}/take', 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) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/rt/rest2.py0000644000175100001770000035212514666673042013632 0ustar00runnerdocker"""Python interface to Request Tracker :term:`API`. Description of Request Tracker :term:`REST` :term:`API`: https://docs.bestpractical.com/rt/5.0.2/RT/REST2.html """ import base64 import collections.abc import dataclasses import datetime import json import logging import re import typing from typing import Literal from urllib.parse import urljoin import httpx import rt.exceptions from .exceptions import AuthorizationError, InvalidUseError, NotFoundError, UnexpectedResponseError __license__ = """ Copyright (C) 2012 CZ.NIC, z.s.p.o. Copyright (c) 2015 Genome Research Ltd. Copyright (c) 2017 CERT Gouvernemental (GOVCERT.LU) 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" ', '"Georges Toth" ', ] VALID_TICKET_LINK_NAMES = ('Parent', 'Child', 'RefersTo', 'ReferredToBy', 'DependsOn', 'DependedOnBy') TYPE_VALID_TICKET_LINK_NAMES = Literal['Parent', 'Child', 'RefersTo', 'ReferredToBy', 'DependsOn', 'DependedOnBy'] TYPE_CONTENT_TYPE = Literal['text/plain', 'text/html'] REGEX_PATTERNS = {'does_not_exist': re.compile(r"""(user|queue|resource)(?: [^does]+)? does not exist""", re.I)} @dataclasses.dataclass class Attachment: """Dataclass representing an attachment.""" file_name: str file_type: str file_content: bytes def to_dict(self) -> typing.Dict[str, str]: """Convert to a dictionary for submitting to the REST API.""" return { 'FileName': self.file_name, 'FileType': self.file_type, 'FileContent': base64.b64encode(self.file_content).decode('utf-8'), } def multipart_form_element(self) -> typing.Tuple[str, bytes, str]: """Convert to a tuple as required for multipart-form-data submission.""" return ( self.file_name, self.file_content, self.file_type, ) class Rt: r""":term:`API` for Request Tracker according to https://docs.bestpractical.com/rt/5.0.2/RT/REST2.html. 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. .. warning:: You need at least version 5.0.2 of RT. .. 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. """ def __init__( self, url: str, proxy: typing.Optional[str] = None, verify_cert: typing.Union[str, bool] = True, http_auth: typing.Optional[httpx.Auth] = None, token: typing.Optional[str] = None, http_timeout: typing.Optional[int] = 20, ) -> None: """API initialization. :param url: Base URL for Request Tracker API. E.g.: http://tracker.example.com/REST/2.0/ :param proxy: Proxy server (string with http://user:password@host/ syntax) :param http_auth: Specify a http authentication instance, e.g. HTTPBasicAuth(), HTTPDigestAuth(), etc. to be used for authenticating to RT :param token: Optional authentication token to be used instead of basic authentication. :param http_timeout: HTTP timeout after which a request is aborted. :raises ValueError: If the specified `url` is invalid. """ self.logger = logging.getLogger(__name__) # ensure trailing slash if not url.endswith('/'): url = f'{url}/' if not url.endswith('REST/2.0/'): raise ValueError('Invalid REST URL specified, please use a form of https://example.com/REST/2.0/') self.url = url self.base_url = url.split('REST/2.0/', 1)[0] self.session = httpx.Client(timeout=http_timeout, verify=verify_cert, proxies=proxy, auth=http_auth) if token is not None: # pragma: no cover # no way to add tests for this with the current docker image self.session.headers['Authorization'] = f'token {token}' def __debug_response(self, response: httpx.Response) -> None: """Output debug information for a given HTTP response.""" response.request.read() self.logger.debug('### %s', datetime.datetime.now(tz=datetime.timezone.utc).isoformat()) self.logger.debug('Request URL: %s', response.request.url) self.logger.debug('Request method: %s', response.request.method) self.logger.debug('Request headers: %s', response.request.headers) self.logger.debug('Request body: %s', str(response.request.content)) self.logger.debug('Response status code: %s', str(response.status_code)) self.logger.debug('Response content:') self.logger.debug(response.content.decode()) def __request( self, selector: str, get_params: typing.Optional[typing.Dict[str, typing.Any]] = None, json_data: typing.Optional[typing.Union[typing.Dict[str, typing.Any], typing.List[typing.Any]]] = None, post_data: typing.Optional[typing.Dict[str, typing.Any]] = None, attachments: typing.Optional[typing.Sequence[Attachment]] = None, ) -> typing.Union[typing.Dict[str, typing.Any], typing.List[str]]: """General request for :term:`API`. :param selector: End part of URL which completes self.url parameter set during class initialization. E.g.: ``ticket/123456/show`` :param get_params: Parameters to add for a GET request. :param json_data: JSON request to send to the API. :param post_data: Dictionary with POST method fields :param attachments: Optional list of :py:class:`~rt.rest2.Attachment` objects :returns: dict or list depending on request :raises AuthorizationError: In case that request is called without previous login or login attempt failed. :raises ConnectionError: In case of connection error. """ try: url = str(urljoin(self.url, selector)) if not attachments: if json_data: response = self.session.post(url, json=json_data) elif post_data: response = self.session.post(url, data=post_data) else: response = self.session.get(url, params=get_params) else: fields: typing.List[typing.Tuple[str, typing.Any]] = [ ('Attachments', attachment.multipart_form_element()) for attachment in attachments ] response = self.session.post(url, files=fields, data={'JSON': json.dumps(json_data)}) self.__debug_response(response) self.__check_response(response) try: result = response.json() except LookupError as exc: # pragma: no cover raise UnexpectedResponseError(f'Unknown response encoding: {response.encoding}.') from exc except UnicodeError as exc: # pragma: no cover raise UnexpectedResponseError( f"""Unknown response encoding (UTF-8 does not work) - "{response.content.decode('utf-8', 'replace')}".""" ) from exc return result except httpx.ConnectError as exc: # pragma: no cover raise ConnectionError('Connection error', exc) from exc def __request_put( self, selector: str, json_data: typing.Optional[typing.Dict[str, typing.Any]] = None, ) -> typing.List[str]: """PUT request for :term:`API`. :param selector: End part of URL which completes self.url parameter set during class initialization. E.g.: ``ticket/123456/show`` :param json_data: JSON request to send to the API. :returns: list :raises AuthorizationError: In case that request is called without previous login or login attempt failed. :raises ConnectionError: In case of connection error. """ try: url = str(urljoin(self.url, selector)) _headers = dict(self.session.headers) _headers['Content-Type'] = 'application/json' response = self.session.put(url, json=json_data, headers=_headers) self.__debug_response(response) self.__check_response(response) try: result = response.json() except LookupError as exc: # pragma: no cover raise UnexpectedResponseError(f'Unknown response encoding: {response.encoding}.') from exc except UnicodeError as exc: # pragma: no cover raise UnexpectedResponseError( f"""Unknown response encoding (UTF-8 does not work) - "{response.content.decode('utf-8', 'replace')}".""" ) from exc return result except httpx.ConnectError as exc: # pragma: no cover raise ConnectionError('Connection error', exc) from exc def __request_delete( self, selector: str, ) -> typing.Dict[str, str]: """DELETE request for :term:`API`. :param selector: End part of URL which completes self.url parameter set during class initialization. E.g.: ``ticket/123456/show`` :returns: dict :raises AuthorizationError: In case that request is called without previous login or login attempt failed. :raises ConnectionError: In case of connection error. """ try: url = str(urljoin(self.url, selector)) _headers = dict(self.session.headers) _headers['Content-Type'] = 'application/json' response = self.session.delete(url, headers=_headers) self.__debug_response(response) self.__check_response(response) try: result = response.json() except LookupError as exc: # pragma: no cover raise UnexpectedResponseError(f'Unknown response encoding: {response.encoding}.') from exc except UnicodeError as exc: # pragma: no cover raise UnexpectedResponseError( f"""Unknown response encoding (UTF-8 does not work) - "{response.content.decode('utf-8', 'replace')}".""" ) from exc return result except httpx.ConnectError as exc: # pragma: no cover raise ConnectionError('Connection error', exc) from exc def __paged_request( self, selector: str, json_data: typing.Optional[typing.Union[typing.List[typing.Dict[str, typing.Any]], typing.Dict[str, typing.Any]]] = None, params: typing.Optional[typing.Dict[str, typing.Any]] = None, page: int = 1, per_page: int = 20, recurse: bool = True, ) -> typing.Iterator[typing.Dict[str, typing.Any]]: """Request using pagination for :term:`API`. :param selector: End part of URL which completes self.url parameter set during class initialization. E.g.: ``ticket/123456/show`` :param json_data: JSON request to send to the API. :param page: The page number to get. :param per_page: Number of results per page to get. :param recurse: Set on the initial call in order to retrieve all pages recursively. :returns: dict :raises AuthorizationError: In case that request is called without previous login or login attempt failed. :raises ConnectionError: In case of connection error. """ if params: params['page'] = page params['per_page'] = per_page else: params = {'page': page, 'per_page': per_page} try: url = str(urljoin(self.url, selector)) method = 'get' if json_data is not None: method = 'post' response = self.session.request(method, url, json=json_data, params=params) self.__check_response(response) try: result = response.json() except LookupError as exc: # pragma: no cover raise UnexpectedResponseError(f'Unknown response encoding: {response.encoding}.') from exc except UnicodeError: # pragma: no cover # replace errors - we need decoded content just to check for error codes in __check_response result = response.content.decode('utf-8', 'replace') if not isinstance(result, dict) and 'items' in result: raise UnexpectedResponseError('Server returned an unexpected result') if result.get('pages', None) is None and result['count'] == 0: # no more results found, exit here # (workaround for the >=RT5.0.5 undefined pages variable for non-superusers) raise NotFoundError yield from result['items'] if recurse and result.get('pages', None) is not None and result['pages'] > result['page']: for _page in range(2, result['pages'] + 1): yield from self.__paged_request( selector, json_data=json_data, page=_page, per_page=result['per_page'], params=params, recurse=False ) elif recurse and result.get('pages', None) is None: # no more results found, exit here # (workaround for the >=RT5.0.5 undefined pages variable for non-superusers) _page = result['page'] while True: _page += 1 try: yield from self.__paged_request( selector, json_data=json_data, page=_page, per_page=result['per_page'], params=params, recurse=False ) except NotFoundError: break except httpx.ConnectError as exc: # pragma: no cover raise ConnectionError('Connection error', exc) from exc @staticmethod def __check_response(response: httpx.Response) -> None: """Search general errors in server response and raise exceptions when found. :param response: Response from HTTP request. :raises BadRequestError: If the server returned an HTTP/400 error. :raises AuthorizationError: Credentials are invalid or missing. :raises NotFoundError: Resource was not found. :raises UnexpectedResponseError: Server returned an unexpected status code. """ if response.status_code == 400: # pragma: no cover try: ret = response.json() except json.JSONDecodeError: ret = 'Bad request' if isinstance(ret, dict): raise rt.exceptions.BadRequestError(ret['message']) raise rt.exceptions.BadRequestError(ret) if response.status_code == 401: # pragma: no cover raise AuthorizationError('Server could not verify that you are authorized to access the requested document.') if response.status_code == 404: raise NotFoundError('No such resource found.') if response.status_code not in (200, 201): raise UnexpectedResponseError( f'Received status code {response.status_code} instead of 200.', status_code=response.status_code, response_message=response.text, ) def __get_url(self, url: str) -> typing.Dict[str, typing.Any]: """Call a URL as specified in the returned JSON of an API operation.""" url_ = url.split('/REST/2.0/', 1)[1] res = self.__request(url_) if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return res def new_correspondence(self, queue: typing.Optional[typing.Union[str, object]] = None) -> typing.Iterator[dict]: """Obtains tickets changed by other users than the system one. :param queue: Queue where to search :returns: Iterator of tickets which were last updated by another 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') def last_updated(self, since: str, queue: typing.Optional[str] = None) -> typing.Iterator[dict]: """Obtains tickets changed after given date. :param since: Date as string in form '2011-02-24' :param queue: Queue where to search :returns: Iterator of tickets with LastUpdated parameter later than *since* ordered in decreasing order by LastUpdated. Each ticket is a dictionary, the same as in :py:meth:`~Rt.get_ticket`. :raises InvalidUseError: If the specified date is of an unsupported format. """ if not self.__validate_date(since): raise InvalidUseError(f'Invalid date specified - "{since}"') return self.search(queue=queue, order='-LastUpdated', LastUpdated__gt=since) @classmethod def __validate_date(cls, _date: str) -> bool: """Check whether the specified date is in the supported format.""" if m := re.match(r'(\d{4})-(\d{2})-(\d{2})', _date): try: year = int(m.group(1)) month = int(m.group(2)) day = int(m.group(3)) except ValueError: return False if 1970 < year < 2100 and 1 < month <= 12 and 1 < day <= 31: return True return False def search( self, queue: typing.Optional[typing.Union[str, object]] = None, order: typing.Optional[str] = None, raw_query: typing.Optional[str] = None, query_format: typing.Union[str, typing.List[str]] = 'l', **kwargs: typing.Any, ) -> typing.Iterator[dict]: r"""Search arbitrary needles in given fields and queue. Example:: >>> tracker = Rt('http://tracker.example.com/REST/2.0/', 'rt-username', 'top-secret') >>> tickets = list(tracker.search(CF_Domain='example.com', Subject__like='warning')) >>> tickets = list(tracker.search(queue='General', order='Status', raw_query="id='1'+OR+id='2'+OR+id='3'")) :param queue: Queue where to search. If you wish to search across all of your queues, pass the ALL_QUEUES object as the argument. :param 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 :param 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. :param query_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 - [field1, field2]: list of fields to be populated :param 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: Iterator over matching tickets. Each ticket is the same dictionary as in :py:meth:`~Rt.get_ticket`. :raises: UnexpectedMessageFormatError: Unexpected format of returned message. InvalidQueryError: If raw query is malformed """ get_params = {} query = [] url = 'tickets' if queue is not None: query.append(f"Queue='{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(f"{key}{op}'{value}'") else: query.append(f"""CF.{{{key[3:]}}}'{op}'{value}\'""") else: query.append(raw_query) get_params['query'] = ' AND '.join('(' + part + ')' for part in query) if order: if order.startswith('-'): get_params['orderby'] = order[1:] get_params['order'] = 'DESC' else: get_params['orderby'] = order if isinstance(query_format, list): get_params['fields'] = ','.join(query_format) elif query_format == 'l': get_params[ 'fields' ] = 'Owner,Status,Created,Subject,Queue,CustomFields,Requestor,Cc,AdminCc,Started,Created,TimeEstimated,Due,Type,InitialPriority,Priority,TimeLeft,LastUpdated' get_params['fields[Queue]'] = 'Name' elif query_format == 's': get_params['fields'] = 'Subject' yield from self.__paged_request(url, params=get_params) def get_ticket(self, ticket_id: typing.Union[str, int]) -> 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 UnexpectedMessageFormatError: Unexpected format of returned message. :raises NotFoundError: If there is no ticket with the specified ticket_id. """ res = self.__request(f'ticket/{ticket_id}', get_params={'fields[Queue]': 'Name'}) if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return res def create_ticket( self, queue: str, content_type: TYPE_CONTENT_TYPE = 'text/plain', subject: typing.Optional[str] = None, content: typing.Optional[str] = None, attachments: typing.Optional[typing.Sequence[Attachment]] = None, **kwargs: typing.Any, ) -> int: """Create new ticket and set given parameters. Example of message sent to ``http://tracker.example.com/REST/2.0/ticket/new``:: { "Queue": "General", "Subject": "Ticket created through REST API", "Owner": "Nobody", "Requestor": "somebody@example.com", "Cc": "user2@example.com", "CustomRoles": {"My Role": "staff1@example.com"}, "Content": "Lorem Ipsum", "CustomFields": {"Severity": "Low"} } :param queue: Queue where to create ticket :param content_type: Content-type of the Content parameter; can be either text/plain or text/html. :param subject: Optional subject for the ticket. :param content: Optional content of the ticket. Must be specified unless attachments are specified. :param attachments: Optional list of :py:class:`~rt.rest2.Attachment` objects :param kwargs: Other arguments possible to set: Requestor, Cc, AdminCc, Owner, Status, Priority, InitialPriority, FinalPriority, TimeEstimated, Starts, Due :returns: ID of new ticket :raises ValueError: If the `content_type` is not of a supported format. """ if content_type not in ('text/plain', 'text/html'): # pragma: no cover raise ValueError('Invalid content-type specified.') ticket_data: typing.Dict[str, typing.Any] = {'Queue': queue} if subject is not None: ticket_data['Subject'] = subject if content is not None: ticket_data['Content'] = content ticket_data['ContentType'] = content_type for k, v in kwargs.items(): ticket_data[k] = v res = self.__request('ticket', json_data=ticket_data, attachments=attachments) if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return int(res['id']) 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 :param 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 can be specified as dict: CustomFields = {"Severity": "Low"} :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) """ msg = self.__request_put(f'ticket/{ticket_id}', json_data=kwargs) self.logger.debug(msg) if not isinstance(msg, list): # pragma: no cover raise UnexpectedResponseError(str(msg)) if not msg: return True for k in msg: if REGEX_PATTERNS['does_not_exist'].search(k): raise rt.exceptions.NotFoundError(k) return bool(msg[0]) def get_ticket_history(self, ticket_id: typing.Union[str, int]) -> typing.Optional[typing.List[typing.Dict[str, typing.Any]]]: """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. """ transactions = self.__paged_request( f'ticket/{ticket_id}/history', params={ 'fields': 'Type,Creator,Created,Description,_hyperlinks', 'fields[Creator]': 'id,Name,RealName,EmailAddress', }, ) return list(transactions) def get_transaction(self, transaction_id: typing.Union[str, int]) -> typing.Dict[str, typing.Any]: """Get a transaction. :param transaction_id: ID of transaction :returns: Return a single transaction. """ res = self.__request(f'transaction/{transaction_id}', get_params={'fields': 'Description'}) if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return res def __correspond( self, ticket_id: typing.Union[str, int], content: str = '', action: Literal['correspond', 'comment'] = 'correspond', content_type: TYPE_CONTENT_TYPE = 'text/plain', attachments: typing.Optional[typing.Sequence[Attachment]] = None, ) -> typing.List[str]: """Sends out the correspondence. :param ticket_id: ID of ticket to which message belongs :param content: Content of email message :param action: correspond or comment :param content_type: Content type of email message, defaults to text/plain. Alternative is text/html. :param attachments: Optional list of :py:class:`~rt.rest2.Attachment` objects :returns: List of messages returned by the backend related to the executed action. :raises BadRequestError: When ticket does not exist :raises InvalidUseError: If the `action` parameter is invalid :raises UnexpectedResponseError: If the response from RT is not as expected """ if action not in ('correspond', 'comment'): # pragma: no cover raise InvalidUseError('action must be either "correspond" or "comment"') post_data: typing.Dict[str, typing.Any] = { 'Content': content, 'ContentType': content_type, } # Adding a one-shot cc/bcc is not supported by RT5.0.2 # if cc: # post_data['Cc'] = cc # noqa: ERA001 # # if bcc: # post_data['Bcc'] = bcc # noqa: ERA001 res = self.__request(f'ticket/{ticket_id}/{action}', json_data=post_data, attachments=attachments) if not isinstance(res, list): # pragma: no cover raise UnexpectedResponseError(str(res)) self.logger.debug(res) return res def reply( self, ticket_id: typing.Union[str, int], content: str = '', content_type: TYPE_CONTENT_TYPE = 'text/plain', attachments: typing.Optional[typing.Sequence[Attachment]] = None, ) -> bool: """Sends email message to the contacts in ``Requestors`` field of given ticket with subject as is set in ``Subject`` field. :param ticket_id: ID of ticket to which message belongs :param content: Content of email message (text/plain or text/html) :param content_type: Content type of email message, default to text/plain :param attachments: Optional list of :py:class:`~rt.rest2.Attachment` objects :returns: ``True`` Operation was successful ``False`` Sending failed (status code != 200) :raises BadRequestError: When ticket does not exist :raises UnexpectedResponseError: If the response from RT is not as expected """ msg = self.__correspond(ticket_id, content, 'correspond', content_type, attachments) if not (isinstance(msg, list) and len(msg) >= 1): # pragma: no cover raise UnexpectedResponseError(str(msg)) return bool(msg[0]) def delete_ticket(self, ticket_id: typing.Union[str, int]) -> None: """Mark a ticket as deleted. :param ticket_id: ID of ticket :raises BadRequestError: When user does not exist :raises NotFoundError: If the user does not exist :raises UnexpectedResponseError: If the response from RT is not as expected """ try: self.__request_delete(f'ticket/{ticket_id}') except UnexpectedResponseError as exc: if exc.status_code == 400: # pragma: no cover raise rt.exceptions.BadRequestError(exc.response_message) from exc if exc.status_code == 204: return raise # pragma: no cover def comment( self, ticket_id: typing.Union[str, int], content: str = '', content_type: TYPE_CONTENT_TYPE = 'text/plain', attachments: typing.Optional[typing.Sequence[Attachment]] = None, ) -> bool: """Adds comment to the given ticket. :param ticket_id: ID of ticket to which comment belongs :param content: Content of comment :param content_type: Content type of comment, default to text/plain :param attachments: Optional list of :py:class:`~rt.rest2.Attachment` objects :returns: ``True`` Operation was successful ``False`` Sending failed (status code != 200) :raises BadRequestError: When ticket does not exist :raises UnexpectedResponseError: If the response from RT is not as expected """ msg = self.__correspond(ticket_id, content, 'comment', content_type, attachments) if not (isinstance(msg, list) and len(msg) >= 1): # pragma: no cover raise UnexpectedResponseError(str(msg)) return bool(msg[0]) def get_attachments(self, ticket_id: typing.Union[str, int]) -> typing.Sequence[typing.Dict[str, str]]: """Get attachment list for a given ticket. Example of a return result: .. code-block:: json [ { "id": "17", "Filename": "README.rst", "ContentLength": "3578", "type": "attachment", "ContentType": "test/plain", "_url": "http://localhost:8080/REST/2.0/attachment/17" } ] :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. """ attachments = [] for item in self.__paged_request( f'ticket/{ticket_id}/attachments', json_data=[{'field': 'Filename', 'operator': 'IS NOT', 'value': ''}], params={'fields': 'Filename,ContentType,ContentLength'}, ): attachments.append(item) return attachments 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 = [] for item in self.__paged_request( f'ticket/{ticket_id}/attachments', json_data=[{'field': 'Filename', 'operator': 'IS NOT', 'value': ''}], ): attachments.append(int(item['id'])) return attachments def get_attachment(self, attachment_id: typing.Union[str, int]) -> typing.Optional[dict]: """Get attachment. :param attachment_id: ID of attachment to fetch :returns: Attachment as dictionary with these keys: * Transaction * ContentType * Parent * Creator * Created * Filename * Content (base64 encoded string) * 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 Set of headers available depends on mailservers sending emails not on Request Tracker! :raises UnexpectedMessageFormatError: Unexpected format of returned message. :raises NotFoundError: If attachment with specified ID does not exist. """ res = self.__request(f'attachment/{attachment_id}') if not (res is None or isinstance(res, dict)): # pragma: no cover raise UnexpectedResponseError(str(res)) return res def get_user(self, user_id: typing.Union[int, str]) -> typing.Dict[str, typing.Any]: """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 :raises UnexpectedMessageFormatError: In case that returned status code is not 200 :raises NotFoundError: If the user does not exist. """ res = self.__request(f'user/{user_id}') if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return res def user_exists(self, user_id: typing.Union[int, str], privileged: bool = True) -> bool: """Check if a given user_id exists. :parameter user_id: User ID to lookup. :parameter privileged: If set to True, only return True if the user_id was found and is privileged. :returns: bool: True on success, else False. """ try: user_dict = self.get_user(user_id) if not privileged or (privileged and user_dict.get('Privileged', '0') == 1): return True except rt.exceptions.NotFoundError: return False return False def create_user(self, user_name: str, email_address: str, **kwargs: typing.Any) -> str: """Create user. :param user_name: Username (login for privileged, required) :param email_address: Email address (required) :param kwargs: Optional fields to set (see edit_user) :returns: ID of new user or False when create fails :raises BadRequestError: When user already exists :raises InvalidUseError: When invalid fields are set :raises UnexpectedResponseError: If the response from RT is not as expected """ 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', 'CustomFields', } invalid_fields = [] post_data = { 'Name': user_name, 'EmailAddress': email_address, } for k, v in kwargs.items(): if k not in valid_fields: invalid_fields.append(k) else: post_data[k] = v if invalid_fields: raise InvalidUseError(f"""Unsupported names of fields: {', '.join(invalid_fields)}.""") try: res = self.__request('user', json_data=post_data) except UnexpectedResponseError as exc: # pragma: no cover if exc.status_code == 400: raise rt.exceptions.BadRequestError(exc.response_message) from exc raise if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return res['id'] def edit_user(self, user_id: typing.Union[str, int], **kwargs: typing.Any) -> typing.List[str]: """Edit user profile. :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: List of status messages :raises BadRequestError: When user does not exist :raises InvalidUseError: When invalid fields are set :raises UnexpectedResponseError: If the response from RT is not as expected """ 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', 'CustomFields', } invalid_fields = [] post_data = {} for key, val in kwargs.items(): if key not in valid_fields: invalid_fields.append(key) else: post_data[key] = val if invalid_fields: raise InvalidUseError(f"""Unsupported names of fields: {', '.join(invalid_fields)}.""") try: ret = self.__request_put(f'user/{user_id}', json_data=post_data) except UnexpectedResponseError as exc: # pragma: no cover if exc.status_code == 400: raise rt.exceptions.BadRequestError(exc.response_message) from exc raise return ret def delete_user(self, user_id: typing.Union[str, int]) -> None: """Disable a user. :param user_id: Identification of a user by name (str) or ID (int) :raises BadRequestError: When user does not exist :raises NotFoundError: If the user does not exist :raises UnexpectedResponseError: If the response from RT is not as expected """ try: _ = self.__request_delete(f'user/{user_id}') except UnexpectedResponseError as exc: if exc.status_code == 400: # pragma: no cover raise rt.exceptions.BadRequestError(exc.response_message) from exc if exc.status_code == 204: return raise # pragma: no cover def get_queue(self, queue_id: typing.Union[str, int]) -> typing.Optional[typing.Dict[str, typing.Any]]: """Get queue details. Example of a return result: .. code-block:: json { "LastUpdatedBy": { "_url": "http://localhost:8080/REST/2.0/user/RT_System", "type": "user", "id": "RT_System" }, "LastUpdated": "2022-03-06T04:53:38Z", "AdminCc": [], "SortOrder": "0", "CorrespondAddress": "", "Creator": { "id": "RT_System", "_url": "http://localhost:8080/REST/2.0/user/RT_System", "type": "user" }, "Lifecycle": "default", "Cc": [], "Created": "2022-03-06T04:53:38Z", "_hyperlinks": [ { "_url": "http://localhost:8080/REST/2.0/queue/1", "type": "queue", "id": 1, "ref": "self" }, { "ref": "history", "_url": "http://localhost:8080/REST/2.0/queue/1/history" }, { "ref": "create", "type": "ticket", "_url": "http://localhost:8080/REST/2.0/ticket?Queue=1" } ], "SLADisabled": "1", "Name": "General", "TicketCustomFields": [], "Disabled": "0", "TicketTransactionCustomFields": [], "CustomFields": [], "Description": "The default queue", "CommentAddress": "", "id": 1 } :param queue_id: Identification of queue by name (str) or queue ID (int) :returns: Queue details as a dictionary :raises UnexpectedMessageFormatError: In case that returned status code is not 200 :raises NotFoundError: In case the queue does not exist """ res = self.__request(f'queue/{queue_id}') if not (res is None or isinstance(res, dict)): # pragma: no cover raise UnexpectedResponseError(str(res)) return res def get_all_queues(self, include_disabled: bool = False) -> typing.List[typing.Dict[str, typing.Any]]: """Return a list of all queues. Example of a return result: .. code-block:: json [ { "InitialPriority": "", "_url": "http://localhost:8080/REST/2.0/queue/1", "type": "queue", "Name": "General", "DefaultDueIn": "", "Description": "The default queue", "CorrespondAddress": "", "CommentAddress": "", "id": "1", "FinalPriority": "" } ] :param include_disabled: Set to True to also return disabled queues. :returns: Returns a list of dictionaries containing basic information on all queues. :raises UnexpectedMessageFormatError: In case that returned status code is not 200 """ params = { 'fields': 'Name,Description,CorrespondAddress,CommentAddress,InitialPriority,FinalPriority,DefaultDueIn', 'find_disabled_rows': int(include_disabled), } queues = self.__paged_request('queues/all', params=params) return list(queues) def edit_queue(self, queue_id: typing.Union[str, int], **kwargs: typing.Any) -> typing.List[str]: """Edit queue. :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 * Disabled * SLADisabled * Lifecycle * SortOrder :returns: List of status messages :raises BadRequestError: When queue does not exist :raises InvalidUseError: When invalid fields are set :raises UnexpectedResponseError: If the response from RT is not as expected """ valid_fields = { 'Name', 'Description', 'CorrespondAddress', 'CommentAddress', 'Disabled', 'SLADisabled', 'Lifecycle', 'SortOrder', } invalid_fields = [] post_data = {} for key, val in kwargs.items(): if key not in valid_fields: invalid_fields.append(key) else: post_data[key] = val if invalid_fields: raise InvalidUseError(f"""Unsupported names of fields: {', '.join(invalid_fields)}.""") try: ret = self.__request_put(f'queue/{queue_id}', json_data=post_data) except UnexpectedResponseError as exc: # pragma: no cover if exc.status_code == 400: raise rt.exceptions.BadRequestError(exc.response_message) from exc raise return ret def create_queue(self, name: str, **kwargs: typing.Any) -> int: """Create queue. :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 BadRequestError: When queue already exists :raises InvalidUseError: When invalid fields are set :raises UnexpectedResponseError: If the response from RT is not as expected """ valid_fields = { 'Name', 'Description', 'CorrespondAddress', 'CommentAddress', 'Disabled', 'SLADisabled', 'Lifecycle', 'SortOrder', } invalid_fields = [] post_data = {'Name': name} for key, val in kwargs.items(): if key not in valid_fields: invalid_fields.append(key) else: post_data[key] = val if invalid_fields: raise InvalidUseError(f"""Unsupported names of fields: {', '.join(invalid_fields)}.""") try: res = self.__request('queue', json_data=post_data) except UnexpectedResponseError as exc: # pragma: no cover if exc.status_code == 400: raise rt.exceptions.BadRequestError(exc.response_message) from exc raise if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return int(res['id']) def delete_queue(self, queue_id: typing.Union[str, int]) -> None: """Disable a queue. :param queue_id: Identification of queue by name (str) or ID (int) :returns: ID or name of edited queue or False when edit fails :raises BadRequestError: When queue does not exist :raises NotFoundError: If the queue does not exist :raises UnexpectedResponseError: If the response from RT is not as expected """ try: _ = self.__request_delete(f'queue/{queue_id}') except UnexpectedResponseError as exc: # pragma: no cover if exc.status_code == 400: raise rt.exceptions.BadRequestError(exc.response_message) from exc if exc.status_code == 204: return raise # pragma: no cover def get_links(self, ticket_id: typing.Union[str, int]) -> typing.Optional[typing.List[typing.Dict[str, str]]]: """Gets the ticket links for a single ticket. Example of a return result: .. code-block:: json [ { "id": "13", "type": "ticket", "_url": "http://localhost:8080/REST/2.0/ticket/13", "ref": "depends-on" } ] :param ticket_id: ticket ID :returns: Links as lists of strings in dictionary with these keys (just those which are defined): * depends-on * depended-on-by * parent * child * refers-to * referred-to-by None is returned if ticket does not exist. :raises UnexpectedMessageFormatError: In case that returned status code is not 200 """ ticket = self.get_ticket(ticket_id) return [link for link in ticket['_hyperlinks'] if link.get('type', '') == 'ticket' and link['ref'] != 'self'] def edit_link( self, ticket_id: typing.Union[str, int], link_name: TYPE_VALID_TICKET_LINK_NAMES, link_value: typing.Union[str, int], delete: bool = False, ) -> bool: """Creates or deletes a link between the specified tickets. :param ticket_id: ID of ticket to edit :param link_name: Name of link to edit ('Parent', 'Child', 'RefersTo', 'ReferredToBy', 'DependsOn', 'DependedOnBy') :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 InvalidUseError: When none or more than one link is specified. Also, when a wrong link name is used or when trying to link to a deleted ticket. """ if link_name not in VALID_TICKET_LINK_NAMES: raise InvalidUseError(f'Unsupported link name. Use one of "{", ".join(VALID_TICKET_LINK_NAMES)}".') if delete: json_data = {f'Delete{link_name}': link_value} else: json_data = {f'Add{link_name}': link_value} msg = self.__request_put(f'ticket/{ticket_id}', json_data=json_data) if msg and isinstance(msg, list): if msg[0].startswith("Couldn't resolve"): raise NotFoundError(msg[0]) if 'not allowed' in msg[0]: raise InvalidUseError(msg[0]) return True def merge_ticket(self, ticket_id: typing.Union[str, int], into_id: typing.Union[str, int]) -> bool: """Merge ticket into another. :param ticket_id: ID of ticket to be merged :param into_id: 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. :raises UnexpectedResponseError: If the response from RT is not as expected """ msg = self.__request_put(f'ticket/{ticket_id}', json_data={'MergeInto': into_id}) if not isinstance(msg, list) or len(msg) != 1: # pragma: no cover raise UnexpectedResponseError(str(msg)) self.logger.debug(str(msg)) return msg[0].lower() == 'merge successful' 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. :raises UnexpectedResponseError: If the response from RT is not as expected """ msg = self.__request_put(f'ticket/{ticket_id}/take') if not isinstance(msg, list) or len(msg) != 1: # pragma: no cover raise UnexpectedResponseError(str(msg)) self.logger.debug(str(msg)) return msg[0].lower().startswith('owner changed') 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. :raises UnexpectedResponseError: If the response from RT is not as expected """ msg = self.__request_put(f'ticket/{ticket_id}/untake') if not isinstance(msg, list) or len(msg) != 1: # pragma: no cover raise UnexpectedResponseError(str(msg)) self.logger.debug(str(msg)) return msg[0].lower().startswith('owner changed') 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. :raises UnexpectedResponseError: If the response from RT is not as expected """ msg = self.__request_put(f'ticket/{ticket_id}/steal') if not isinstance(msg, list) or len(msg) != 1: # pragma: no cover raise UnexpectedResponseError(str(msg)) self.logger.debug(str(msg)) return msg[0].lower().startswith('owner changed') class AsyncRt: r""":term:`API` for Request Tracker according to https://docs.bestpractical.com/rt/5.0.2/RT/REST2.html. 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. .. warning:: You need at least version 5.0.2 of RT. .. 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. """ def __init__( self, url: str, proxy: typing.Optional[str] = None, verify_cert: typing.Union[str, bool] = True, http_auth: typing.Optional[httpx.Auth] = None, token: typing.Optional[str] = None, http_timeout: typing.Optional[int] = 20, ) -> None: """API initialization. :param url: Base URL for Request Tracker API. E.g.: http://tracker.example.com/REST/2.0/ :param proxy: Proxy server (string with http://user:password@host/ syntax) :param http_auth: Specify a http authentication instance, e.g. HTTPBasicAuth(), HTTPDigestAuth(), etc. to be used for authenticating to RT :param token: Optional authentication token to be used instead of basic authentication. :param http_timeout: HTTP timeout after which a request is aborted. :raises ValueError: If the specified `url` is invalid. """ self.logger = logging.getLogger(__name__) # ensure trailing slash if not url.endswith('/'): url = f'{url}/' if not url.endswith('REST/2.0/'): raise ValueError('Invalid REST URL specified, please use a form of https://example.com/REST/2.0/') self.url = url self.base_url = url.split('REST/2.0/', 1)[0] self.session = httpx.AsyncClient(timeout=http_timeout, verify=verify_cert, proxies=proxy, auth=http_auth) if token is not None: # pragma: no cover # no way to add tests for this with the current docker image self.session.headers['Authorization'] = f'token {token}' def __debug_response(self, response: httpx.Response) -> None: """Output debug information for a given HTTP response.""" response.request.read() self.logger.debug('### %s', datetime.datetime.now(tz=datetime.timezone.utc).isoformat()) self.logger.debug('Request URL: %s', response.request.url) self.logger.debug('Request method: %s', response.request.method) self.logger.debug('Request headers: %s', response.request.headers) self.logger.debug('Request body: %s', str(response.request.content)) self.logger.debug('Response status code: %s', str(response.status_code)) self.logger.debug('Response content:') self.logger.debug(response.content.decode()) async def __request( self, selector: str, get_params: typing.Optional[typing.Dict[str, typing.Any]] = None, json_data: typing.Optional[typing.Union[typing.Dict[str, typing.Any], typing.List[typing.Any]]] = None, post_data: typing.Optional[typing.Dict[str, typing.Any]] = None, attachments: typing.Optional[typing.Sequence[Attachment]] = None, ) -> typing.Union[typing.Dict[str, typing.Any], typing.List[str]]: """General request for :term:`API`. :param selector: End part of URL which completes self.url parameter set during class initialization. E.g.: ``ticket/123456/show`` :param get_params: Parameters to add for a GET request. :param json_data: JSON request to send to the API. :param post_data: Dictionary with POST method fields :param attachments: Optional list of :py:class:`~rt.rest2.Attachment` objects :returns: dict or list depending on request :raises AuthorizationError: In case that request is called without previous login or login attempt failed. :raises ConnectionError: In case of connection error. """ try: url = str(urljoin(self.url, selector)) if not attachments: if json_data: response = await self.session.post(url, json=json_data) elif post_data: response = await self.session.post(url, data=post_data) else: response = await self.session.get(url, params=get_params) else: fields: typing.List[typing.Tuple[str, typing.Any]] = [ ('Attachments', attachment.multipart_form_element()) for attachment in attachments ] response = await self.session.post(url, files=fields, data={'JSON': json.dumps(json_data)}) self.__debug_response(response) self.__check_response(response) try: result = response.json() except LookupError as exc: # pragma: no cover raise UnexpectedResponseError(f'Unknown response encoding: {response.encoding}.') from exc except UnicodeError as exc: # pragma: no cover raise UnexpectedResponseError( f"""Unknown response encoding (UTF-8 does not work) - "{response.content.decode('utf-8', 'replace')}".""" ) from exc return result except httpx.ConnectError as exc: # pragma: no cover raise ConnectionError('Connection error', exc) from exc async def __request_put( self, selector: str, json_data: typing.Optional[typing.Dict[str, typing.Any]] = None, ) -> typing.List[str]: """PUT request for :term:`API`. :param selector: End part of URL which completes self.url parameter set during class initialization. E.g.: ``ticket/123456/show`` :param json_data: JSON request to send to the API. :returns: list :raises AuthorizationError: In case that request is called without previous login or login attempt failed. :raises ConnectionError: In case of connection error. """ try: url = str(urljoin(self.url, selector)) _headers = dict(self.session.headers) _headers['Content-Type'] = 'application/json' response = await self.session.put(url, json=json_data, headers=_headers) self.__debug_response(response) self.__check_response(response) try: result = response.json() except LookupError as exc: # pragma: no cover raise UnexpectedResponseError(f'Unknown response encoding: {response.encoding}.') from exc except UnicodeError as exc: # pragma: no cover raise UnexpectedResponseError( f"""Unknown response encoding (UTF-8 does not work) - "{response.content.decode('utf-8', 'replace')}".""" ) from exc return result except httpx.ConnectError as exc: # pragma: no cover raise ConnectionError('Connection error', exc) from exc async def __request_delete(self, selector: str) -> typing.Dict[str, str]: """DELETE request for :term:`API`. :param selector: End part of URL which completes self.url parameter set during class initialization. E.g.: ``ticket/123456/show`` :returns: dict :raises AuthorizationError: In case that request is called without previous login or login attempt failed. :raises ConnectionError: In case of connection error. """ try: url = str(urljoin(self.url, selector)) _headers = dict(self.session.headers) _headers['Content-Type'] = 'application/json' response = await self.session.delete(url, headers=_headers) self.__debug_response(response) self.__check_response(response) try: result = response.json() except LookupError as exc: # pragma: no cover raise UnexpectedResponseError(f'Unknown response encoding: {response.encoding}.') from exc except UnicodeError as exc: # pragma: no cover raise UnexpectedResponseError( f"""Unknown response encoding (UTF-8 does not work) - "{response.content.decode('utf-8', 'replace')}".""" ) from exc return result except httpx.ConnectError as exc: # pragma: no cover raise ConnectionError('Connection error', exc) from exc async def __paged_request( self, selector: str, json_data: typing.Optional[typing.Union[typing.List[typing.Dict[str, typing.Any]], typing.Dict[str, typing.Any]]] = None, params: typing.Optional[typing.Dict[str, typing.Any]] = None, page: int = 1, per_page: int = 20, recurse: bool = True, ) -> collections.abc.AsyncIterator: """Request using pagination for :term:`API`. :param selector: End part of URL which completes self.url parameter set during class initialization. E.g.: ``ticket/123456/show`` :param json_data: JSON request to send to the API. :param page: The page number to get. :param per_page: Number of results per page to get. :param recurse: Set on the initial call in order to retrieve all pages recursively. :returns: collections.abc.AsyncIterator[typing.Dict[str, typing.Any]] :raises AuthorizationError: In case that request is called without previous login or login attempt failed. :raises ConnectionError: In case of connection error. """ if params: params['page'] = page params['per_page'] = per_page else: params = {'page': page, 'per_page': per_page} try: url = str(urljoin(self.url, selector)) method = 'get' if json_data is not None: method = 'post' response = await self.session.request(method, url, json=json_data, params=params) self.__check_response(response) try: result = response.json() except LookupError as exc: # pragma: no cover raise UnexpectedResponseError(f'Unknown response encoding: {response.encoding}.') from exc except UnicodeError: # pragma: no cover # replace errors - we need decoded content just to check for error codes in __check_response result = response.content.decode('utf-8', 'replace') if not isinstance(result, dict) and 'items' in result: raise UnexpectedResponseError('Server returned an unexpected result') if result.get('pages', None) is None and result['count'] == 0: # no more results found, exit here # (workaround for the >=RT5.0.5 undefined pages variable for non-superusers) raise NotFoundError for item in result['items']: yield item if recurse and result.get('pages', None) is not None and result['pages'] > result['page']: for _page in range(2, result['pages'] + 1): async for item in self.__paged_request( selector, json_data=json_data, page=_page, per_page=result['per_page'], params=params, recurse=False ): yield item elif recurse and result.get('pages', None) is None: # no more results found, exit here # (workaround for the >=RT5.0.5 undefined pages variable for non-superusers) _page = result['page'] while True: _page += 1 try: async for item in self.__paged_request( selector, json_data=json_data, page=_page, per_page=result['per_page'], params=params, recurse=False ): yield item except NotFoundError: break except httpx.ConnectError as exc: # pragma: no cover raise ConnectionError('Connection error', exc) from exc @staticmethod def __check_response(response: httpx.Response) -> None: """Search general errors in server response and raise exceptions when found. :param response: Response from HTTP request. :raises BadRequestError: If the server returned an HTTP/400 error. :raises AuthorizationError: Credentials are invalid or missing. :raises NotFoundError: Resource was not found. :raises UnexpectedResponseError: Server returned an unexpected status code. """ if response.status_code == 400: # pragma: no cover try: ret = response.json() except json.JSONDecodeError: ret = 'Bad request' if isinstance(ret, dict): raise rt.exceptions.BadRequestError(ret['message']) raise rt.exceptions.BadRequestError(ret) if response.status_code == 401: # pragma: no cover raise AuthorizationError('Server could not verify that you are authorized to access the requested document.') if response.status_code == 404: raise NotFoundError('No such resource found.') if response.status_code not in (200, 201): raise UnexpectedResponseError( f'Received status code {response.status_code} instead of 200.', status_code=response.status_code, response_message=response.text, ) async def __get_url(self, url: str) -> typing.Dict[str, typing.Any]: """Call a URL as specified in the returned JSON of an API operation.""" url_ = url.split('/REST/2.0/', 1)[1] res = await self.__request(url_) if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return res async def new_correspondence(self, queue: typing.Optional[typing.Union[str, object]] = None) -> collections.abc.AsyncIterator: """Obtains tickets changed by other users than the system one. :param queue: Queue where to search :returns: Iterator of tickets which were last updated by another user than the system one, ordered in decreasing order by LastUpdated. Each ticket is dictionary, the same as in :py:meth:`~Rt.get_ticket`. collections.abc.AsyncIterator[dict] """ return self.search(queue=queue, order='-LastUpdated') async def last_updated(self, since: str, queue: typing.Optional[str] = None) -> collections.abc.AsyncIterator: """Obtains tickets changed after given date. :param since: Date as string in form '2011-02-24' :param queue: Queue where to search :returns: Iterator of tickets with LastUpdated parameter later than *since* ordered in decreasing order by LastUpdated. Each ticket is a dictionary, the same as in :py:meth:`~Rt.get_ticket`. collections.abc.AsyncIterator[dict] :raises InvalidUseError: If the specified date is of an unsupported format. """ if not self.__validate_date(since): raise InvalidUseError(f'Invalid date specified - "{since}"') return self.search(queue=queue, order='-LastUpdated', LastUpdated__gt=since) @classmethod def __validate_date(cls, _date: str) -> bool: """Check whether the specified date is in the supported format.""" if m := re.match(r'(\d{4})-(\d{2})-(\d{2})', _date): try: year = int(m.group(1)) month = int(m.group(2)) day = int(m.group(3)) except ValueError: return False if 1970 < year < 2100 and 1 < month <= 12 and 1 < day <= 31: return True return False async def search( self, queue: typing.Optional[typing.Union[str, object]] = None, order: typing.Optional[str] = None, raw_query: typing.Optional[str] = None, query_format: typing.Union[str, typing.List[str]] = 'l', **kwargs: typing.Any, ) -> collections.abc.AsyncIterator: r"""Search arbitrary needles in given fields and queue. Example:: >>> tracker = Rt('http://tracker.example.com/REST/2.0/', 'rt-username', 'top-secret') >>> tickets = list(tracker.search(CF_Domain='example.com', Subject__like='warning')) >>> tickets = list(tracker.search(queue='General', order='Status', raw_query="id='1'+OR+id='2'+OR+id='3'")) :param queue: Queue where to search. If you wish to search across all of your queues, pass the ALL_QUEUES object as the argument. :param 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 :param 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. :param query_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 - [field1, field2]: list of fields to be populated :param 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: Iterator over matching tickets. Each ticket is the same dictionary as in :py:meth:`~Rt.get_ticket`. collections.abc.AsyncIterator[dict] :raises: UnexpectedMessageFormatError: Unexpected format of returned message. InvalidQueryError: If raw query is malformed """ get_params = {} query = [] url = 'tickets' if queue is not None: query.append(f"Queue='{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(f"{key}{op}'{value}'") else: query.append(f"""CF.{{{key[3:]}}}'{op}'{value}\'""") else: query.append(raw_query) get_params['query'] = ' AND '.join('(' + part + ')' for part in query) if order: if order.startswith('-'): get_params['orderby'] = order[1:] get_params['order'] = 'DESC' else: get_params['orderby'] = order if isinstance(query_format, list): get_params['fields'] = ','.join(query_format) elif query_format == 'l': get_params[ 'fields' ] = 'Owner,Status,Created,Subject,Queue,CustomFields,Requestor,Cc,AdminCc,Started,Created,TimeEstimated,Due,Type,InitialPriority,Priority,TimeLeft,LastUpdated' get_params['fields[Queue]'] = 'Name' elif query_format == 's': get_params['fields'] = 'Subject' async for item in self.__paged_request(url, params=get_params): yield item async def get_ticket(self, ticket_id: typing.Union[str, int]) -> 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 UnexpectedMessageFormatError: Unexpected format of returned message. :raises NotFoundError: If there is no ticket with the specified ticket_id. """ res = await self.__request(f'ticket/{ticket_id}', get_params={'fields[Queue]': 'Name'}) if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return res async def create_ticket( self, queue: str, content_type: TYPE_CONTENT_TYPE = 'text/plain', subject: typing.Optional[str] = None, content: typing.Optional[str] = None, attachments: typing.Optional[typing.Sequence[Attachment]] = None, **kwargs: typing.Any, ) -> int: """Create new ticket and set given parameters. Example of message sent to ``http://tracker.example.com/REST/2.0/ticket/new``:: { "Queue": "General", "Subject": "Ticket created through REST API", "Owner": "Nobody", "Requestor": "somebody@example.com", "Cc": "user2@example.com", "CustomRoles": {"My Role": "staff1@example.com"}, "Content": "Lorem Ipsum", "CustomFields": {"Severity": "Low"} } :param queue: Queue where to create ticket :param content_type: Content-type of the Content parameter; can be either text/plain or text/html. :param subject: Optional subject for the ticket. :param content: Optional content of the ticket. Must be specified unless attachments are specified. :param attachments: Optional list of :py:class:`~rt.rest2.Attachment` objects :param kwargs: Other arguments possible to set: Requestors, Cc, AdminCc, Owner, Status, Priority, InitialPriority, FinalPriority, TimeEstimated, Starts, Due :returns: ID of new ticket :raises ValueError: If the `content_type` is not of a supported format. """ if content_type not in ('text/plain', 'text/html'): # pragma: no cover raise ValueError('Invalid content-type specified.') ticket_data: typing.Dict[str, typing.Any] = {'Queue': queue} if subject is not None: ticket_data['Subject'] = subject if content is not None: ticket_data['Content'] = content ticket_data['ContentType'] = content_type for k, v in kwargs.items(): ticket_data[k] = v res = await self.__request('ticket', json_data=ticket_data, attachments=attachments) if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return int(res['id']) async 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 :param 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 can be specified as dict: CustomFields = {"Severity": "Low"} :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) """ msg = await self.__request_put(f'ticket/{ticket_id}', json_data=kwargs) self.logger.debug(msg) if not isinstance(msg, list): # pragma: no cover raise UnexpectedResponseError(str(msg)) if not msg: return True for k in msg: if REGEX_PATTERNS['does_not_exist'].search(k): raise rt.exceptions.NotFoundError(k) return bool(msg[0]) async def get_ticket_history(self, ticket_id: typing.Union[str, int]) -> collections.abc.AsyncIterator: """Get set of short history items. :param ticket_id: ID of ticket :returns: Iterator of history items ordered increasingly by time of event. Each history item is a tuple containing (id, Description). collections.abc.AsyncIterator[typing.Dict[str, typing.Any]] """ async for transaction in self.__paged_request( f'ticket/{ticket_id}/history', params={ 'fields': 'Type,Creator,Created,Description,_hyperlinks', 'fields[Creator]': 'id,Name,RealName,EmailAddress', }, ): yield transaction async def get_transaction(self, transaction_id: typing.Union[str, int]) -> typing.Dict[str, typing.Any]: """Get a transaction. :param transaction_id: ID of transaction :returns: Return a single transaction. """ res = await self.__request(f'transaction/{transaction_id}', get_params={'fields': 'Description'}) if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return res async def __correspond( self, ticket_id: typing.Union[str, int], content: str = '', action: Literal['correspond', 'comment'] = 'correspond', content_type: TYPE_CONTENT_TYPE = 'text/plain', attachments: typing.Optional[typing.Sequence[Attachment]] = None, ) -> typing.List[str]: """Sends out the correspondence. :param ticket_id: ID of ticket to which message belongs :param content: Content of email message :param action: correspond or comment :param content_type: Content type of email message, defaults to text/plain. Alternative is text/html. :param attachments: Optional list of :py:class:`~rt.rest2.Attachment` objects :returns: List of messages returned by the backend related to the executed action. :raises BadRequestError: When ticket does not exist :raises InvalidUseError: If the `action` parameter is invalid :raises UnexpectedResponseError: If the response from RT is not as expected """ if action not in ('correspond', 'comment'): # pragma: no cover raise InvalidUseError('action must be either "correspond" or "comment"') post_data: typing.Dict[str, typing.Any] = { 'Content': content, 'ContentType': content_type, } # Adding a one-shot cc/bcc is not supported by RT5.0.2 # if cc: # post_data['Cc'] = cc # noqa: ERA001 # # if bcc: # post_data['Bcc'] = bcc # noqa: ERA001 res = await self.__request(f'ticket/{ticket_id}/{action}', json_data=post_data, attachments=attachments) if not isinstance(res, list): # pragma: no cover raise UnexpectedResponseError(str(res)) self.logger.debug(res) return res async def reply( self, ticket_id: typing.Union[str, int], content: str = '', content_type: TYPE_CONTENT_TYPE = 'text/plain', attachments: typing.Optional[typing.Sequence[Attachment]] = None, ) -> bool: """Sends email message to the contacts in ``Requestors`` field of given ticket with subject as is set in ``Subject`` field. :param ticket_id: ID of ticket to which message belongs :param content: Content of email message (text/plain or text/html) :param content_type: Content type of email message, default to text/plain :param attachments: Optional list of :py:class:`~rt.rest2.Attachment` objects :returns: ``True`` Operation was successful ``False`` Sending failed (status code != 200) :raises BadRequestError: When ticket does not exist :raises UnexpectedResponseError: If the response from RT is not as expected """ msg = await self.__correspond(ticket_id, content, 'correspond', content_type, attachments) if not (isinstance(msg, list) and len(msg) >= 1): # pragma: no cover raise UnexpectedResponseError(str(msg)) return bool(msg[0]) async def delete_ticket(self, ticket_id: typing.Union[str, int]) -> None: """Mark a ticket as deleted. :param ticket_id: ID of ticket :raises BadRequestError: When user does not exist :raises NotFoundError: If the user does not exist :raises UnexpectedResponseError: If the response from RT is not as expected """ try: await self.__request_delete(f'ticket/{ticket_id}') except UnexpectedResponseError as exc: if exc.status_code == 400: # pragma: no cover raise rt.exceptions.BadRequestError(exc.response_message) from exc if exc.status_code == 204: return raise # pragma: no cover async def comment( self, ticket_id: typing.Union[str, int], content: str = '', content_type: TYPE_CONTENT_TYPE = 'text/plain', attachments: typing.Optional[typing.Sequence[Attachment]] = None, ) -> bool: """Adds comment to the given ticket. :param ticket_id: ID of ticket to which comment belongs :param content: Content of comment :param content_type: Content type of comment, default to text/plain :param attachments: Optional list of :py:class:`~rt.rest2.Attachment` objects :returns: ``True`` Operation was successful ``False`` Sending failed (status code != 200) :raises BadRequestError: When ticket does not exist :raises UnexpectedResponseError: If the response from RT is not as expected """ msg = await self.__correspond(ticket_id, content, 'comment', content_type, attachments) if not (isinstance(msg, list) and len(msg) >= 1): # pragma: no cover raise UnexpectedResponseError(str(msg)) return bool(msg[0]) async def get_attachments(self, ticket_id: typing.Union[str, int]) -> collections.abc.AsyncIterator: """Get attachment list for a given ticket. Example of a return result: .. code-block:: json [ { "id": "17", "Filename": "README.rst", "ContentLength": "3578", "type": "attachment", "ContentType": "test/plain", "_url": "http://localhost:8080/REST/2.0/attachment/17" } ] :param ticket_id: ID of ticket :returns: Iterator of attachments belonging to given ticket. collections.abc.AsyncIterator[typing.Dict[str, str]] """ async for item in self.__paged_request( f'ticket/{ticket_id}/attachments', json_data=[{'field': 'Filename', 'operator': 'IS NOT', 'value': ''}], params={'fields': 'Filename,ContentType,ContentLength'}, ): yield item async def get_attachments_ids(self, ticket_id: typing.Union[str, int]) -> collections.abc.AsyncIterator: """Get IDs of attachments for given ticket. :param ticket_id: ID of ticket :returns: Iterator of IDs (type int) of attachments belonging to given ticket. collections.abc.AsyncIterator[int] """ async for item in self.__paged_request( f'ticket/{ticket_id}/attachments', json_data=[{'field': 'Filename', 'operator': 'IS NOT', 'value': ''}], ): yield int(item['id']) async def get_attachment(self, attachment_id: typing.Union[str, int]) -> typing.Optional[dict]: """Get attachment. :param attachment_id: ID of attachment to fetch :returns: Attachment as dictionary with these keys: * Transaction * ContentType * Parent * Creator * Created * Filename * Content (base64 encoded string) * 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 Set of headers available depends on mailservers sending emails not on Request Tracker! :raises UnexpectedMessageFormatError: Unexpected format of returned message. :raises NotFoundError: If attachment with specified ID does not exist. """ res = await self.__request(f'attachment/{attachment_id}') if not (res is None or isinstance(res, dict)): # pragma: no cover raise UnexpectedResponseError(str(res)) return res async def get_user(self, user_id: typing.Union[int, str]) -> typing.Dict[str, typing.Any]: """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 :raises UnexpectedMessageFormatError: In case that returned status code is not 200 :raises NotFoundError: If the user does not exist. """ res = await self.__request(f'user/{user_id}') if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return res async def user_exists(self, user_id: typing.Union[int, str], privileged: bool = True) -> bool: """Check if a given user_id exists. :parameter user_id: User ID to lookup. :parameter privileged: If set to True, only return True if the user_id was found and is privileged. :returns: bool: True on success, else False. """ try: user_dict = await self.get_user(user_id) if not privileged or (privileged and user_dict.get('Privileged', '0') == 1): return True except rt.exceptions.NotFoundError: return False return False async def create_user(self, user_name: str, email_address: str, **kwargs: typing.Any) -> str: """Create user. :param user_name: Username (login for privileged, required) :param email_address: Email address (required) :param kwargs: Optional fields to set (see edit_user) :returns: ID of new user or False when create fails :raises BadRequestError: When user already exists :raises InvalidUseError: When invalid fields are set :raises UnexpectedResponseError: If the response from RT is not as expected """ 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', 'CustomFields', } invalid_fields = [] post_data = { 'Name': user_name, 'EmailAddress': email_address, } for k, v in kwargs.items(): if k not in valid_fields: invalid_fields.append(k) else: post_data[k] = v if invalid_fields: raise InvalidUseError(f"""Unsupported names of fields: {', '.join(invalid_fields)}.""") try: res = await self.__request('user', json_data=post_data) except UnexpectedResponseError as exc: # pragma: no cover if exc.status_code == 400: raise rt.exceptions.BadRequestError(exc.response_message) from exc raise if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return res['id'] async def edit_user(self, user_id: typing.Union[str, int], **kwargs: typing.Any) -> typing.List[str]: """Edit user profile. :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: List of status messages :raises BadRequestError: When user does not exist :raises InvalidUseError: When invalid fields are set :raises UnexpectedResponseError: If the response from RT is not as expected """ 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', 'CustomFields', } invalid_fields = [] post_data = {} for key, val in kwargs.items(): if key not in valid_fields: invalid_fields.append(key) else: post_data[key] = val if invalid_fields: raise InvalidUseError(f"""Unsupported names of fields: {', '.join(invalid_fields)}.""") try: ret = await self.__request_put(f'user/{user_id}', json_data=post_data) except UnexpectedResponseError as exc: # pragma: no cover if exc.status_code == 400: raise rt.exceptions.BadRequestError(exc.response_message) from exc raise return ret async def delete_user(self, user_id: typing.Union[str, int]) -> None: """Disable a user. :param user_id: Identification of a user by name (str) or ID (int) :raises BadRequestError: When user does not exist :raises NotFoundError: If the user does not exist :raises UnexpectedResponseError: If the response from RT is not as expected """ try: _ = await self.__request_delete(f'user/{user_id}') except UnexpectedResponseError as exc: if exc.status_code == 400: # pragma: no cover raise rt.exceptions.BadRequestError(exc.response_message) from exc if exc.status_code == 204: return raise # pragma: no cover async def get_queue(self, queue_id: typing.Union[str, int]) -> typing.Optional[typing.Dict[str, typing.Any]]: """Get queue details. Example of a return result: .. code-block:: json { "LastUpdatedBy": { "_url": "http://localhost:8080/REST/2.0/user/RT_System", "type": "user", "id": "RT_System" }, "LastUpdated": "2022-03-06T04:53:38Z", "AdminCc": [], "SortOrder": "0", "CorrespondAddress": "", "Creator": { "id": "RT_System", "_url": "http://localhost:8080/REST/2.0/user/RT_System", "type": "user" }, "Lifecycle": "default", "Cc": [], "Created": "2022-03-06T04:53:38Z", "_hyperlinks": [ { "_url": "http://localhost:8080/REST/2.0/queue/1", "type": "queue", "id": 1, "ref": "self" }, { "ref": "history", "_url": "http://localhost:8080/REST/2.0/queue/1/history" }, { "ref": "create", "type": "ticket", "_url": "http://localhost:8080/REST/2.0/ticket?Queue=1" } ], "SLADisabled": "1", "Name": "General", "TicketCustomFields": [], "Disabled": "0", "TicketTransactionCustomFields": [], "CustomFields": [], "Description": "The default queue", "CommentAddress": "", "id": 1 } :param queue_id: Identification of queue by name (str) or queue ID (int) :returns: Queue details as a dictionary :raises UnexpectedMessageFormatError: In case that returned status code is not 200 :raises NotFoundError: In case the queue does not exist """ res = await self.__request(f'queue/{queue_id}') if not (res is None or isinstance(res, dict)): # pragma: no cover raise UnexpectedResponseError(str(res)) return res async def get_all_queues(self, include_disabled: bool = False) -> collections.abc.AsyncIterator: """Return a list of all queues. Example of a return result: .. code-block:: json [ { "InitialPriority": "", "_url": "http://localhost:8080/REST/2.0/queue/1", "type": "queue", "Name": "General", "DefaultDueIn": "", "Description": "The default queue", "CorrespondAddress": "", "CommentAddress": "", "id": "1", "FinalPriority": "" } ] :param include_disabled: Set to True to also return disabled queues. :returns: Iterator of dictionaries containing basic information on all queues. collections.abc.AsyncIterator[typing.Dict[str, typing.Any]] :raises UnexpectedMessageFormatError: In case that returned status code is not 200 """ params = { 'fields': 'Name,Description,CorrespondAddress,CommentAddress,InitialPriority,FinalPriority,DefaultDueIn', 'find_disabled_rows': int(include_disabled), } async for item in self.__paged_request('queues/all', params=params): yield item async def edit_queue(self, queue_id: typing.Union[str, int], **kwargs: typing.Any) -> typing.List[str]: """Edit queue. :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 * Disabled * SLADisabled * Lifecycle * SortOrder :returns: List of status messages :raises BadRequestError: When queue does not exist :raises InvalidUseError: When invalid fields are set :raises UnexpectedResponseError: If the response from RT is not as expected """ valid_fields = { 'Name', 'Description', 'CorrespondAddress', 'CommentAddress', 'Disabled', 'SLADisabled', 'Lifecycle', 'SortOrder', } invalid_fields = [] post_data = {} for key, val in kwargs.items(): if key not in valid_fields: invalid_fields.append(key) else: post_data[key] = val if invalid_fields: raise InvalidUseError(f"""Unsupported names of fields: {', '.join(invalid_fields)}.""") try: ret = await self.__request_put(f'queue/{queue_id}', json_data=post_data) except UnexpectedResponseError as exc: # pragma: no cover if exc.status_code == 400: raise rt.exceptions.BadRequestError(exc.response_message) from exc raise return ret async def create_queue(self, name: str, **kwargs: typing.Any) -> int: """Create queue. :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 BadRequestError: When queue already exists :raises InvalidUseError: When invalid fields are set :raises UnexpectedResponseError: If the response from RT is not as expected """ valid_fields = { 'Name', 'Description', 'CorrespondAddress', 'CommentAddress', 'Disabled', 'SLADisabled', 'Lifecycle', 'SortOrder', } invalid_fields = [] post_data = {'Name': name} for key, val in kwargs.items(): if key not in valid_fields: invalid_fields.append(key) else: post_data[key] = val if invalid_fields: raise InvalidUseError(f"""Unsupported names of fields: {', '.join(invalid_fields)}.""") try: res = await self.__request('queue', json_data=post_data) except UnexpectedResponseError as exc: # pragma: no cover if exc.status_code == 400: raise rt.exceptions.BadRequestError(exc.response_message) from exc raise if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return int(res['id']) async def delete_queue(self, queue_id: typing.Union[str, int]) -> None: """Disable a queue. :param queue_id: Identification of queue by name (str) or ID (int) :returns: ID or name of edited queue or False when edit fails :raises BadRequestError: When queue does not exist :raises NotFoundError: If the queue does not exist :raises UnexpectedResponseError: If the response from RT is not as expected """ try: _ = await self.__request_delete(f'queue/{queue_id}') except UnexpectedResponseError as exc: # pragma: no cover if exc.status_code == 400: raise rt.exceptions.BadRequestError(exc.response_message) from exc if exc.status_code == 204: return raise # pragma: no cover async def get_links(self, ticket_id: typing.Union[str, int]) -> typing.List[typing.Dict[str, str]]: """Gets the ticket links for a single ticket. Example of a return result: .. code-block:: json [ { "id": "13", "type": "ticket", "_url": "http://localhost:8080/REST/2.0/ticket/13", "ref": "depends-on" } ] :param ticket_id: ticket ID :returns: Links as lists of strings in dictionary with these keys (just those which are defined): * depends-on * depended-on-by * parent * child * refers-to * referred-to-by None is returned if ticket does not exist. :raises UnexpectedMessageFormatError: In case that returned status code is not 200 """ ticket = await self.get_ticket(ticket_id) return [link for link in ticket['_hyperlinks'] if link.get('type', '') == 'ticket' and link['ref'] != 'self'] async def edit_link( self, ticket_id: typing.Union[str, int], link_name: TYPE_VALID_TICKET_LINK_NAMES, link_value: typing.Union[str, int], delete: bool = False, ) -> bool: """Creates or deletes a link between the specified tickets. :param ticket_id: ID of ticket to edit :param link_name: Name of link to edit ('Parent', 'Child', 'RefersTo', 'ReferredToBy', 'DependsOn', 'DependedOnBy') :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 InvalidUseError: When none or more than one link is specified. Also, when a wrong link name is used or when trying to link to a deleted ticket. """ if link_name not in VALID_TICKET_LINK_NAMES: raise InvalidUseError(f'Unsupported link name. Use one of "{", ".join(VALID_TICKET_LINK_NAMES)}".') if delete: json_data = {f'Delete{link_name}': link_value} else: json_data = {f'Add{link_name}': link_value} msg = await self.__request_put(f'ticket/{ticket_id}', json_data=json_data) if msg and isinstance(msg, list): if msg[0].startswith("Couldn't resolve"): raise NotFoundError(msg[0]) if 'not allowed' in msg[0]: raise InvalidUseError(msg[0]) return True async def merge_ticket(self, ticket_id: typing.Union[str, int], into_id: typing.Union[str, int]) -> bool: """Merge ticket into another. :param ticket_id: ID of ticket to be merged :param into_id: 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. :raises UnexpectedResponseError: If the response from RT is not as expected """ msg = await self.__request_put(f'ticket/{ticket_id}', json_data={'MergeInto': into_id}) if not isinstance(msg, list) or len(msg) != 1: # pragma: no cover raise UnexpectedResponseError(str(msg)) self.logger.debug(str(msg)) return msg[0].lower() == 'merge successful' async 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. :raises UnexpectedResponseError: If the response from RT is not as expected """ msg = await self.__request_put(f'ticket/{ticket_id}/take') if not isinstance(msg, list) or len(msg) != 1: # pragma: no cover raise UnexpectedResponseError(str(msg)) self.logger.debug(str(msg)) return msg[0].lower().startswith('owner changed') async 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. :raises UnexpectedResponseError: If the response from RT is not as expected """ msg = await self.__request_put(f'ticket/{ticket_id}/untake') if not isinstance(msg, list) or len(msg) != 1: # pragma: no cover raise UnexpectedResponseError(str(msg)) self.logger.debug(str(msg)) return msg[0].lower().startswith('owner changed') async 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. :raises UnexpectedResponseError: If the response from RT is not as expected """ msg = await self.__request_put(f'ticket/{ticket_id}/steal') if not isinstance(msg, list) or len(msg) != 1: # pragma: no cover raise UnexpectedResponseError(str(msg)) self.logger.debug(str(msg)) return msg[0].lower().startswith('owner changed') ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1725658667.0468843 rt-3.2.0/rt.egg-info/0000755000175100001770000000000014666673053013705 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658667.0 rt-3.2.0/rt.egg-info/PKG-INFO0000644000175100001770000001446614666673053015015 0ustar00runnerdockerMetadata-Version: 2.1 Name: rt Version: 3.2.0 Summary: Python interface to Request Tracker API Author-email: Georges Toth License: GNU General Public License v3 (GPLv3) Project-URL: Homepage, https://github.com/python-rt/python-rt Project-URL: Documentation, https://python-rt.readthedocs.io/ Project-URL: Source, https://github.com/python-rt/python-rt Project-URL: Tracker, https://github.com/python-rt/python-rt/issues Project-URL: Changelog, https://github.com/python-rt/python-rt/blob/master/CHANGELOG.md 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.8 Description-Content-Type: text/x-rst License-File: LICENSE License-File: AUTHORS Requires-Dist: requests Requires-Dist: httpx Provides-Extra: docs Requires-Dist: sphinx; extra == "docs" Requires-Dist: sphinx-autodoc-typehints; extra == "docs" Requires-Dist: sphinx-rtd-theme; extra == "docs" Requires-Dist: furo; extra == "docs" Requires-Dist: sphinx-copybutton; extra == "docs" Provides-Extra: dev Requires-Dist: mypy; extra == "dev" Requires-Dist: ruff; extra == "dev" Requires-Dist: types-requests; extra == "dev" Requires-Dist: codespell; extra == "dev" Requires-Dist: bandit; extra == "dev" Provides-Extra: test Requires-Dist: pytest; extra == "test" Requires-Dist: pytest-asyncio; extra == "test" Requires-Dist: coverage; extra == "test" .. image:: https://codebeat.co/badges/a52cfe15-b824-435b-a594-4bf2be2fb06f :target: https://codebeat.co/projects/github-com-python-rt-python-rt-master :alt: codebeat badge .. image:: https://github.com/python-rt/python-rt/actions/workflows/test_lint.yml/badge.svg :target: https://github.com/python-rt/python-rt/actions/workflows/test_lint.yml :alt: tests .. image:: https://readthedocs.org/projects/python-rt/badge/?version=stable :target: https://python-rt.readthedocs.io/en/stable/?badge=stable :alt: Documentation Status .. image:: https://badge.fury.io/py/rt.svg :target: https://badge.fury.io/py/rt ============================================== Rt - Python interface to Request Tracker API ============================================== Python implementation of REST API described here: - https://rt-wiki.bestpractical.com/wiki/REST - https://docs.bestpractical.com/rt/5.0.2/RT/REST2.html .. csv-table:: Python version compatibility: :header: "Python", "rt" :widths: 15, 15 "2.7", "< 2.0.0" ">= 3.5, <3.7", ">= 2.0.0, < 3.0.0" ">= 3.7", ">= 3.0.0, < 3.1.0" ">= 3.8", ">= 3.0.0" ℹ️ **Note**: Please note that starting with the major release of v3.0.0, this library requires Python version >= 3.8. See the *Python version compatibility* table above for more detailed information. ⚡ **Note**: As of version 3.1.0, this library is async compatible. Usage:: import rt.rest2 import httpx tracker = rt.rest2.AsyncRt('http://localhost/rt/REST/2.0/', http_auth=httpx.BasicAuth('root', 'password')) ⚠️ **Warning**: Though version 3.x still supports RT REST API version 1, it contains minor breaking changes. Please see the changelog in the documentation for details. Requirements ============ This module uses following Python modules: - requests (http://docs.python-requests.org/) - requests-toolbelt (https://pypi.org/project/requests-toolbelt/) - typing-extensions (depending on python version) Documentation ============= https://python-rt.readthedocs.io/en/latest/ 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 registry 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.rest2 >>> import httpx >>> tracker = rt.rest2.Rt('http://localhost/rt/REST/2.0/', http_auth=httpx.BasicAuth('root', 'password')) >>> map(lambda x: x['id'], tracker.search(Queue='helpdesk', Status='open')) ['1', '2', '10', '15'] >>> tracker.create_ticket(queue='helpdesk', \ ... subject='Coffee (important)', content='Help I Ran Out of Coffee!') 19 >>> tracker.edit_ticket(19, Requestor='addicted@example.com') True >>> tracker.reply(19, content='Do you know Starbucks?') True Get the last important updates from a specific queue that have been updated recently:: >>> import datetime >>> import base64 >>> import rt.rest2 >>> import httpx >>> tracker = rt.rest2.Rt('http://localhost/rt/REST/2.0/', http_auth=httpx.BasicAuth('root', 'password')) >>> 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'] >>> history = tracker.get_ticket_history(id) >>> last_update = list(reversed([h for h in history if h['Type'] in ('Correspond', 'Comment')])) >>> hid = tracker.get_transaction(last_update[0]['id'] if last_update else history[0]['id']) >>> >>> attachment_id = None >>> for k in hid['_hyperlinks']: >>> if k['ref'] == 'attachment': >>> attachment_id = k['_url'].rsplit('/', 1)[1] >>> break >>> >>> if attachment_id is not None: >>> attachment = c.get_attachment(attachment_id) >>> if attachment['Content'] is not None: >>> content = base64.b64decode(attachment['Content']).decode() >>> print(content) 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, issue tracking and git repository: https://github.com/python-rt/python-rt ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658667.0 rt-3.2.0/rt.egg-info/SOURCES.txt0000644000175100001770000000114514666673053015572 0ustar00runnerdocker.codespell_ignore .editorconfig AUTHORS CHANGELOG.md LICENSE MANIFEST.in README.rst noxfile.py pyproject.toml run_nox.sh setup.py doc/Makefile doc/changelog.rst doc/conf.py doc/exceptions.rst doc/glossary.rst doc/index.rst doc/rest1.rst doc/rest2.rst doc/usage.rst rt/__init__.py rt/exceptions.py rt/py.typed rt/rest1.py rt/rest2.py rt.egg-info/PKG-INFO rt.egg-info/SOURCES.txt rt.egg-info/dependency_links.txt rt.egg-info/requires.txt rt.egg-info/top_level.txt tests/__init__.py tests/conftest.py tests/test_basic.py tests/test_basic_async.py tests/test_rest1.py tests/test_tickets.py tests/test_tickets_async.py././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658667.0 rt-3.2.0/rt.egg-info/dependency_links.txt0000644000175100001770000000000114666673053017753 0ustar00runnerdocker ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658667.0 rt-3.2.0/rt.egg-info/requires.txt0000644000175100001770000000026714666673053016312 0ustar00runnerdockerrequests httpx [dev] mypy ruff types-requests codespell bandit [docs] sphinx sphinx-autodoc-typehints sphinx-rtd-theme furo sphinx-copybutton [test] pytest pytest-asyncio coverage ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658667.0 rt-3.2.0/rt.egg-info/top_level.txt0000644000175100001770000000000314666673053016430 0ustar00runnerdockerrt ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/run_nox.sh0000755000175100001770000000036514666673042013617 0ustar00runnerdocker#!/bin/bash echo "Run this script with -R in order to not re-install dependencies on every run." echo "" echo "" export PYENV_ROOT="$HOME/.pyenv" [[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH" eval "$(pyenv init -)" nox "$@" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1725658667.0468843 rt-3.2.0/setup.cfg0000644000175100001770000000004614666673053013407 0ustar00runnerdocker[egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/setup.py0000644000175100001770000000004714666673042013277 0ustar00runnerdockerimport setuptools setuptools.setup() ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1725658667.0468843 rt-3.2.0/tests/0000755000175100001770000000000014666673053012730 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/tests/__init__.py0000644000175100001770000000032114666673042015033 0ustar00runnerdocker# ruff: noqa: S311 import random import string def random_string(length: int = 15) -> str: """Return a random string.""" return ''.join([random.choice(string.ascii_letters) for i in range(length)]) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/tests/conftest.py0000644000175100001770000000132414666673042015125 0ustar00runnerdocker# ruff: noqa: S105 import typing import httpx import pytest if typing.TYPE_CHECKING: import rt.rest2 # blank setup defaults RT_URL = 'http://localhost:8080/REST/2.0/' RT_USER = 'root' RT_PASSWORD = 'password' RT_QUEUE = 'General' @pytest.fixture(scope='session') def rt_connection() -> 'rt.rest2.Rt': """Setup a generic connection.""" import rt.rest2 return rt.rest2.Rt(url=RT_URL, http_auth=httpx.BasicAuth(RT_USER, RT_PASSWORD), http_timeout=None) @pytest.fixture(scope='session') def async_rt_connection() -> 'rt.rest2.AsyncRt': """Setup a generic connection.""" import rt.rest2 return rt.rest2.AsyncRt(url=RT_URL, http_auth=httpx.BasicAuth(RT_USER, RT_PASSWORD), http_timeout=None) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/tests/test_basic.py0000644000175100001770000004153214666673042015425 0ustar00runnerdocker"""Tests for python-rt / REST2 - Python interface to Request Tracker :term:`API`.""" # ruff: noqa: S101, S105, S311 __license__ = """ Copyright (C) 2013 CZ.NIC, z.s.p.o. Copyright (c) 2021 CERT Gouvernemental (GOVCERT.LU) 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" ', '"Georges Toth" ', ] import base64 import random import string import typing import httpx import pytest import rt.exceptions import rt.rest2 from . import random_string RT_URL = 'http://localhost:8080/REST/2.0/' RT_USER = 'root' RT_PASSWORD = 'password' RT_QUEUE = 'General' def test_get_user(rt_connection: rt.rest2.Rt): user = rt_connection.get_user(RT_USER) assert user['Name'] == RT_USER assert '@' in user['EmailAddress'] assert user['Privileged'] == 1 def test_invalid_api_url(): with pytest.raises(ValueError): rt.rest2.Rt(url='https://example.com', http_auth=httpx.BasicAuth('dummy', 'dummy')) def test_ticket_operations(rt_connection: rt.rest2.Rt): ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) # empty search result search_result = list(rt_connection.search(Subject=ticket_subject)) assert not len(search_result) # create ticket_id = rt_connection.create_ticket(subject=ticket_subject, content=ticket_text, queue=RT_QUEUE) assert ticket_id > -1 # search search_result = list(rt_connection.search(Subject=ticket_subject)) assert len(search_result) == 1 assert search_result[0]['id'] == str(ticket_id) assert search_result[0]['Status'] == 'new' # search with query_format field list search_result = list(rt_connection.search(Subject=ticket_subject, query_format=['Status','Subject'])) assert len(search_result) == 1 assert search_result[0]['Subject'] == str(ticket_subject) assert search_result[0]['Status'] == 'new' assert 'Requestor' not in search_result[0].keys() # raw search search_result = list(rt_connection.search(raw_query=f'Subject="{ticket_subject}"')) assert len(search_result) == 1 assert search_result[0]['id'] == str(ticket_id) assert search_result[0]['Status'] == 'new' # get ticket ticket = rt_connection.get_ticket(ticket_id) search_result[0]['id'] = int(search_result[0]['id']) for k in search_result[0]: if k.startswith('_') or k in ('type', 'CustomFields'): continue assert k in ticket assert ticket[k] == search_result[0][k] # edit ticket requestors = ['tester1@example.com', 'tester2@example.com'] rt_connection.edit_ticket(ticket_id, Status='open', Requestor=requestors) # get ticket (edited) ticket = rt_connection.get_ticket(ticket_id) assert ticket['Status'] == 'open' for requestor in ticket['Requestor']: assert requestor['id'] in requestors for requestor in requestors: found = False for _requestor in ticket['Requestor']: if _requestor['id'] == requestor: found = True break assert found # get history hist = rt_connection.get_ticket_history(ticket_id) assert len(hist) > 0 transaction = rt_connection.get_transaction(hist[0]['id']) found = False for hyperlink in transaction['_hyperlinks']: if hyperlink['ref'] == 'attachment': attachment_id = hyperlink['_url'].rsplit('/', 1)[1] attachment = base64.b64decode(rt_connection.get_attachment(attachment_id)['Content']).decode('utf-8') found = True assert attachment == ticket_text break assert found # get_short_history short_hist = rt_connection.get_ticket_history(ticket_id) assert len(short_hist) > 0 assert short_hist[0]['Type'] == 'Create' assert short_hist[0]['Creator']['Name'] == RT_USER # create 2nd ticket ticket2_subject = 'Testing issue ' + ''.join([random.choice(string.ascii_letters) for i in range(15)]) ticket2_id = rt_connection.create_ticket(queue=RT_QUEUE, subject=ticket2_subject) assert ticket2_id > -1 # edit link assert rt_connection.edit_link(ticket_id, 'DependsOn', ticket2_id) # get links links1 = rt_connection.get_links(ticket_id) found = False for link in links1: if link['ref'] == 'depends-on' and link['id'] == str(ticket2_id): found = True assert found links2 = rt_connection.get_links(ticket2_id) found = False for link in links2: if link['ref'] == 'depended-on-by' and link['id'] == str(ticket_id): found = True assert found # 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.' attachment = rt.rest2.Attachment(attachment_name, 'text/plain', attachment_content) assert rt_connection.reply(ticket_id, content=reply_text, attachments=[attachment]) # reply with a comment reply_text = 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' assert rt_connection.comment(ticket_id, content=reply_text) # reply with a html content reply_text = 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' assert rt_connection.reply(ticket_id, content=reply_text, content_type='text/html') # attachments list at_list = rt_connection.get_attachments(ticket_id) assert at_list at_names = [at['Filename'] for at in at_list] assert attachment_name in at_names # get the attachment and compare it's content at_id = at_list[at_names.index(attachment_name)]['id'] at_content = base64.b64decode(rt_connection.get_attachment(at_id)['Content']) assert at_content == attachment_content # set invalid user with pytest.raises(rt.exceptions.NotFoundError): rt_connection.edit_ticket(ticket_id, Owner='invalid_user') # set invalid queue with pytest.raises(rt.exceptions.NotFoundError): rt_connection.edit_ticket(ticket_id, Queue='invalid_queue') # edit invalid ticket with pytest.raises(rt.exceptions.NotFoundError): rt_connection.edit_ticket(999999999, Owner='Nobody') # merge tickets assert rt_connection.merge_ticket(ticket2_id, ticket_id) # delete ticket assert rt_connection.delete_ticket(ticket_id) is None # delete invalid ticket with pytest.raises(rt.exceptions.NotFoundError): assert rt_connection.delete_ticket(999999999) def test_attachments_create(rt_connection: rt.rest2.Rt): """Create a ticket with a random (>= 2) number of attachments and verify that they have been successfully added to the ticket.""" ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) attachment_count = random.randint(2, 10) attachments = [] for _i in range(attachment_count): attachment_content = random_string(length=100).encode() attachment_name = f'attachment-{random_string(length=10)}.txt' attachments.append(rt.rest2.Attachment(attachment_name, 'text/plain', attachment_content)) # create ticket_id = rt_connection.create_ticket(subject=ticket_subject, content=ticket_text, queue=RT_QUEUE, attachments=attachments) assert ticket_id > -1 # get ticket ticket = rt_connection.get_ticket(ticket_id) assert int(ticket['id']) == ticket_id # attachments list at_list = rt_connection.get_attachments(ticket_id) assert at_list assert len(at_list) == len(attachments) at_names = [at['Filename'] for at in at_list] for k in attachments: assert k.file_name in at_names # get the attachment and compare it's content at_id = at_list[at_names.index(k.file_name)]['id'] at_content = base64.b64decode(rt_connection.get_attachment(at_id)['Content']) assert at_content == k.file_content def test_attachments_comment(rt_connection: rt.rest2.Rt): """Create a ticket and comment to it with a random (>= 2) number of attachments and verify that they have been successfully added to the ticket.""" ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) # create ticket_id = rt_connection.create_ticket(subject=ticket_subject, content=ticket_text, queue=RT_QUEUE) assert ticket_id > -1 attachment_count = random.randint(2, 10) attachments = [] for _i in range(attachment_count): attachment_content = random_string(length=100).encode() attachment_name = f'attachment-{random_string(length=10)}.txt' attachments.append(rt.rest2.Attachment(attachment_name, 'text/plain', attachment_content)) # comment with attachments ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) comment_success = rt_connection.comment(ticket_id=ticket_id, content=ticket_text, attachments=attachments) assert comment_success # attachments list at_list = rt_connection.get_attachments(ticket_id) assert at_list assert len(at_list) == len(attachments) at_names = [at['Filename'] for at in at_list] for k in attachments: assert k.file_name in at_names # get the attachment and compare it's content at_id = at_list[at_names.index(k.file_name)]['id'] at_content = base64.b64decode(rt_connection.get_attachment(at_id)['Content']) assert at_content == k.file_content def test_attachments_reply(rt_connection: rt.rest2.Rt): """Create a ticket and reply to it with a random (>= 2) number of attachments and verify that they have been successfully added to the ticket.""" ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) # create ticket_id = rt_connection.create_ticket(subject=ticket_subject, content=ticket_text, queue=RT_QUEUE) assert ticket_id > -1 attachment_count = random.randint(2, 10) attachments = [] for _i in range(attachment_count): attachment_content = random_string(length=100).encode() attachment_name = f'attachment-{random_string(length=10)}.txt' attachments.append(rt.rest2.Attachment(attachment_name, 'text/plain', attachment_content)) # comment with attachments ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) comment_success = rt_connection.reply(ticket_id=ticket_id, content=ticket_text, attachments=attachments) assert comment_success # attachments list at_list = rt_connection.get_attachments(ticket_id) assert at_list assert len(at_list) == len(attachments) at_names = [at['Filename'] for at in at_list] for k in attachments: assert k.file_name in at_names # get the attachment and compare it's content at_id = at_list[at_names.index(k.file_name)]['id'] at_content = base64.b64decode(rt_connection.get_attachment(at_id)['Content']) assert at_content == k.file_content def test_ticket_operations_admincc_cc(rt_connection: rt.rest2.Rt): ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) def compare_list(from_list: typing.List[str], ticket_list: typing.List[dict]) -> bool: """Lists (Requestor, AdminCc, Cc) returned from REST2 contain a list of dicts with additional user information. Thus a simple compare of both lists is not enough. """ if len(from_list) != len(ticket_list): return False to_list = [entry['id'] for entry in ticket_list] diff = set(from_list) ^ set(to_list) return not diff ticket_id = rt_connection.create_ticket(subject=ticket_subject, content=ticket_text, queue=RT_QUEUE) assert ticket_id > -1 # make sure Requestor, AdminCc and Cc are present and an empty list, as would be expected ticket = rt_connection.get_ticket(ticket_id) assert len(ticket['Requestor']) >= 0 assert len(ticket['AdminCc']) >= 0 assert len(ticket['Cc']) >= 0 # set requestors requestors = ['tester1@example.com', 'tester2@example.com'] rt_connection.edit_ticket(ticket_id, Status='open', Requestor=requestors) # verify ticket = rt_connection.get_ticket(ticket_id) assert compare_list(requestors, ticket['Requestor']) # set admincc admincc = ['tester2@example.com', 'tester3@example.com'] rt_connection.edit_ticket(ticket_id, Status='open', AdminCc=admincc) # verify ticket = rt_connection.get_ticket(ticket_id) assert compare_list(requestors, ticket['Requestor']) assert compare_list(admincc, ticket['AdminCc']) # update admincc admincc = ['tester2@example.com', 'tester3@example.com', 'tester4@example.com'] rt_connection.edit_ticket(ticket_id, Status='open', AdminCc=admincc) # verify ticket = rt_connection.get_ticket(ticket_id) assert compare_list(requestors, ticket['Requestor']) assert compare_list(admincc, ticket['AdminCc']) # unset requestors and admincc requestors = [] admincc = [] rt_connection.edit_ticket(ticket_id, Status='open', Requestor=requestors, AdminCc=admincc) # verify ticket = rt_connection.get_ticket(ticket_id) assert compare_list(requestors, ticket['Requestor']) assert compare_list(admincc, ticket['AdminCc']) def test_users(rt_connection: rt.rest2.Rt): assert rt_connection.get_user('tester1@example.com') is not None assert rt_connection.user_exists('root', privileged=True) is True assert rt_connection.user_exists('tester1@example.com', privileged=False) is True assert rt_connection.user_exists('tester1@example.com', privileged=True) is False assert rt_connection.user_exists('does-not-exist@example.com') is False random_user_name = f'username_{random_string()}' random_user_email = f'user-{random_string()}@example.com' random_user_password = f'user_password-{random_string()}' assert rt_connection.create_user(random_user_name, random_user_email, Password=random_user_password) == random_user_name rt_connection.delete_user(random_user_name) with pytest.raises(rt.exceptions.NotFoundError): rt_connection.delete_user(f'username_{random_string()}') assert rt_connection.edit_user(user_id=random_user_name, RealName=random_user_name) def test_queues(rt_connection: rt.rest2.Rt): queue = rt_connection.get_queue(RT_QUEUE) assert queue['Name'] == RT_QUEUE queues = rt_connection.get_all_queues() assert len(queues) >= 1 found = False for q in queues: if q['Name'] == RT_QUEUE: found = True assert found random_queue_name = f'Queue {random_string()}' random_queue_email = f'q-{random_string()}@example.com' rt_connection.create_queue(random_queue_name, CorrespondAddress=random_queue_email, Description='test queue') queues = rt_connection.get_all_queues() found = False for q in queues: if q['Name'] == random_queue_name: found = True assert found rt_connection.edit_queue(random_queue_name, Disabled='1') assert rt_connection.get_queue(random_queue_name)['Disabled'] == '1' rt_connection.edit_queue(random_queue_name, Disabled='0') assert rt_connection.get_queue(random_queue_name)['Disabled'] == '0' with pytest.raises(rt.exceptions.NotFoundError): rt_connection.get_queue('InvalidName') rt_connection.delete_queue(random_queue_name) with pytest.raises(rt.exceptions.NotFoundError): rt_connection.delete_queue(f'Queue {random_string()}') ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/tests/test_basic_async.py0000644000175100001770000004434014666673042016622 0ustar00runnerdocker"""Tests for python-rt / REST2 - Python interface to Request Tracker :term:`API`.""" # ruff: noqa: S101, S105, S311 __license__ = """ Copyright (C) 2013 CZ.NIC, z.s.p.o. Copyright (c) 2021 CERT Gouvernemental (GOVCERT.LU) 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" ', '"Georges Toth" ', ] import base64 import random import string import typing import httpx import pytest import rt.exceptions import rt.rest2 from . import random_string RT_URL = 'http://localhost:8080/REST/2.0/' RT_USER = 'root' RT_PASSWORD = 'password' RT_QUEUE = 'General' @pytest.mark.asyncio async def test_get_user(async_rt_connection: rt.rest2.AsyncRt): user = await async_rt_connection.get_user(RT_USER) assert user['Name'] == RT_USER assert '@' in user['EmailAddress'] assert user['Privileged'] == 1 @pytest.mark.asyncio async def test_invalid_api_url(): with pytest.raises(ValueError): rt.rest2.AsyncRt(url='https://example.com', http_auth=httpx.BasicAuth('dummy', 'dummy')) @pytest.mark.asyncio async def test_ticket_operations(async_rt_connection: rt.rest2.AsyncRt): ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) # empty search result search_result = [item async for item in async_rt_connection.search(Subject=ticket_subject)] assert not len(search_result) # create ticket_id = await async_rt_connection.create_ticket(subject=ticket_subject, content=ticket_text, queue=RT_QUEUE) assert ticket_id > -1 # search search_result = [item async for item in async_rt_connection.search(Subject=ticket_subject)] assert len(search_result) == 1 assert search_result[0]['id'] == str(ticket_id) assert search_result[0]['Status'] == 'new' # search with query_format field list search_result = [item async for item in async_rt_connection.search(Subject=ticket_subject, query_format=['Status','Subject'])] assert len(search_result) == 1 assert search_result[0]['Subject'] == str(ticket_subject) assert search_result[0]['Status'] == 'new' assert 'Requestor' not in search_result[0].keys() # raw search search_result = [item async for item in async_rt_connection.search(raw_query=f'Subject="{ticket_subject}"')] assert len(search_result) == 1 assert search_result[0]['id'] == str(ticket_id) assert search_result[0]['Status'] == 'new' # get ticket ticket = await async_rt_connection.get_ticket(ticket_id) search_result[0]['id'] = int(search_result[0]['id']) for k in search_result[0]: if k.startswith('_') or k in ('type', 'CustomFields'): continue assert k in ticket assert ticket[k] == search_result[0][k] # edit ticket requestors = ['tester1@example.com', 'tester2@example.com'] await async_rt_connection.edit_ticket(ticket_id, Status='open', Requestor=requestors) # get ticket (edited) ticket = await async_rt_connection.get_ticket(ticket_id) assert ticket['Status'] == 'open' for requestor in ticket['Requestor']: assert requestor['id'] in requestors for requestor in requestors: found = False for _requestor in ticket['Requestor']: if _requestor['id'] == requestor: found = True break assert found # get history hist = [item async for item in async_rt_connection.get_ticket_history(ticket_id)] assert len(hist) > 0 transaction = await async_rt_connection.get_transaction(hist[0]['id']) found = False for hyperlink in transaction['_hyperlinks']: if hyperlink['ref'] == 'attachment': attachment_id = hyperlink['_url'].rsplit('/', 1)[1] attachment = base64.b64decode((await async_rt_connection.get_attachment(attachment_id))['Content']).decode('utf-8') found = True assert attachment == ticket_text break assert found # get_short_history short_hist = [item async for item in async_rt_connection.get_ticket_history(ticket_id)] assert len(short_hist) > 0 assert short_hist[0]['Type'] == 'Create' assert short_hist[0]['Creator']['Name'] == RT_USER # create 2nd ticket ticket2_subject = 'Testing issue ' + ''.join([random.choice(string.ascii_letters) for i in range(15)]) ticket2_id = await async_rt_connection.create_ticket(queue=RT_QUEUE, subject=ticket2_subject) assert ticket2_id > -1 # edit link assert await async_rt_connection.edit_link(ticket_id, 'DependsOn', ticket2_id) # get links links1 = await async_rt_connection.get_links(ticket_id) found = False for link in links1: if link['ref'] == 'depends-on' and link['id'] == str(ticket2_id): found = True assert found links2 = await async_rt_connection.get_links(ticket2_id) found = False for link in links2: if link['ref'] == 'depended-on-by' and link['id'] == str(ticket_id): found = True assert found # 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.' attachment = rt.rest2.Attachment(attachment_name, 'text/plain', attachment_content) assert await async_rt_connection.reply(ticket_id, content=reply_text, attachments=[attachment]) # reply with a comment reply_text = 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' assert await async_rt_connection.comment(ticket_id, content=reply_text) # reply with a html content reply_text = 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' assert await async_rt_connection.reply(ticket_id, content=reply_text, content_type='text/html') # attachments list at_list = [item async for item in async_rt_connection.get_attachments(ticket_id)] assert at_list at_names = [at['Filename'] for at in at_list] assert attachment_name in at_names # get the attachment and compare it's content at_id = at_list[at_names.index(attachment_name)]['id'] at_content = base64.b64decode((await async_rt_connection.get_attachment(at_id))['Content']) assert at_content == attachment_content # set invalid user with pytest.raises(rt.exceptions.NotFoundError): await async_rt_connection.edit_ticket(ticket_id, Owner='invalid_user') # set invalid queue with pytest.raises(rt.exceptions.NotFoundError): await async_rt_connection.edit_ticket(ticket_id, Queue='invalid_queue') # edit invalid ticket with pytest.raises(rt.exceptions.NotFoundError): await async_rt_connection.edit_ticket(999999999, Owner='Nobody') # merge tickets assert await async_rt_connection.merge_ticket(ticket2_id, ticket_id) # delete ticket assert await async_rt_connection.delete_ticket(ticket_id) is None # delete invalid ticket with pytest.raises(rt.exceptions.NotFoundError): assert await async_rt_connection.delete_ticket(999999999) @pytest.mark.asyncio async def test_attachments_create(async_rt_connection: rt.rest2.AsyncRt): """Create a ticket with a random (>= 2) number of attachments and verify that they have been successfully added to the ticket.""" ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) attachment_count = random.randint(2, 10) attachments = [] for _i in range(attachment_count): attachment_content = random_string(length=100).encode() attachment_name = f'attachment-{random_string(length=10)}.txt' attachments.append(rt.rest2.Attachment(attachment_name, 'text/plain', attachment_content)) # create ticket_id = await async_rt_connection.create_ticket( subject=ticket_subject, content=ticket_text, queue=RT_QUEUE, attachments=attachments ) assert ticket_id > -1 # get ticket ticket = await async_rt_connection.get_ticket(ticket_id) assert int(ticket['id']) == ticket_id # attachments list at_list = [item async for item in async_rt_connection.get_attachments(ticket_id)] assert at_list assert len(at_list) == len(attachments) at_names = [at['Filename'] for at in at_list] for k in attachments: assert k.file_name in at_names # get the attachment and compare it's content at_id = at_list[at_names.index(k.file_name)]['id'] at_content = base64.b64decode((await async_rt_connection.get_attachment(at_id))['Content']) assert at_content == k.file_content @pytest.mark.asyncio async def test_attachments_comment(async_rt_connection: rt.rest2.AsyncRt): """Create a ticket and comment to it with a random (>= 2) number of attachments and verify that they have been successfully added to the ticket.""" ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) # create ticket_id = await async_rt_connection.create_ticket(subject=ticket_subject, content=ticket_text, queue=RT_QUEUE) assert ticket_id > -1 attachment_count = random.randint(2, 10) attachments = [] for _i in range(attachment_count): attachment_content = random_string(length=100).encode() attachment_name = f'attachment-{random_string(length=10)}.txt' attachments.append(rt.rest2.Attachment(attachment_name, 'text/plain', attachment_content)) # comment with attachments ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) comment_success = await async_rt_connection.comment(ticket_id=ticket_id, content=ticket_text, attachments=attachments) assert comment_success # attachments list at_list = [item async for item in async_rt_connection.get_attachments(ticket_id)] assert at_list assert len(at_list) == len(attachments) at_names = [at['Filename'] for at in at_list] for k in attachments: assert k.file_name in at_names # get the attachment and compare it's content at_id = at_list[at_names.index(k.file_name)]['id'] at_content = base64.b64decode((await async_rt_connection.get_attachment(at_id))['Content']) assert at_content == k.file_content @pytest.mark.asyncio async def test_attachments_reply(async_rt_connection: rt.rest2.AsyncRt): """Create a ticket and reply to it with a random (>= 2) number of attachments and verify that they have been successfully added to the ticket.""" ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) # create ticket_id = await async_rt_connection.create_ticket(subject=ticket_subject, content=ticket_text, queue=RT_QUEUE) assert ticket_id > -1 attachment_count = random.randint(2, 10) attachments = [] for _i in range(attachment_count): attachment_content = random_string(length=100).encode() attachment_name = f'attachment-{random_string(length=10)}.txt' attachments.append(rt.rest2.Attachment(attachment_name, 'text/plain', attachment_content)) # comment with attachments ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) comment_success = await async_rt_connection.reply(ticket_id=ticket_id, content=ticket_text, attachments=attachments) assert comment_success # attachments list at_list = [item async for item in async_rt_connection.get_attachments(ticket_id)] assert at_list assert len(at_list) == len(attachments) at_names = [at['Filename'] for at in at_list] for k in attachments: assert k.file_name in at_names # get the attachment and compare it's content at_id = at_list[at_names.index(k.file_name)]['id'] at_content = base64.b64decode((await async_rt_connection.get_attachment(at_id))['Content']) assert at_content == k.file_content @pytest.mark.asyncio async def test_ticket_operations_admincc_cc(async_rt_connection: rt.rest2.AsyncRt): ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) def compare_list(from_list: typing.List[str], ticket_list: typing.List[dict]) -> bool: """Lists (Requestor, AdminCc, Cc) returned from REST2 contain a list of dicts with additional user information. Thus a simple compare of both lists is not enough. """ if len(from_list) != len(ticket_list): return False to_list = [entry['id'] for entry in ticket_list] diff = set(from_list) ^ set(to_list) return not diff ticket_id = await async_rt_connection.create_ticket(subject=ticket_subject, content=ticket_text, queue=RT_QUEUE) assert ticket_id > -1 # make sure Requestor, AdminCc and Cc are present and an empty list, as would be expected ticket = await async_rt_connection.get_ticket(ticket_id) assert len(ticket['Requestor']) >= 0 assert len(ticket['AdminCc']) >= 0 assert len(ticket['Cc']) >= 0 # set requestors requestors = ['tester1@example.com', 'tester2@example.com'] await async_rt_connection.edit_ticket(ticket_id, Status='open', Requestor=requestors) # verify ticket = await async_rt_connection.get_ticket(ticket_id) assert compare_list(requestors, ticket['Requestor']) # set admincc admincc = ['tester2@example.com', 'tester3@example.com'] await async_rt_connection.edit_ticket(ticket_id, Status='open', AdminCc=admincc) # verify ticket = await async_rt_connection.get_ticket(ticket_id) assert compare_list(requestors, ticket['Requestor']) assert compare_list(admincc, ticket['AdminCc']) # update admincc admincc = ['tester2@example.com', 'tester3@example.com', 'tester4@example.com'] await async_rt_connection.edit_ticket(ticket_id, Status='open', AdminCc=admincc) # verify ticket = await async_rt_connection.get_ticket(ticket_id) assert compare_list(requestors, ticket['Requestor']) assert compare_list(admincc, ticket['AdminCc']) # unset requestors and admincc requestors = [] admincc = [] await async_rt_connection.edit_ticket(ticket_id, Status='open', Requestor=requestors, AdminCc=admincc) # verify ticket = await async_rt_connection.get_ticket(ticket_id) assert compare_list(requestors, ticket['Requestor']) assert compare_list(admincc, ticket['AdminCc']) @pytest.mark.asyncio async def test_users(async_rt_connection: rt.rest2.AsyncRt): assert await async_rt_connection.get_user('tester1@example.com') is not None assert await async_rt_connection.user_exists('root', privileged=True) is True assert await async_rt_connection.user_exists('tester1@example.com', privileged=False) is True assert await async_rt_connection.user_exists('tester1@example.com', privileged=True) is False assert await async_rt_connection.user_exists('does-not-exist@example.com') is False random_user_name = f'username_{random_string()}' random_user_email = f'user-{random_string()}@example.com' random_user_password = f'user_password-{random_string()}' assert await async_rt_connection.create_user(random_user_name, random_user_email, Password=random_user_password) == random_user_name await async_rt_connection.delete_user(random_user_name) with pytest.raises(rt.exceptions.NotFoundError): await async_rt_connection.delete_user(f'username_{random_string()}') assert await async_rt_connection.edit_user(user_id=random_user_name, RealName=random_user_name) @pytest.mark.asyncio async def test_queues(async_rt_connection: rt.rest2.AsyncRt): queue = await async_rt_connection.get_queue(RT_QUEUE) assert queue['Name'] == RT_QUEUE queues = [item async for item in async_rt_connection.get_all_queues()] assert len(queues) >= 1 found = False for q in queues: if q['Name'] == RT_QUEUE: found = True assert found random_queue_name = f'Queue {random_string()}' random_queue_email = f'q-{random_string()}@example.com' await async_rt_connection.create_queue(random_queue_name, CorrespondAddress=random_queue_email, Description='test queue') queues = [item async for item in async_rt_connection.get_all_queues()] found = False for q in queues: if q['Name'] == random_queue_name: found = True assert found await async_rt_connection.edit_queue(random_queue_name, Disabled='1') assert (await async_rt_connection.get_queue(random_queue_name))['Disabled'] == '1' await async_rt_connection.edit_queue(random_queue_name, Disabled='0') assert (await async_rt_connection.get_queue(random_queue_name))['Disabled'] == '0' with pytest.raises(rt.exceptions.NotFoundError): await async_rt_connection.get_queue('InvalidName') await async_rt_connection.delete_queue(random_queue_name) with pytest.raises(rt.exceptions.NotFoundError): await async_rt_connection.delete_queue(f'Queue {random_string()}') ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/tests/test_rest1.py0000644000175100001770000003313514666673042015402 0ustar00runnerdocker"""Tests for Rt - Python interface to Request Tracker :term:`API`""" # ruff: noqa: S101, S105, S311 __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 requests.utils import rt.rest1 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) @staticmethod def _fix_unsecure_cookie(tracker: rt.rest1.Rt) -> None: """As of RT 5.0.4, cookies returned by the REST API are marked as secure by default. This breaks tests though as we are connecting via HTTP. This method fixes these cookies for the tests to work. """ cookies = requests.utils.dict_from_cookiejar(tracker.session.cookies) tracker.session.cookies.clear() tracker.session.cookies.update(cookies) @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.rest1.Rt(self.RT_VALID_CREDENTIALS[name]['url'], **self.RT_VALID_CREDENTIALS[name]['support']) self.assertTrue(tracker.login(), 'Invalid login to RT demo site ' + name) # unsecure cookie self._fix_unsecure_cookie(tracker) self.assertTrue(tracker.logout(), 'Invalid logout from RT demo site ' + name) for name, params in self.RT_INVALID_CREDENTIALS.items(): tracker = rt.rest1.Rt(**params) self.assertFalse(tracker.login(), 'Login to RT demo site ' + name + ' should fail but did not') self.assertRaises(rt.exceptions.AuthorizationError, lambda: tracker.search()) for name, params in self.RT_MISSING_CREDENTIALS.items(): tracker = rt.rest1.Rt(**params) self.assertRaises(rt.exceptions.AuthorizationError, lambda: tracker.login()) for name, params in self.RT_BAD_URL.items(): tracker = rt.rest1.Rt(**params) self.assertRaises(rt.exceptions.UnexpectedResponseError, 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.rest1.Rt(url, default_login=default_login, default_password=default_password) self.assertTrue(tracker.login(), 'Invalid login to RT demo site ' + name) # unsecure cookie self._fix_unsecure_cookie(tracker) # 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.rest1.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=f'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.') # raw search all queues search_result = tracker.search(Queue=rt.rest1.ALL_QUEUES, raw_query=f'Subject="{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']) @unittest.skipUnless(_have_creds(RT_VALID_CREDENTIALS), 'missing credentials required to run test') def test_ticket_operations_admincc_cc(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.rest1.Rt(url, default_login=default_login, default_password=default_password) self.assertTrue(tracker.login(), 'Invalid login to RT demo site ' + name) # unsecure cookie self._fix_unsecure_cookie(tracker) ticket_id = tracker.create_ticket(Subject=ticket_subject, Text=ticket_text) self.assertTrue(ticket_id > -1, 'Creating ticket failed.') # make sure Requestors, AdminCc and Cc are present and an empty list, as would be expected ticket = tracker.get_ticket(ticket_id) self.assertTrue(len(ticket['Requestors']) >= 0) self.assertTrue(len(ticket['AdminCc']) >= 0) self.assertTrue(len(ticket['Cc']) >= 0) # set requestors requestors = ['tester1@example.com', 'tester2@example.com'] tracker.edit_ticket(ticket_id, Status='open', Requestors=requestors) # verify ticket = tracker.get_ticket(ticket_id) self.assertListEqual(requestors, ticket['Requestors']) # set admincc admincc = ['tester2@example.com', 'tester3@example.com'] tracker.edit_ticket(ticket_id, Status='open', AdminCc=admincc) # verify ticket = tracker.get_ticket(ticket_id) self.assertListEqual(requestors, ticket['Requestors']) self.assertListEqual(admincc, ticket['AdminCc']) # update admincc admincc = ['tester2@example.com', 'tester3@example.com', 'tester4@example.com'] tracker.edit_ticket(ticket_id, Status='open', AdminCc=admincc) # verify ticket = tracker.get_ticket(ticket_id) self.assertListEqual(requestors, ticket['Requestors']) self.assertListEqual(admincc, ticket['AdminCc']) # unset requestors and admincc requestors = [] admincc = [] tracker.edit_ticket(ticket_id, Status='open', Requestors=requestors, AdminCc=admincc) # verify ticket = tracker.get_ticket(ticket_id) self.assertListEqual(requestors, ticket['Requestors']) self.assertListEqual(admincc, ticket['AdminCc']) if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/tests/test_tickets.py0000644000175100001770000000540314666673042016007 0ustar00runnerdocker"""Tests for python-rt / REST2 - Python interface to Request Tracker :term:`API`.""" # ruff: noqa: S101, S105, S311 __license__ = """ Copyright (C) 2013 CZ.NIC, z.s.p.o. Copyright (c) 2021 CERT Gouvernemental (GOVCERT.LU) 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" ', '"Georges Toth" ', ] import base64 import rt.rest2 from . import random_string from .conftest import RT_QUEUE def test_ticket_attachments(rt_connection: rt.rest2.Rt): """Test various ticket attachment operations.""" ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) attachment_content = b'Content of attachment.' attachment_name = 'attachment-name.txt' attachment = rt.rest2.Attachment(attachment_name, 'text/plain', attachment_content) ticket_id = rt_connection.create_ticket(subject=ticket_subject, content=ticket_text, queue=RT_QUEUE, attachments=[attachment]) assert ticket_id att_ids = rt_connection.get_attachments_ids(ticket_id) assert len(att_ids) == 1 att_list = rt_connection.get_attachments(ticket_id) assert len(att_list) == 1 att_names = [att['Filename'] for att in att_list] assert attachment_name in att_names # get the attachment and compare it's content att_id = att_list[att_names.index(attachment_name)]['id'] att_content = base64.b64decode(rt_connection.get_attachment(att_id)['Content']) assert att_content == attachment_content def test_ticket_take(rt_connection: rt.rest2.Rt): """Test take/untake.""" ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) ticket_id = rt_connection.create_ticket(subject=ticket_subject, content=ticket_text, queue=RT_QUEUE) assert ticket_id assert rt_connection.take(ticket_id) assert rt_connection.untake(ticket_id) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1725658658.0 rt-3.2.0/tests/test_tickets_async.py0000644000175100001770000000573414666673042017213 0ustar00runnerdocker"""Tests for python-rt / REST2 - Python interface to Request Tracker :term:`API`.""" # ruff: noqa: S101 __license__ = """ Copyright (C) 2013 CZ.NIC, z.s.p.o. Copyright (c) 2021 CERT Gouvernemental (GOVCERT.LU) 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" ', '"Georges Toth" ', ] import base64 import pytest import rt.rest2 from . import random_string from .conftest import RT_QUEUE @pytest.mark.asyncio async def test_ticket_attachments(async_rt_connection: rt.rest2.AsyncRt): """Test various ticket attachment operations.""" ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) attachment_content = b'Content of attachment.' attachment_name = 'attachment-name.txt' attachment = rt.rest2.Attachment(attachment_name, 'text/plain', attachment_content) ticket_id = await async_rt_connection.create_ticket( subject=ticket_subject, content=ticket_text, queue=RT_QUEUE, attachments=[attachment] ) assert ticket_id att_ids = [item async for item in async_rt_connection.get_attachments_ids(ticket_id)] assert len(att_ids) == 1 att_list = [item async for item in async_rt_connection.get_attachments(ticket_id)] assert len(att_list) == 1 att_names = [att['Filename'] for att in att_list] assert attachment_name in att_names # get the attachment and compare it's content att_id = att_list[att_names.index(attachment_name)]['id'] att_content = base64.b64decode((await async_rt_connection.get_attachment(att_id))['Content']) assert att_content == attachment_content @pytest.mark.asyncio async def test_ticket_take(async_rt_connection: rt.rest2.AsyncRt): """Test take/untake.""" ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) ticket_id = await async_rt_connection.create_ticket(subject=ticket_subject, content=ticket_text, queue=RT_QUEUE) assert ticket_id assert await async_rt_connection.take(ticket_id) assert await async_rt_connection.untake(ticket_id)