Repository: sirk123au/ArrTools Branch: master Commit: 80d50f2c46ca Files: 20 Total size: 125.7 KB Directory structure: gitextract_3p_wpwp1/ ├── .github/ │ └── FUNDING.yml ├── .gitignore ├── LICENSE ├── README.md ├── RadarrSync.py ├── arr_gui.py ├── backup_lidarr_2csv.py ├── backup_radarr_2csv.py ├── backup_readarr_2csv.py ├── backup_sonarr_2csv.py ├── config_example.ini ├── export_trakt.py ├── get_imdbid.py ├── lidarr_add_from_list.py ├── radarr_add_from_list.py ├── radarr_remove_downloaded.py ├── radarr_unmonitor_downloaded.py ├── remove_from_sonarr.py ├── requirements.txt └── sonarr_add_from_list.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ # These are supported funding model platforms github: sirk123au patreon: # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: # Replace with a single Ko-fi username tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] ================================================ FILE: .gitignore ================================================ syntax: glob config.ini *.log .vscode trakt_search.py *.csv *config.ini *.pyc *.csv import_from_tmdb.py yt_music_vid_get.py cookies.txt ================================================ FILE: LICENSE ================================================ 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 . ================================================ FILE: README.md ================================================ ## Radarr and Sonarr Tools *radarr_add_from_list.py* Add Movies from a csv formatted file. *sonarr_add_from_list.py* Add Shows from a csv formatted file. *lidarr_add_from_list.py* Add Artists from a csv formatted file. *radarr_remove_downloaded.py* Removes already downloaded movies and removes their entries from Radarr. *backup_radarr_2csv.py* Creates a backup of the Radarr Database for easy importing. *backup_sonarr_2csv.py* Creates a backup of the Sonarr Database for easy importing. *backup_lidarr_2csv.py* Creates a backup of the Lidarr Database for easy importing. *get_imdbid.py* Matches the imdbd from a csv list MovieName/ShowName,Year for easy importing for the list import. *arr_gui.py* Standalone GUI to import or export data for Radarr, Sonarr or Lidarr. Using radarr_add_from_list/sonarr_add_from_list The input list file has to have the format. It has to have MovieName/ShowName,Year,imdbid **imdbid is Optional Makes it easer to find movie/TV show Use pip install -r requirements.txt to install the required python modules Movies CSV ``` title,year,imdbid (This header has to be included in the csv for it to work correctly) Ben-Hur,1959,tt0052618 Gone with the Wind,1939,tt0031381 Without imdbid title,year,imdbid (This header has to be included in the csv for it to work correctly) The English Patient,1996 Schindler's List,1993 ``` TV Shows CSV ``` title,year,imdbid (This header has to be included in the csv for it to work correctly) 13 Reasons Why,2017,tt1837492 50 Central,2017,tt7261310 Without imdbID title,year,imdbid (This header has to be included in the csv for it to work correctly) 60 Days In,2016 9-1-1,2018 A Discovery of Witches,2018 ``` Artist CSV ``` artist,foreignArtistId 10cc 2 DJ's and One 3 Doors Down 3-11 Porter With foreignArtistId artist,foreignArtistId Weird Al Yankovic,7746d775-9550-4360-b8d5-c37bd448ce01 Adele,cc2c9c3c-b7bc-4b8b-84d8-4fbd8779e493 Alanis Morissette,4bdcee62-4902-4773-8cd1-e252e2e31225 Arctic Monkeys,ada7a83c-e3e1-40f1-93f9-3e73dbc9298a Augie March,29070ba5-c3df-41d9-bed0-8e2f1e1c22ad BABYMETAL,27e2997f-f7a1-4353-bcc4-57b9274fa9a4 Backstreet Boys,2f569e60-0a1b-4fb9-95a4-3dc1525d1aad ``` If `foreignArtistId` is omitted, `lidarr_add_from_list.py` will attempt to retrieve the MusicBrainz ID automatically. Run the GUI with ``` $ python3 arr_gui.py ``` The CLI scripts remain for advanced usage, but the GUI handles common import and export operations without calling them. Rename config_example.ini and add your details ``` [radarr] api_key = Radarr Api Key baseurl = http://localhost:7878 Radarr Base Url urlbase = ; Include URL Base if you have it enabled rootfolderpath = Movie Root Path (trailing slash is needed eg. /media/Movies/ or d:\media\Movies\) searchForMovie = Enable forced search qualityProfileId = omdbapi_key = sign up here for free api key http://www.omdbapi.com/apikey.aspx [sonarr] api_key = Sonarr Api Key baseurl = http://localhost:8989 urlbase = ; Include URL Base if you have it enabled rootfolderpath = Show Root Path (trailing slash is needed eg. /media/shows/ or d:\media\shows\) searchForShow = qualityProfileId = omdbapi_key = tvdb_api = ; sign up here for a api key https://thetvdb.com/api-information tvdb_userkey = tvdb_username = [lidarr] api_key = baseurl = http://localhost:8686 rootfolderpath = [gui] # Optional default CSV path used by arr_gui.py default_csv = Standard Profile ID 1 Any 2 SD 3 HD-720p 4 HD-1080p 5 Ultra-HD 6 HD - 720p/1080p ``` Thanks for the support :) [![Github Sponsorship](https://img.shields.io/badge/support-me-red.svg)](https://github.com/users/sirk123au/sponsorship) [![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/M4M25DUMM) ================================================ FILE: RadarrSync.py ================================================ import os import logging import requests import json import configparser import sys DEV = False VER = '1.0.1' ######################################################################################################################## logger = logging.getLogger() logger.setLevel(logging.DEBUG) logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s") fileHandler = logging.FileHandler("./Output.txt") fileHandler.setFormatter(logFormatter) logger.addHandler(fileHandler) consoleHandler = logging.StreamHandler(sys.stdout) consoleHandler.setFormatter(logFormatter) logger.addHandler(consoleHandler) ######################################################################################################################## def ConfigSectionMap(section): dict1 = {} options = Config.options(section) for option in options: try: dict1[option] = Config.get(section, option) if dict1[option] == -1: logger.debug("skip: %s" % option) except: print("exception on %s!" % option) dict1[option] = None return dict1 logger.debug('RadarSync Version {}'.format(VER)) Config = configparser.ConfigParser() # Loads an alternate config file so that I can work on my servers without uploading config to github if DEV: settingsFilename = os.path.join(os.getcwd(), 'Dev' 'Config.txt') else: settingsFilename = os.path.join(os.getcwd(), 'Config.txt') Config.read(settingsFilename) radarr_url = ConfigSectionMap("Radarr")['url'] radarr_key = ConfigSectionMap("Radarr")['key'] radarrSession = requests.Session() radarrSession.trust_env = False radarrMovies = radarrSession.get('{0}/api/movie?apikey={1}'.format(radarr_url, radarr_key)) if radarrMovies.status_code != 200: logger.error('Radarr server error - response {}'.format(radarrMovies.status_code)) sys.exit(0) for server in Config.sections(): if server == 'Default' or server == "Radarr": continue # Default section handled previously as it always needed else: logger.debug('syncing to {0}'.format(server)) session = requests.Session() session.trust_env = False SyncServer_url = ConfigSectionMap(server)['url'] SyncServer_key = ConfigSectionMap(server)['key'] SyncServer_target_profile = ConfigSectionMap(server)['target_profile'] SyncServerMovies = session.get('{0}/api/movie?apikey={1}'.format(SyncServer_url, SyncServer_key)) if SyncServerMovies.status_code != 200: logger.error('4K Radarr server error - response {}'.format(SyncServerMovies.status_code)) sys.exit(0) # build a list of movied IDs already in the sync server, this is used later to prevent readding a movie that already # exists. # TODO refactor variable names to make it clear this builds list of existing not list of movies to add # TODO #11 add reconcilliation to remove movies that have been deleted from source server movieIds_to_syncserver = [] for movie_to_sync in SyncServerMovies.json(): movieIds_to_syncserver.append(movie_to_sync['tmdbId']) #logger.debug('found movie to be added') newMovies = 0 searchid = [] for movie in radarrMovies.json(): if movie['profileId'] == int(ConfigSectionMap(server)['profile']): if movie['tmdbId'] not in movieIds_to_syncserver: logging.debug('title: {0}'.format(movie['title'])) logging.debug('qualityProfileId: {0}'.format(movie['qualityProfileId'])) logging.debug('titleSlug: {0}'.format(movie['titleSlug'])) images = movie['images'] for image in images: image['url'] = '{0}{1}'.format(radarr_url, image['url']) logging.debug(image['url']) logging.debug('tmdbId: {0}'.format(movie['tmdbId'])) logging.debug('path: {0}'.format(movie['path'])) logging.debug('monitored: {0}'.format(movie['monitored'])) # Update the path based on "path_from" and "path_to" passed to us in Config.txt path = movie['path'] path = path.replace(ConfigSectionMap(server)['path_from'], ConfigSectionMap(server)['path_to']) payload = {'title': movie['title'], 'qualityProfileId': movie['qualityProfileId'], 'titleSlug': movie['titleSlug'], 'tmdbId': movie['tmdbId'], 'path': path, 'monitored': movie['monitored'], 'images': images, 'profileId': SyncServer_target_profile, 'minimumAvailability': 'released' } r = session.post('{0}/api/movie?apikey={1}'.format(SyncServer_url, SyncServer_key), data=json.dumps(payload)) if r.status_code == 200: searchid.append(int(r.json()['id'])) logger.info('adding {0} to {1} server'.format(movie['title'], server)) else: logger.debug('Failed with error: {0}'.format(r.json())) else: logging.debug('{0} already in {1} library'.format(movie['title'], server)) else: logging.debug('Skipping {0}, wanted profile: {1} found profile: {2}'.format(movie['title'], movie['profileId'], int(ConfigSectionMap(server)['profile']) )) if len(searchid): payload = {'name' : 'MoviesSearch', 'movieIds' : searchid} session.post('{0}/api/command?apikey={1}'.format(SyncServer_url, SyncServer_key), data=json.dumps(payload)) ================================================ FILE: arr_gui.py ================================================ import csv import configparser import urllib.parse import requests import tkinter as tk from tkinter import filedialog, messagebox CONFIG_PATH = "./config.ini" def load_config(): config = configparser.ConfigParser() config.read(CONFIG_PATH) return config def load_defaults(): config = load_config() csv_path = "" if config.has_section("gui"): csv_path = config.get("gui", "default_csv", fallback="") return csv_path def browse_file(entry): path = filedialog.askopenfilename(filetypes=[("CSV files", "*.csv"), ("All files", "*.*")]) if path: entry.delete(0, tk.END) entry.insert(0, path) # ----------------------- Radarr helpers --------------------------------- def radarr_import(csv_path: str, cfg: configparser.ConfigParser) -> None: baseurl = cfg["radarr"]["baseurl"] urlbase = cfg["radarr"].get("urlbase", "") api_key = cfg["radarr"]["api_key"] root = cfg["radarr"]["rootfolderpath"] profile = cfg["radarr"]["qualityProfileId"] search = cfg.getboolean("radarr", "searchForMovie", fallback=False) headers = {"Content-type": "application/json", "X-Api-Key": api_key} session = requests.Session() with open(csv_path, encoding="utf-8") as f: reader = csv.DictReader(f) for row in reader: title = row.get("title") year = row.get("year") imdbid = row.get("imdbid") if imdbid: url = f"{baseurl}{urlbase}/api/v3/movie/lookup/imdb?imdbId={imdbid}" else: term = urllib.parse.quote_plus(f"{title} {year}" if year else title) url = f"{baseurl}{urlbase}/api/v3/movie/lookup?term={term}" rsp = session.get(url, headers=headers) if rsp.status_code != 200 or rsp.text in ("", "[]"): messagebox.showwarning("Radarr", f"{title} not found") continue data = rsp.json() if isinstance(data, list): data = data[0] payload = { "title": data.get("title"), "tmdbId": data.get("tmdbId"), "year": data.get("year"), "titleSlug": data.get("titleSlug"), "qualityProfileId": int(profile), "rootFolderPath": root, "monitored": True, "images": data.get("images", []), "addOptions": {"searchForMovie": search}, } add_url = f"{baseurl}{urlbase}/api/v3/movie" session.post(add_url, headers=headers, json=payload) def radarr_export(cfg: configparser.ConfigParser) -> None: baseurl = cfg["radarr"]["baseurl"] urlbase = cfg["radarr"].get("urlbase", "") api_key = cfg["radarr"]["api_key"] headers = {"Content-type": "application/json", "X-Api-Key": api_key} url = f"{baseurl}{urlbase}/api/v3/movie" rsp = requests.get(url, headers=headers) rsp.raise_for_status() data = rsp.json() with open("radarr_backup.csv", "w", newline="", encoding="utf-8") as f: writer = csv.writer(f) writer.writerow(["title", "year", "imdbid", "tmdbId"]) for d in data: writer.writerow([d.get("title"), d.get("year"), d.get("imdbId"), d.get("tmdbId")]) # ----------------------- Sonarr helpers --------------------------------- def sonarr_import(csv_path: str, cfg: configparser.ConfigParser) -> None: baseurl = cfg["sonarr"]["baseurl"] urlbase = cfg["sonarr"].get("urlbase", "") api_key = cfg["sonarr"]["api_key"] root = cfg["sonarr"]["rootfolderpath"] profile = cfg["sonarr"]["qualityProfileId"] search = cfg.getboolean("sonarr", "searchForShow", fallback=False) headers = {"Content-type": "application/json", "X-Api-Key": api_key} session = requests.Session() with open(csv_path, encoding="utf-8") as f: reader = csv.DictReader(f) for row in reader: title = row.get("title") year = row.get("year") imdbid = row.get("imdbid") if imdbid: url = f"{baseurl}{urlbase}/api/v3/series/lookup?term=imdb:{imdbid}" else: term = urllib.parse.quote_plus(f"{title} {year}" if year else title) url = f"{baseurl}{urlbase}/api/v3/series/lookup?term={term}" rsp = session.get(url, headers=headers) if rsp.status_code != 200 or rsp.text in ("", "[]"): messagebox.showwarning("Sonarr", f"{title} not found") continue data = rsp.json() if isinstance(data, list): data = data[0] payload = { "title": data.get("title"), "tvdbId": data.get("tvdbId"), "year": data.get("year"), "titleSlug": data.get("titleSlug"), "qualityProfileId": int(profile), "rootFolderPath": root, "monitored": True, "seasonFolder": True, "images": data.get("images", []), "seasons": data.get("seasons", []), "addOptions": {"searchForMissingEpisodes": search}, } add_url = f"{baseurl}{urlbase}/api/v3/series" session.post(add_url, headers=headers, json=payload) def sonarr_export(cfg: configparser.ConfigParser) -> None: baseurl = cfg["sonarr"]["baseurl"] urlbase = cfg["sonarr"].get("urlbase", "") api_key = cfg["sonarr"]["api_key"] headers = {"Content-type": "application/json", "X-Api-Key": api_key} url = f"{baseurl}{urlbase}/api/v3/series" rsp = requests.get(url, headers=headers) rsp.raise_for_status() data = rsp.json() with open("sonarr_backup.csv", "w", newline="", encoding="utf-8") as f: writer = csv.writer(f) writer.writerow(["title", "year", "imdbid"]) for d in data: writer.writerow([d.get("title"), d.get("year"), d.get("imdbId")]) # ----------------------- Lidarr helpers --------------------------------- def lidarr_import(csv_path: str, cfg: configparser.ConfigParser) -> None: baseurl = cfg["lidarr"]["baseurl"] api_key = cfg["lidarr"]["api_key"] root = cfg["lidarr"]["rootfolderpath"] headers = {"Content-type": "application/json", "X-Api-Key": api_key} session = requests.Session() def lookup_artist(name: str) -> str | None: url = f"https://api.lidarr.audio/api/v0.4/search?type=artist&query=\"{urllib.parse.quote_plus(name)}\"" resp = session.get(url, headers=headers) if resp.status_code == 200 and resp.text not in ("", "[]"): data = resp.json() if isinstance(data, list): return data[0].get("id") return data.get("id") return None with open(csv_path, encoding="utf-8") as f: reader = csv.DictReader(f) for row in reader: artist = row.get("artist") mbid = row.get("foreignArtistId") if not mbid: mbid = lookup_artist(artist) if not mbid: messagebox.showwarning("Lidarr", f"{artist} not found") continue payload = { "artistName": artist, "foreignArtistId": mbid, "QualityProfileId": 1, "MetadataProfileId": 1, "Path": os.path.join(root, artist), "RootFolderPath": root, "monitored": True, "addOptions": {"searchForMissingAlbums": False}, } add_url = f"{baseurl}/api/v1/artist" session.post(add_url, headers=headers, json=payload) def lidarr_export(cfg: configparser.ConfigParser) -> None: baseurl = cfg["lidarr"]["baseurl"] api_key = cfg["lidarr"]["api_key"] headers = {"Content-type": "application/json", "X-Api-Key": api_key} url = f"{baseurl}/api/v1/artist" rsp = requests.get(url, headers=headers) rsp.raise_for_status() data = rsp.json() with open("lidarr_backup.csv", "w", newline="", encoding="utf-8") as f: writer = csv.writer(f) writer.writerow(["artist", "foreignArtistId"]) for d in data: writer.writerow([d.get("artistName"), d.get("foreignArtistId")]) # ----------------------- GUI logic --------------------------------- def run_action(service_var, action_var, csv_entry): service = service_var.get() action = action_var.get() csv_path = csv_entry.get() cfg = load_config() if action == "Import" and not csv_path: messagebox.showerror("Error", "Please select a CSV file for import") return try: if service == "Radarr" and action == "Import": radarr_import(csv_path, cfg) elif service == "Radarr" and action == "Export": radarr_export(cfg) elif service == "Sonarr" and action == "Import": sonarr_import(csv_path, cfg) elif service == "Sonarr" and action == "Export": sonarr_export(cfg) elif service == "Lidarr" and action == "Import": lidarr_import(csv_path, cfg) elif service == "Lidarr" and action == "Export": lidarr_export(cfg) else: messagebox.showerror("Error", "Invalid selection") return messagebox.showinfo("Success", "Operation completed") except Exception as exc: # simplistic error handling messagebox.showerror("Error", str(exc)) def main(): root = tk.Tk() root.title("ArrTools GUI") csv_default = load_defaults() tk.Label(root, text="Service:").grid(row=0, column=0, padx=5, pady=5, sticky="e") service_var = tk.StringVar(value="Radarr") tk.OptionMenu(root, service_var, "Radarr", "Sonarr", "Lidarr").grid(row=0, column=1, padx=5, pady=5) tk.Label(root, text="Action:").grid(row=1, column=0, padx=5, pady=5, sticky="e") action_var = tk.StringVar(value="Import") tk.OptionMenu(root, action_var, "Import", "Export").grid(row=1, column=1, padx=5, pady=5) tk.Label(root, text="CSV File:").grid(row=2, column=0, padx=5, pady=5, sticky="e") csv_entry = tk.Entry(root, width=40) csv_entry.grid(row=2, column=1, padx=5, pady=5) csv_entry.insert(0, csv_default) tk.Button(root, text="Browse", command=lambda: browse_file(csv_entry)).grid(row=2, column=2, padx=5, pady=5) tk.Button( root, text="Run", command=lambda: run_action(service_var, action_var, csv_entry), ).grid(row=3, column=0, columnspan=3, pady=10) root.mainloop() if __name__ == "__main__": main() ================================================ FILE: backup_lidarr_2csv.py ================================================ """Export Lidarr artist information to a CSV file.""" import argparse import csv import json import sys import re import configparser from pathlib import Path import requests if sys.version_info[0] < 3: raise Exception("Must be using Python 3") def backup_lidarr(config_path: str, output_path: str) -> None: """Backup Lidarr artists to ``output_path`` using ``config_path``.""" config = configparser.ConfigParser() config.read(config_path) baseurl = config['lidarr']['baseurl'] api_key = config['lidarr']['api_key'] headers = {"Content-type": "application/json", "X-Api-Key": api_key} url = f"{baseurl}/api/v1/artist" print("Downloading Data...") response = requests.get(url, headers=headers) response.raise_for_status() lidarr_data = response.json() with open(output_path, "w", newline="", encoding="utf-8") as csvfile: csvwriter = csv.writer(csvfile) csvwriter.writerow(["artist", "foreignArtistId"]) for artist_info in lidarr_data: artist = re.sub(r"[^a-zA-Z0-9 ]", "", artist_info["artistName"]) csvwriter.writerow([artist, artist_info.get("foreignArtistId")]) def main() -> None: parser = argparse.ArgumentParser(description="Backup Lidarr artists to CSV") parser.add_argument( "-c", "--config", default="./config.ini", help="Path to config.ini", ) parser.add_argument( "-o", "--output", default="./lidarr_backup.csv", help="Output CSV file", ) args = parser.parse_args() try: backup_lidarr(args.config, args.output) print("Done...") except Exception as exc: # keep CLI simple print(f"Error: {exc}") if __name__ == "__main__": main() ================================================ FILE: backup_radarr_2csv.py ================================================ import requests, json, csv, sys, configparser if sys.version_info[0] < 3: raise Exception("Must be using Python 3") config = configparser.ConfigParser() config.read('./config.ini') baseurl = config['radarr']['baseurl'] api_key = config['radarr']['api_key'] urlbase = config['radarr']['urlbase'] with open('./radarr_backup.csv', 'w', encoding="utf-8", newline='' ) as csvfile: csvwriter = csv.writer(csvfile, delimiter=',') print("Downloading Data...") headers = {"Content-type": "application/json", "X-Api-Key": api_key } url = f"{baseurl}{urlbase}/api/v3/movie" rsp = requests.get(url , headers=headers) csvwriter.writerow(['title','year','imdbid', 'tmdbId']) if rsp.status_code == 200: RadarrData = json.loads(rsp.text) for d in RadarrData: csvwriter.writerow([d.get('title'),d.get('year'), d.get('imdbId'),d.get('tmdbId')]) else: print("Failed to connect to Radar...") print("Done...") ================================================ FILE: backup_readarr_2csv.py ================================================ import requests, json, csv, sys, configparser if sys.version_info[0] < 3: raise Exception("Must be using Python 3") config = configparser.ConfigParser() config.read('./config.ini') baseurl = config['readarr']['baseurl'] api_key = config['readarr']['api_key'] with open('./readarr_backup.csv', 'w', newline='') as csvfile: csvwriter = csv.writer(csvfile, delimiter=',') print("Downloading Data...") headers = {"Content-type": "application/json", "X-Api-Key": api_key } url = "{}/api/v1/book".format(baseurl) rsp = requests.get(url , headers=headers) csvwriter.writerow(['AuthorID','AuthorName','BookID','BookName']) if rsp.status_code == 200: readarrData = json.loads(rsp.text) for d in readarrData: csvwriter.writerow([d['author']['foreignAuthorId'], d['author']['authorName'], d['foreignBookId'], d['title']]) else: print("Failed to connect to readarr...") print("Done...") ================================================ FILE: backup_sonarr_2csv.py ================================================ import requests, json, csv, sys, configparser if sys.version_info[0] < 3: raise Exception("Must be using Python 3") config = configparser.ConfigParser() config.read('./config.ini') baseurl = config['sonarr']['baseurl'] api_key = config['sonarr']['api_key'] with open('./sonarr_backup.csv', 'w', newline='') as csvfile: csvwriter = csv.writer(csvfile, delimiter=',') print("Downloading Data...") headers = {"Content-type": "application/json", "X-Api-Key": api_key } url = "{}/api/v3/series".format(baseurl) rsp = requests.get(url , headers=headers) csvwriter.writerow(['title','year','imdbid']) if rsp.status_code == 200: RadarrData = json.loads(rsp.text) for d in RadarrData: csvwriter.writerow([d['title'],d['year'], d.get('imdbId')]) else: print("Failed to connect to Radar...") print("Done...") ================================================ FILE: config_example.ini ================================================ [radarr] api_key = baseurl = urlbase = ; Include URL Base if you have it enabled rootfolderpath = searchForMovie = qualityProfileId = omdbapi_key = ; sign up here for api key http://www.omdbapi.com/apikey.aspx [sonarr] api_key = baseurl = urlbase = ; Include URL Base if you have it enabled rootfolderpath = searchForShow = qualityProfileId = omdbapi_key = tvdb_api = ; sign up here for a api key https://thetvdb.com/api-information tvdb_userkey = tvdb_username = [lidarr] api_key = baseurl = rootfolderpath = ; Standard Profile ID ; 1 Any ; 2 SD ; 3 HD-720p ; 4 HD-1080p ; 5 Ultra-HD ; 6 HD - 720p/1080p [gui] # Default CSV file path for the GUI default_csv = ================================================ FILE: export_trakt.py ================================================ #!/usr/bin/python # -*- coding: utf-8 -*- # # (c) Copyright 2016-2018 xbgmsharp # # Purpose: # Export Movies or TVShows IDs from Trakt.tv # # Requirement on Ubuntu/Debian Linux system # apt-get install python-dateutil python-simplejson python-requests python-openssl jq # # Requirement on Windows on Python 2.7 # C:\Python2.7\Scripts\easy_install-2.7.exe simplejson requests # import sys, os # https://urllib3.readthedocs.org/en/latest/security.html#disabling-warnings # http://quabr.com/27981545/surpress-insecurerequestwarning-unverified-https-request-is-being-made-in-pytho # http://docs.python-requests.org/en/v2.4.3/user/advanced/#proxies try: import simplejson as json import requests requests.packages.urllib3.disable_warnings() import csv except: sys.exit("Please use your favorite mehtod to install the following module requests and simplejson to use this script") import argparse import ConfigParser import datetime import collections import pprint pp = pprint.PrettyPrinter(indent=4) desc="""This program export Movies or TVShows IDs from Trakt.tv list.""" epilog="""Read a list from Trakt API. Export them into a CSV file.""" _trakt = { 'client_id' : '', # Auth details for trakt API 'client_secret' : '', # Auth details for trakt API 'oauth_token' : '', # Auth details for trakt API 'baseurl' : 'https://api.trakt.tv' # Sandbox environment https://api-staging.trakt.tv } _headers = { 'Accept' : 'application/json', # required per API 'Content-Type' : 'application/json', # required per API 'User-Agent' : 'Tratk importer', # User-agent 'Connection' : 'Keep-Alive', # Thanks to urllib3, keep-alive is 100% automatic within a session! 'trakt-api-version' : '2', # required per API 'trakt-api-key' : '', # required per API 'Authorization' : '', # required per API } _proxy = { 'proxy' : False, # True or False, trigger proxy use 'host' : 'https://127.0.0.1', # Host/IP of the proxy 'port' : '3128' # Port of the proxy } _proxyDict = { "http" : _proxy['host']+':'+_proxy['port'], "https" : _proxy['host']+':'+_proxy['port'] } response_arr = [] def read_config(options): """ Read config file and if provided overwrite default values If no config file exist, create one with default values """ global work_dir work_dir = '' if getattr(sys, 'frozen', False): work_dir = os.path.dirname(sys.executable) elif __file__: work_dir = os.path.dirname(__file__) _configfile = os.path.join(work_dir, options.config) if os.path.exists(options.config): _configfile = options.config if options.verbose: print "Config file: {0}".format(_configfile) if os.path.exists(_configfile): try: config = ConfigParser.SafeConfigParser() config.read(_configfile) if config.has_option('TRAKT','CLIENT_ID') and len(config.get('TRAKT','CLIENT_ID')) != 0: _trakt['client_id'] = config.get('TRAKT','CLIENT_ID') else: print 'Error, you must specify a trakt.tv CLIENT_ID' sys.exit(1) if config.has_option('TRAKT','CLIENT_SECRET') and len(config.get('TRAKT','CLIENT_SECRET')) != 0: _trakt['client_secret'] = config.get('TRAKT','CLIENT_SECRET') else: print 'Error, you must specify a trakt.tv CLIENT_SECRET' sys.exit(1) if config.has_option('TRAKT','OAUTH_TOKEN') and len(config.get('TRAKT','OAUTH_TOKEN')) != 0: _trakt['oauth_token'] = config.get('TRAKT','OAUTH_TOKEN') else: print 'Warning, authentification is required' if config.has_option('TRAKT','BASEURL'): _trakt['baseurl'] = config.get('TRAKT','BASEURL') if config.has_option('SETTINGS','PROXY'): _proxy['proxy'] = config.getboolean('SETTINGS','PROXY') if _proxy['proxy'] and config.has_option('SETTINGS','PROXY_HOST') and config.has_option('SETTINGS','PROXY_PORT'): _proxy['host'] = config.get('SETTINGS','PROXY_HOST') _proxy['port'] = config.get('SETTINGS','PROXY_PORT') _proxyDict['http'] = _proxy['host']+':'+_proxy['port'] _proxyDict['https'] = _proxy['host']+':'+_proxy['port'] except: print "Error reading configuration file {0}".format(_configfile) sys.exit(1) else: try: print '%s file was not found!' % _configfile config = ConfigParser.RawConfigParser() config.add_section('TRAKT') config.set('TRAKT', 'CLIENT_ID', '') config.set('TRAKT', 'CLIENT_SECRET', '') config.set('TRAKT', 'OAUTH_TOKEN', '') config.set('TRAKT', 'BASEURL', 'https://api.trakt.tv') config.add_section('SETTINGS') config.set('SETTINGS', 'PROXY', False) config.set('SETTINGS', 'PROXY_HOST', 'https://127.0.0.1') config.set('SETTINGS', 'PROXY_PORT', '3128') with open(_configfile, 'wb') as configfile: config.write(configfile) print "Default settings wrote to file {0}".format(_configfile) except: print "Error writing configuration file {0}".format(_configfile) sys.exit(1) def write_csv(options, results): """Write list output into a CSV file format""" if options.verbose: print "CSV output file: {0}".format(options.output) # Write result CSV with open(options.output, 'wb') as fp: keys = {} for i in results: for k in i.keys(): keys[k] = 1 mycsv = csv.DictWriter(fp, fieldnames=keys.keys(), quoting=csv.QUOTE_ALL) mycsv.writeheader() for row in results: mycsv.writerow(row) fp.close() def api_auth(options): """API call for authentification OAUTH""" print("Open the link in a browser and paste the pincode when prompted") print("https://trakt.tv/oauth/authorize?response_type=code&" "client_id={0}&redirect_uri=urn:ietf:wg:oauth:2.0:oob".format( _trakt["client_id"])) pincode = str(raw_input('Input PIN:')) url = _trakt['baseurl'] + '/oauth/token' values = { "code": pincode, "client_id": _trakt["client_id"], "client_secret": _trakt["client_secret"], "redirect_uri": "urn:ietf:wg:oauth:2.0:oob", "grant_type": "authorization_code" } request = requests.post(url, data=values) response = request.json() _headers['Authorization'] = 'Bearer ' + response["access_token"] _headers['trakt-api-key'] = _trakt['client_id'] print 'Save as "oauth_token" in file {0}: {1}'.format(options.config, response["access_token"]) def api_get_list(options, page): """API call for Sync / Get list by type""" url = _trakt['baseurl'] + '/sync/{list}/{type}?page={page}&limit={limit}'.format( list=options.list, type=options.type, page=page, limit=1000) if options.verbose: print(url) if _proxy['proxy']: r = requests.get(url, headers=_headers, proxies=_proxyDict, timeout=(10, 60)) else: r = requests.get(url, headers=_headers, timeout=(5, 60)) #pp.pprint(r.headers) if r.status_code != 200: print "Error fetching Get {list}: {status} [{text}]".format( list=options.list, status=r.status_code, text=r.text) return None else: global response_arr response_arr += json.loads(r.text) if 'X-Pagination-Page-Count'in r.headers and r.headers['X-Pagination-Page-Count']: print "Fetched page {page} of {PageCount} pages for {list} list".format( page=page, PageCount=r.headers['X-Pagination-Page-Count'], list=options.list) if page != int(r.headers['X-Pagination-Page-Count']): api_get_list(options, page+1) return response_arr def api_get_userlists(options, page): """API call for Sync / Get list by type""" url = _trakt['baseurl'] + '/users/{user}/lists'.format( user=options.userlist, page=page, limit=1000) #url = _trakt['baseurl'] + '/users/{user}/lists/{list_id}?page={page}&limit={limit}'.format( # list=options.list, type=options.type, page=page, limit=1000) if options.verbose: print(url) if _proxy['proxy']: r = requests.get(url, headers=_headers, proxies=_proxyDict, timeout=(10, 60)) else: r = requests.get(url, headers=_headers, timeout=(5, 60)) #pp.pprint(r.headers) if r.status_code != 200: print "Error fetching Get {list}: {status} [{text}]".format( list=options.list, status=r.status_code, text=r.text) return None else: global response_arr response_arr += json.loads(r.text) if 'X-Pagination-Page-Count'in r.headers and r.headers['X-Pagination-Page-Count']: print "Fetched page {page} of {PageCount} pages for {list} list".format( page=page, PageCount=r.headers['X-Pagination-Page-Count'], list=options.list) if page != int(r.headers['X-Pagination-Page-Count']): api_get_list(options, page+1) return response_arr def api_get_userlist(options, page): """API call for Sync / Get list by type""" url = _trakt['baseurl'] + '/users/{user}/lists/{list_id}/items/{type}?page={page}&limit={limit}'.format( user=options.userlist, list_id=options.listid, type=options.type, page=page, limit=1000) if options.verbose: print(url) if _proxy['proxy']: r = requests.get(url, headers=_headers, proxies=_proxyDict, timeout=(10, 60)) else: r = requests.get(url, headers=_headers, timeout=(5, 60)) #pp.pprint(r.headers) if r.status_code != 200: print "Error fetching Get {list}: {status} [{text}]".format( list=options.list, status=r.status_code, text=r.text) return None else: global response_arr response_arr += json.loads(r.text) if 'X-Pagination-Page-Count'in r.headers and r.headers['X-Pagination-Page-Count']: print "Fetched page {page} of {PageCount} pages for {list} list".format( page=page, PageCount=r.headers['X-Pagination-Page-Count'], list=options.list) if page != int(r.headers['X-Pagination-Page-Count']): api_get_userlist(options, page+1) return response_arr def api_remove_from_list(options, remove_data, is_id=False): """API call for Sync / Remove from list""" url = _trakt['baseurl'] + '/sync/{list}/remove'.format(list=options.list) if options.type == 'episodes': values = { 'shows' : remove_data } elif not is_id: values = { options.type : remove_data } else: values = { 'ids' : remove_data } json_data = json.dumps(values) if options.verbose: print(url) pp.pprint(json_data) if _proxy['proxy']: r = requests.post(url, data=json_data, headers=_headers, proxies=_proxyDict, timeout=(10, 60)) else: r = requests.post(url, data=json_data, headers=_headers, timeout=(5, 60)) if r.status_code != 200: print "Error removing items from {list}: {status} [{text}]".format( list=options.list, status=r.status_code, text=r.text) return None else: return json.loads(r.text) def main(): """ Main program loop * Read configuration file and validate * Authenticate if require * Export data from Trakt.tv * Cleanup list from Trakt.tv * Write to CSV """ ## Parse inputs if any parser = argparse.ArgumentParser(version='%(prog)s 0.3', description=desc, epilog=epilog) parser.add_argument('-c', '--config', help='allow to overwrite default config filename, default %(default)s', action='store', type=str, dest='config', default='tconfig.ini') parser.add_argument('-o', '--output', help='allow to overwrite default output filename, default %(default)s', nargs='?', type=str, const='export.csv', default=None) parser.add_argument('-t', '--type', help='allow to overwrite type, default %(default)s', choices=['movies', 'shows', 'episodes'], dest='type', default='movies') parser.add_argument('-l', '--list', help='allow to overwrite default list, default %(default)s', choices=['watchlist', 'collection', 'history'], dest='list', default='history') parser.add_argument('-u', '--userlist', help='allow to export a user custom list, default %(default)s', dest='userlist', default=None) parser.add_argument('-C', '--clean', help='empty list after export, default %(default)s', default=False, action='store_true', dest='clean') parser.add_argument('-D', '--duplicate', help='remove duplicate from list after export, default %(default)s', default=False, action='store_true', dest='dup') #parser.add_argument('-d', '--dryrun', # help='do not update the account, default %(default)s', # default=True, action='store_true', dest='dryrun') parser.add_argument('-V', '--verbose', help='print additional verbose information, default %(default)s', default=True, action='store_true', dest='verbose') options = parser.parse_args() ## Display debug information if options.verbose: print "Options: %s" % options if options.type == 'episodes' and options.list == "collection": print "Error, you can only fetch {0} from the history or watchlist list".format(options.type) sys.exit(1) if options.userlist: options.list = options.userlist if not options.output: options.output = 'export_{type}_{list}.csv'.format(type=options.type, list=options.list) ## Read configuration and validate read_config(options) ## Display oauth token if exist, otherwise authenticate to get one if _trakt['oauth_token']: _headers['Authorization'] = 'Bearer ' + _trakt['oauth_token'] _headers['trakt-api-key'] = _trakt['client_id'] else: api_auth(options) ## Display debug information if options.verbose: print "trakt: {}".format(_trakt) print "Authorization header: {}".format(_headers['Authorization']) ## Get lits from Trakt user export_data = [] if options.userlist: export_data = api_get_userlists(options, 1) if export_data: print "Found {0} user list".format(len(export_data)) #pp.pprint(export_data) for data in export_data: print "Found list id '{id}' name '{name}' with {items} items own by {own}".format( name=data['name'], id=data['ids']['trakt'], items=data['item_count'], own=data['user']['username']) print("Input the custom list id to export") options.listid = str(raw_input('Input:')) global response_arr ## Cleanup global.... response_arr = [] export_data = api_get_userlist(options, 1) #pp.pprint(export_data) if export_data: print "Found {0} Item-Count".format(len(export_data)) else: print "Error, no item return for {type} from the user list {list}".format( type=options.type, list=options.userlist) sys.exit(1) ## Get data from Trakt if not export_data: export_data = api_get_list(options, 1) if export_data: print "Found {0} Item-Count".format(len(export_data)) else: print "Error, no item return for {type} from the {list} list".format( type=options.type, list=options.list) sys.exit(1) if options.list == 'history': options.time = 'watched_at' elif options.list == 'watchlist': options.time = 'listed_at' elif options.list == 'collection': options.time = 'collected_at' elif option.userlist != None: options.time = 'listed_at' export_csv = [] find_dupids = [] for data in export_data: #pp.pprint(data) if options.type[:-1] != "episode" and 'imdb' in data[options.type[:-1]]['ids']: find_dupids.append(data[options.type[:-1]]['ids']['imdb']) export_csv.append({ 'imdb' : data[options.type[:-1]]['ids']['imdb'], 'trakt_id' : data[options.type[:-1]]['ids']['trakt'], options.time : data[options.time], 'title' : data[options.type[:-1]]['title'].encode('utf-8')}) elif 'tmdb' in data[options.type[:-1]]['ids']: find_dupids.append(data[options.type[:-1]]['ids']['tmdb']) if not data['episode']['title']: data['episode']['title'] = "no episode title" export_csv.append({ 'tmdb' : data[options.type[:-1]]['ids']['tmdb'], 'trakt_id' : data[options.type[:-1]]['ids']['trakt'], options.time : data[options.time], 'season' : data[options.type[:-1]]['season'], 'episode' : data[options.type[:-1]]['number'], 'episode_title' : data['episode']['title'].encode('utf-8'), 'show_title' : data['show']['title'].encode('utf-8')}) #print export_csv ## Write export data into CSV file write_csv(options, export_csv) ## Empty list after export if options.clean: cleanup_results = {'sentids' : 0, 'deleted' : 0, 'not_found' : 0} to_remove = [] for data in export_data: # TODO add filter #if data[options.time] == "2012-01-01T00:00:00.000Z": to_remove.append({'ids': data[options.type[:-1]]['ids']}) if len(to_remove) >= 10: # Remove by batch of 10 cleanup_results['sentids'] += len(to_remove) result = api_remove_from_list(options, to_remove) if result: print "Result: {0}".format(result) if 'deleted' in result and result['deleted']: cleanup_results['deleted'] += result['deleted'][options.type] if 'not_found' in result and result['not_found']: cleanup_results['not_found'] += len(result['not_found'][options.type]) to_remove = [] # Remove the rest if len(to_remove) > 0: #print pp.pprint(data) cleanup_results['sentids'] += len(to_remove) result = api_remove_from_list(options, to_remove) if result: print "Result: {0}".format(result) if 'deleted' in result and result['deleted']: cleanup_results['deleted'] += result['deleted'][options.type] if 'not_found' in result and result['not_found']: cleanup_results['not_found'] += len(result['not_found'][options.type]) print "Overall cleanup {sent} {type}, results deleted:{deleted}, not_found:{not_found}".format( sent=cleanup_results['sentids'], type=options.type, deleted=cleanup_results['deleted'], not_found=cleanup_results['not_found']) ## Found duplicate and remove duplicate dup_ids = [item for item, count in collections.Counter(find_dupids).items() if count > 1] print "Found {dups} duplicate out of {total} {entry}".format( entry=options.type, dups=len(dup_ids), total=len(find_dupids)) if options.dup: if len(dup_ids) > 0: print dup_ids dup_results = {'sentids' : 0, 'deleted' : 0, 'not_found' : 0} to_remove = [] for dupid in find_dupids: count = 0 for data in export_data: if data[options.type[:-1]]['ids']['imdb'] == dupid: #print "{0} {1}".format(dupid, data['id']) count += 1 if count > 1: print "Removing {0} {1}".format(dupid, data['id']) to_remove.append(data['id']) dup_results['sentids'] += len(to_remove) result = api_remove_from_list(options, to_remove, is_id=True) if len(to_remove) >= 10: # Remove by batch of 10 if result: print "Result: {0}".format(result) if 'deleted' in result and result['deleted']: dup_results['deleted'] += result['deleted'][options.type] if 'not_found' in result and result['not_found']: dup_results['not_found'] += len(result['not_found'][options.type]) to_remove = [] ## Remove the rest if len(to_remove) > 0: dup_results['sentids'] += len(to_remove) result = api_remove_from_list(options, to_remove, is_id=True) if result: print "Result: {0}".format(result) if 'deleted' in result and result['deleted']: dup_results['deleted'] += result['deleted'][options.type] if 'not_found' in result and result['not_found']: dup_results['not_found'] += len(result['not_found'][options.type]) to_remove = [] print "Overall {dup} duplicate {sent} {type}, results deleted:{deleted}, not_found:{not_found}".format( dup=len(dup_ids), sent=dup_results['sentids'], type=options.type, deleted=dup_results['deleted'], not_found=dup_results['not_found']) if __name__ == '__main__': main() ================================================ FILE: get_imdbid.py ================================================ import os, time, requests, json, sys, re, configparser config = configparser.ConfigParser() config.read('./config.ini') omdbapi_key = config['sonarr']['omdbapi_key'] add_count = 0 failed_count = 0 res = 0 def main(): global add_count global failed_count global res if len(sys.argv)<2: print ("No list Specified... Bye!!"); sys.exit(-1) f=open(sys.argv[1], "r") if f.mode == 'r': f1 = f.readlines() print('\033c') res = input("This list contains S) TV Shows or M) Movies [S/M]? : ") if res == "S" or "s": res = 'series' elif res == "M" or "m": res = 'movie' else: print("Invalid Entry"); sys.exit(0) fo = open("{}.csv".format(res), "a") fo.write("title,year,imdbid\n") for x in f1: r = requests.get("https://www.omdbapi.com/?t={}&type={}&apikey={}".format(x.rstrip(),res,omdbapi_key)) if r.status_code == 200: item = json.loads(r.text) if item.get('Response') == "False": failed_count +=1 ff = open("{}_failed".format(res), "a") ff.write("{} Failed to be Matched\n".format(x.rstrip())) ff.close() continue else: year = item.get('Year') imdbid = item.get('imdbID') title = item.get('Title') title = re.sub('[(]\d{4}[)]','',title) fo.write("{},{},{}\n".format(title.rstrip(),year[:4],imdbid)) #print ("{},{},{}".format(title.rstrip(),year[:4],imdbid)) print('\033c') print("Matching {} {}.".format(title,year[:4])) add_count +=1 print("\u001b[32mMatched {} of {}, {} Failed to match. {} file was created.\u001b[0m".format(add_count,len(f1),failed_count,res)) fo.close() if __name__ == "__main__": main() ================================================ FILE: lidarr_add_from_list.py ================================================ """Add artists from a CSV list into Lidarr.""" import csv import json import logging import logging.handlers import os import sys import configparser import requests from requests.adapters import HTTPAdapter, Retry from colorlog import ColoredFormatter LidarrData: list = [] artist_added_count = 0 artist_exist_count = 0 # Config ############################################################################################################### config = configparser.ConfigParser() config.read('./config.ini') baseurl = config['lidarr']['baseurl'] # urlbase = config['lidarr']['urlbase'] api_key = config['lidarr']['api_key'] rootfolderpath = config['lidarr']['rootfolderpath'] # Logging ###################################################################### logging.getLogger().setLevel(logging.NOTSET) formatter = ColoredFormatter( "%(log_color)s[%(levelname)s]%(reset)s %(white)s%(message)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red,bg_white', }, secondary_log_colors={}, style="%", ) console = logging.StreamHandler() console.setLevel(logging.INFO) console.setFormatter(formatter) logging.getLogger().addHandler(console) if not os.path.exists("./logs"): os.mkdir("./logs") log_file_name = "./logs/lafl.log" filelogger = logging.handlers.RotatingFileHandler(filename=log_file_name) filelogger.setLevel(logging.DEBUG) log_formatter = logging.Formatter("%(asctime)s [%(levelname)-5.5s] %(message)s") filelogger.setFormatter(log_formatter) logging.getLogger().addHandler(filelogger) log = logging.getLogger("app." + __name__) ######################################################################################################################## def create_session() -> requests.Session: """Return a session with retry and backoff configured.""" retries = Retry(total=5, backoff_factor=1, status_forcelist=[500, 502, 503, 504], allowed_methods=["GET", "POST"]) session = requests.Session() adapter = HTTPAdapter(max_retries=retries) session.mount("https://", adapter) session.mount("http://", adapter) return session def add_artist(artist_name: str, foreign_artist_id: str, session: requests.Session) -> None: """Add an artist to Lidarr if it does not already exist.""" payload = { "artistName": artist_name, "foreignArtistId": foreign_artist_id, "QualityProfileId": 1, "MetadataProfileId": 1, "Path": os.path.join(rootfolderpath, artist_name), "albumFolder": True, "RootFolderPath": rootfolderpath, "monitored": True, "addOptions": {"searchForMissingAlbums": False}, } url = f"{baseurl}/api/v1/artist" headers = {"Content-type": "application/json", "X-Api-Key": api_key} try: rsp = session.post(url, headers=headers, json=payload, timeout=10) except requests.RequestException as exc: log.error(f"Error adding {artist_name}: {exc}") return if rsp.status_code == 201: artist_added_count += 1 log.info(f"{artist_name} added to Lidarr :)") elif rsp.status_code == 400: artist_exist_count += 1 log.info(f"{artist_name} already exists in Lidarr.") else: log.error(f"{artist_name} not found. Status: {rsp.status_code}") def get_artist_id(artist: str, session: requests.Session) -> str | None: """Query Lidarr's search API to resolve an artist's MBID.""" url = f"https://api.lidarr.audio/api/v0.4/search?type=artist&query=\"{artist}\"" headers = {"Content-type": "application/json", "X-Api-Key": api_key} try: rsp = session.get(url, headers=headers, timeout=10) except requests.RequestException as exc: log.error(f"Error searching for {artist}: {exc}") return None if rsp.text == "[]": log.error(f"Sorry. We couldn't find {artist}") with open("not_found.txt", "a+", encoding="utf-8") as fo: fo.write(f"{artist}\n") return None data = json.loads(rsp.text) if rsp.status_code == 200: try: return data[0]["id"] except Exception: return data.get("id") return None def lookup_musicbrainz(artist: str, session: requests.Session) -> str | None: """Query MusicBrainz directly for the artist MBID.""" url = "https://musicbrainz.org/ws/2/artist/" params = {"query": f'artist:"{artist}"', "fmt": "json"} headers = { "User-Agent": "ArrTools (https://github.com/sirk123au/ArrTools)", } try: rsp = session.get(url, headers=headers, params=params, timeout=10) except requests.RequestException as exc: log.error(f"Error searching MusicBrainz for {artist}: {exc}") return None if rsp.status_code != 200: log.error( f"MusicBrainz search failed for {artist}. Status: {rsp.status_code}" ) return None data = rsp.json() artists = data.get("artists") if not artists: log.error(f"Sorry. We couldn't find {artist} on MusicBrainz") with open("not_found.txt", "a+", encoding="utf-8") as fo: fo.write(f"{artist}\n") return None return artists[0].get("id") def main() -> None: """Entry point for the script.""" global LidarrData, artist_exist_count, artist_added_count if sys.version_info[0] < 3: log.error("Must be using Python 3") sys.exit(-1) if len(sys.argv) < 2: log.error("No list specified... bye!!") sys.exit(-1) if not os.path.exists(sys.argv[1]): log.error(f"{sys.argv[1]} does not exist") sys.exit(-1) session = create_session() log.info("Downloading Lidarr data...") headers = {"Content-type": "application/json", "X-Api-Key": api_key} url = f"{baseurl}/api/v1/artist" try: rsp = session.get(url, headers=headers, timeout=10) except requests.RequestException as exc: log.error(f"Error connecting to Lidarr: {exc}") sys.exit(-1) if rsp.status_code == 200: LidarrData = json.loads(rsp.text) elif rsp.status_code == 401: log.error("Failed to connect to Lidarr - unauthorized. Check API key in config.") sys.exit(-1) else: log.error(f"URL -> {url} Status Code -> {rsp.status_code}") log.error("Failed to connect to Lidarr...") sys.exit(-1) with open(sys.argv[1], encoding="utf-8") as csvfile: rows = list(csv.DictReader(csvfile)) total_count = len(rows) if total_count == 0: log.error("No artists found in file... bye!!") sys.exit(0) if rows and "artist" not in rows[0]: log.error("Invalid CSV file - header must contain artist and foreignArtistId") sys.exit(-1) log.info(f"Found {total_count} artists in {sys.argv[1]} :)") for row in rows: artist = row.get("artist") foreign_artist_id = row.get("foreignArtistId") if not artist: continue if not foreign_artist_id: foreign_artist_id = get_artist_id(artist, session) if not foreign_artist_id: foreign_artist_id = lookup_musicbrainz(artist, session) if not foreign_artist_id: continue try: existing_ids = [artist.get("foreignArtistId") for artist in LidarrData] if foreign_artist_id in existing_ids: artist_exist_count += 1 log.info(f"{artist} already exists in Lidarr Data.") else: add_artist(artist, foreign_artist_id, session) except Exception as err: log.error(err) sys.exit(-1) log.info( f"Added {artist_added_count} of {total_count} artists, {artist_exist_count} already exist" ) if __name__ == "__main__": main() ================================================ FILE: radarr_add_from_list.py ================================================ import configparser import csv import json import logging.handlers import os import requests import sys import urllib.parse from colorlog import ColoredFormatter movie_added_count = 0 movie_exist_count = 0 # Config ############################################################################################################### config = configparser.ConfigParser() config.read('./config.ini') baseurl = config['radarr']['baseurl'] urlbase = config['radarr']['urlbase'] api_key = config['radarr']['api_key'] rootfolderpath = config['radarr']['rootfolderpath'] searchForMovie = config['radarr']['searchForMovie'] if searchForMovie == "1" or searchForMovie == "True": searchForMovie = True else: searchForMovie = False quality_profile_id = config['radarr']['qualityProfileId'] omdbapi_key = config['radarr']['omdbapi_key'] # Logging ############################################################################################################## logging.getLogger().setLevel(logging.NOTSET) formatter = ColoredFormatter( "%(log_color)s[%(levelname)s]%(reset)s %(white)s%(message)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red,bg_white', }, secondary_log_colors={}, style='%' ) logger = logging.StreamHandler() logger.setLevel(logging.INFO) # DEBUG To show all logger.setFormatter(formatter) logging.getLogger().addHandler(logger) if not os.path.exists("./logs/"): os.mkdir("./logs/") logFileName = "./logs/rafl.log" # .format(datetime.now().strftime("%Y-%m-%d-%H.%M.%S")) filelogger = logging.handlers.RotatingFileHandler(filename=logFileName) filelogger.setLevel(logging.DEBUG) logFormatter = logging.Formatter("%(asctime)s [%(levelname)-5.5s] %(message)s") filelogger.setFormatter(logFormatter) logging.getLogger().addHandler(filelogger) log = logging.getLogger("app." + __name__) ######################################################################################################################## def add_movie(title, year, imdbid, quality_profile_id): global movie_added_count global movie_exist_count if year == "" or year is None: year = get_year(title) if imdbid == "" or imdbid is None: imdbid = get_imdbid(title, year) # Store Radarr Server imdbid for faster matching current_movie_ids = [movie.get('imdbId') for movie in RadarrData] if match_profile_id(quality_profile_id): ProfileId = get_profile_from_name(quality_profile_id) if imdbid is None: log.warning(f"Cannot find IMDbId for {title}, attempting to add without it...") # Search by Movie Title in Radarr headers = {"Content-type": "application/json", 'Accept': 'application/json'} url = f"{baseurl}{urlbase}/api/v3/movie/lookup?term={title.replace(' ', '%20')}&apikey={api_key}" radarr_api_response = requests.get(url, headers=headers) data = json.loads(radarr_api_response.text) if radarr_api_response.text == "[]": log.error(f"Sorry. We couldn't find any movies matching {title} ({year})") return if radarr_api_response.status_code == 200: tmdbid = data[0]["tmdbId"] title = data[0]["title"] year = data[0]['year'] images = json.loads(json.dumps(data[0]["images"])) titleslug = data[0]["titleSlug"] movie_data = json.dumps({ "title": title, "qualityProfileId": ProfileId, "year": year, "tmdbId": tmdbid, "titleslug": titleslug, "monitored": True, "minimumAvailability": "released", "rootFolderPath": rootfolderpath, "images": images, "addOptions": {"searchForMovie": searchForMovie} }) # Add Movie To Radarr headers = {"Content-type": "application/json", 'Accept': 'application/json', "X-Api-Key": api_key} url = f'{baseurl}{urlbase}/api/v3/movie' radarr_api_response = requests.post(url, headers=headers, data=movie_data) log.debug(f"Radarr response: {radarr_api_response.status_code}: {radarr_api_response.text}") if radarr_api_response.status_code == 201: movie_added_count += 1 if searchForMovie: log.info(f"{tmdbid}\t {title} ({year}) Added to Radarr :) NowSearching.") else: log.info(f"{tmdbid}\t {title} ({year}) Added to Radarr :) Search Disabled.") elif radarr_api_response.status_code == 400: movie_exist_count += 1 log.info(f"{tmdbid}\t {title} ({year}) already Exists in Radarr.") return else: log.error(f"{imdbid}\t {title} ({year}) Not found, Not added to Radarr.") return elif imdbid not in current_movie_ids: log.warning(f"Found IMDbId for {title} - attempting to add to Radarr...") # Build json Data to import into radarr session = requests.Session() adapter = requests.adapters.HTTPAdapter(max_retries=20) session.mount('https://', adapter) session.mount('http://', adapter) headers = {"Content-type": "application/json", 'Accept': 'application/json'} url = f"{baseurl}{urlbase}/api/v3/movie/lookup/imdb?imdbId={imdbid}&apikey={api_key}" radarr_api_response = session.get(url, headers=headers) if len(radarr_api_response.text) == 0: log.error(f"Sorry. We couldn't find any movies matching {title} ({year})") return if radarr_api_response.status_code == 200: data = json.loads(radarr_api_response.text) tmdbid = data["tmdbId"] title = data["title"] year = data['year'] images = json.loads(json.dumps(data["images"])) titleslug = data["titleSlug"] movie_data = json.dumps({ "title": title, "qualityProfileId": ProfileId, "year": year, "tmdbId": tmdbid, "titleslug": titleslug, "monitored": True, "minimumAvailability": "released", "rootFolderPath": rootfolderpath, "images": images, "addOptions": {"searchForMovie": searchForMovie}}) elif radarr_api_response.status_code == 404: log.error(f"{imdbid}\t {title} ({year}) Movie not found... unable to add to Radarr") return elif radarr_api_response.status_code == 500: log.error(f"{imdbid}\t {title} ({year}) Can't find TMDB ID - movie may have been removed!") return else: log.error("Something else has happened.") return # Add Movie To Radarr headers = {"Content-type": "application/json", 'Accept': 'application/json', "X-Api-Key": api_key} url = f'{baseurl}{urlbase}/api/v3/movie' radarr_api_response = requests.post(url, headers=headers, data=movie_data) log.debug(f"Radarr response: {radarr_api_response.status_code}: {radarr_api_response.text}") if radarr_api_response.status_code == 201: log.debug("Connected to Radarr!") movie_added_count += 1 if searchForMovie: # Check If you want to force download search log.info( f"{imdbid}\t {title} ({year}) Added to Radarr :) Now Searching.") else: log.info( f"{imdbid}\t {title} ({year}) Added to Radarr :) Search Disabled.") else: movie_exist_count += 1 log.info(f"{imdbid}\t {title} ({year}) already exists in Radarr!") return def get_profile_from_name(name :str) -> int: """ Converts Profile Name -> ID :return: ID :type: any """ try: number = int(name) return name except ValueError: profiles = quality_profiles profile = next((item for item in profiles if item["name"] == name), False) if not profile: log.error(f"Could not find profile_id for instance profile ID {name}") return select_profile_id() return profile.get('id') def get_quality_profiles() -> list: """ Parses local Radarr API to get the server's quality profiles and return them to calling functions :return: The server's quality profiles as a list :type: list """ log.info("Getting quality profiles...") headers = {"Content-type": "application/json", "X-Api-Key": f"{api_key}"} url = f"{baseurl}{urlbase}/api/v3/qualityProfile" r = requests.get(url, headers=headers) profiles_json = json.loads(r.text) return profiles_json def select_profile_id(): """ Allows the user to select a quality profile ID at runtime using console input :return: Returns an integer that matches the specified quality profile Id :type: int """ selected = False profile_choice = -1 print("\nPlease enter a valid profile ID:") for profile in quality_profiles: print(f"{profile.get('id')}: {profile.get('name')}") while not selected: user_input = input("> ") selected = match_profile_id(user_input) if selected: profile_choice = user_input return profile_choice def match_profile_id(quality_id) -> bool: """ Checks if a given quality profile ID matches with one from the API. :type: bool :param quality_id: Quality profile ID as a string of int :return: Returns true if the quality profile is matched/found """ profiles = quality_profiles if not quality_id.isdigit(): profile = next((p for p in profiles if p["name"] == quality_id), False) else: profile = next((p for p in profiles if p['id'] == int(quality_id)), False) if not profile: log.error(f'Could not find profile_id for instance profile ID: {quality_id}') if match_profile_id(select_profile_id()): return True return True def get_imdbid(title: str, year: str) -> str | None: """ Uses OMDB to return the IMDB ID (ttXXXXXXX) of a movie :param title: Title of the movie :param year: Year the movie released :return: IMDB ID of the movie if found, or None if not. """ # Get Movie imdbid log.info(f"Getting IMDbId for {title}") parsed_movie_title = urllib.parse.quote(title, "UTF-8") headers = {"Content-type": "application/json", 'Accept': 'application/json'} r = requests.get(f"https://www.omdbapi.com/?t={parsed_movie_title}&y={year}&type=movie&apikey={omdbapi_key}", headers=headers) if r.status_code == 401: log.error("OMDb API Request limit reached!") d = json.loads(r.text) if r.status_code == 200: if d.get('Response') == "False": return None else: return d.get('imdbID') else: return None def get_year(imdbid: str) -> str | None: """ Uses OMDB to check the year that a given movie released :param imdbid: The IMDB ID of a movie :return: Year the movie released if found, None if not """ # Get Movie Year headers = {"Content-type": "application/json", 'Accept': 'application/json'} r = requests.get(f"https://www.omdbapi.com/?t={imdbid}&apikey={omdbapi_key}", headers=headers) if r.status_code == 401: log.error("OMDb API Request limit reached!") d = json.loads(r.text) if r.status_code == 200: if d.get('Response') == "False": return None else: return d.get('Year') else: return None def main(): global RadarrData global quality_profiles global quality_profile_id print('\033c') if sys.version_info[0] < 3: log.error("Must be using Python 3") sys.exit(-1) if len(sys.argv) < 2: log.error("No CSV file specified... bye!!") sys.exit(-1) if not os.path.exists(sys.argv[1]): log.error(f"{sys.argv[1]} does not exist!") sys.exit(-1) log.info("Downloading Radarr Movie Data. :)") headers = {"Content-type": "application/json", "X-Api-Key": api_key} url = f"{baseurl}{urlbase}/api/v3/movie" rsp = requests.get(url, headers=headers) if rsp.status_code == 200: if len(rsp.text) == 0: log.error("No data downloaded from Radarr.") sys.exit(-1) RadarrData = json.loads(rsp.text) if not RadarrData: log.error("No data downloaded from Radarr.") sys.exit(-1) quality_profiles = get_quality_profiles() else: log.error("Failed to connect to Radarr...") sys.exit(-1) log.info(f"Loading {sys.argv[1]}...") with open(sys.argv[1], encoding="ISO-8859-1", errors='ignore') as csvfile: total_count = len(list(csv.DictReader(csvfile))) with open(sys.argv[1], encoding="ISO-8859-1", errors='ignore') as csvfile: movies_list = csv.DictReader(csvfile) if not total_count > 0: log.error("No movies found in CSV file.") exit() if movies_list.fieldnames != ["title", "year", "imdbid"]: log.error("Invalid CSV file - header does not contain title,year,imdbid") sys.exit(-1) log.info(f"Found {total_count} movies in {sys.argv[1]} :)") for row in movies_list: title = row['title'] year = row['year'] imdbid = row['imdbid'] try: if quality_profile_id is None or quality_profile_id == '': log.warning("Quality profile not set in config file.") quality_profile_id = select_profile_id() add_movie(title, year, imdbid,quality_profile_id) except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] log.error(exc_type, fname, exc_tb.tb_lineno) sys.exit(-1) log.info(f"Added {movie_added_count} of {total_count} movies - {movie_exist_count} already existed ;)") if __name__ == "__main__": main() ================================================ FILE: radarr_remove_downloaded.py ================================================ import os, requests, json, logging, logging.handlers, sys from colorlog import ColoredFormatter import configparser # Config ############################################################################################################### config = configparser.ConfigParser() config.read('./config.ini') baseurl = config['radarr']['baseurl'] api_key = config['radarr']['api_key'] # Logging ############################################################################################################## formatter = ColoredFormatter( "%(log_color)s[%(levelname)s]%(reset)s %(white)s%(message)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red,bg_white', }, secondary_log_colors={}, style='%' ) logging.getLogger().setLevel(logging.NOTSET) logger = logging.StreamHandler(sys.stdout) logger.setLevel(logging.INFO) # DEBUG To show all # logFormatter = logging.Formatter("\033[1;31;32m[%(levelname)s] \u001b[0m%(message)s") logger.setFormatter(formatter) logging.getLogger().addHandler(logger) rotatingHandler = logging.handlers.RotatingFileHandler(filename='./rrd.log') rotatingHandler.setLevel(logging.DEBUG) logFormatter = logging.Formatter("%(asctime)s [%(levelname)-5.5s] %(message)s") rotatingHandler.setFormatter(logFormatter) logging.getLogger().addHandler(rotatingHandler) log = logging.getLogger("app." + __name__) ######################################################################################################################## print('\033c') if sys.version_info[0] < 3: log.error("Must be using Python 3"); sys.exit(-1) log.info("Downloading Radarr Movie Data...") headers = {"Content-type": "application/json", "X-Api-Key": api_key } url = "{}/api/v3/movie".format(baseurl) rsp = requests.get(url, headers=headers) data = json.loads(rsp.text) count = 0 for i in data: headers = {"Content-type": "application/json", "X-Api-Key": api_key } url = "{}/api/v3/movie/{}?deleteFiles=false&addExclusion=false".format(baseurl,i['id']) rsp = requests.delete(url, headers=headers) print(rsp.text) if rsp.status_code == 200: log.info ("\u001b[36m{} ({})\u001b[0m \u001b[31mRemoving from Radarr...\u001b[0m".format(i['title'],i['year'])) # if i['hasFile']: print(json.dumps(i, indent=4, sort_keys=True)) # if i['year'] < 1980 and i['hasFile']: # if os.path.exists(i['path']): # rsp = requests.delete(url, headers=headers) # if rsp.status_code == 200: # count +=1 # log.info ("\u001b[36m{} ({})\u001b[0m is older than 1980, \u001b[31mRemoving from Radarr...\u001b[0m".format(i['title'],i['year'])) if i['hasFile']: if os.path.exists(i['path']): # if "720" or "1080" in i['movieFile']['quality']['quality']['name']: rsp = requests.delete(url, headers=headers) if rsp.status_code == 200: count +=1 log.info ("\u001b[36m{} ({})\u001b[0m Has been downloaded, \u001b[31mRemoving from Radarr...\u001b[0m".format(i['title'],i['year'])) log.info ("Removed {} Movies.".format(count)) ================================================ FILE: radarr_unmonitor_downloaded.py ================================================ import os, requests, json, logging, logging.handlers, sys from colorlog import ColoredFormatter import configparser # Config ############################################################################################################### config = configparser.ConfigParser() config.read('./config.ini') baseurl = config['radarr']['baseurl'] urlbase = config['radarr']['urlbase'] api_key = config['radarr']['api_key'] if urlbase != "": baseurl = "{}{}".format(baseurl,urlbase) # Logging ############################################################################################################## formatter = ColoredFormatter( "%(log_color)s[%(levelname)s]%(reset)s %(white)s%(message)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red,bg_white', }, secondary_log_colors={}, style='%' ) logging.getLogger().setLevel(logging.NOTSET) logger = logging.StreamHandler(sys.stdout) logger.setLevel(logging.INFO) # DEBUG To show all # logFormatter = logging.Formatter("\033[1;31;32m[%(levelname)s] \u001b[0m%(message)s") logger.setFormatter(formatter) logging.getLogger().addHandler(logger) log = logging.getLogger("app." + __name__) ######################################################################################################################## print('\033c') if sys.version_info[0] < 3: log.error("Must be using Python 3"); sys.exit(-1) log.info("Downloading Radarr Movie Data...") headers = {"Content-type": "application/json", "X-Api-Key": api_key } url = "{}/api/v3/movie".format(baseurl) rsp = requests.get(url, headers=headers) data = json.loads(rsp.text) count = 0 for i in data: headers = {"Content-type": "application/json", "X-Api-Key": api_key } url = "{}/api/v3/movie/{}".format(baseurl,i['id']) rsp = requests.get(url, headers=headers) if rsp.status_code == 200: if i['hasFile']: if os.path.exists(i['path']): if i['monitored'] == True: # print(json.dumps(i, indent=4, sort_keys=True)) data = json.loads(json.dumps(i)) data['monitored'] = False data = json.dumps(data, indent=4, sort_keys=True) headers = {"Content-type": "application/json", 'Accept':'application/json', "X-Api-Key": api_key} url = '{}/api/movie'.format(baseurl) rsp = requests.put(url, headers=headers, data=data) if rsp.status_code == 201: count += 1 log.info ("\u001b[36m{} ({})\u001b[0m Has been downloaded, \u001b[31mUnmonitoring....\u001b[0m".format(i['title'],i['year'])) log.info ("Unmonitored {} Movies.".format(count)) ================================================ FILE: remove_from_sonarr.py ================================================ import os, requests, json, logging, logging.handlers, sys from colorlog import ColoredFormatter import configparser # Config ############################################################################################################### config = configparser.ConfigParser() config.read('./config.ini') baseurl = config['sonarr']['baseurl'] api_key = config['sonarr']['api_key'] # Logging ############################################################################################################## formatter = ColoredFormatter( "%(log_color)s[%(levelname)s]%(reset)s %(white)s%(message)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red,bg_white', }, secondary_log_colors={}, style='%' ) logging.getLogger().setLevel(logging.NOTSET) logger = logging.StreamHandler(sys.stdout) logger.setLevel(logging.INFO) # DEBUG To show all # logFormatter = logging.Formatter("\033[1;31;32m[%(levelname)s] \u001b[0m%(message)s") logger.setFormatter(formatter) logging.getLogger().addHandler(logger) rotatingHandler = logging.handlers.RotatingFileHandler(filename='./rfs.log') rotatingHandler.setLevel(logging.DEBUG) logFormatter = logging.Formatter("%(asctime)s [%(levelname)-5.5s] %(message)s") rotatingHandler.setFormatter(logFormatter) logging.getLogger().addHandler(rotatingHandler) log = logging.getLogger("app." + __name__) ######################################################################################################################## print('\033c') if sys.version_info[0] < 3: log.error("Must be using Python 3"); sys.exit(-1) log.info("Downloading Sonarr Series Data...") headers = {"Content-type": "application/json", "X-Api-Key": api_key } url = "{}/sonarr/api/series".format(baseurl) rsp = requests.get(url, headers=headers) data = json.loads(rsp.text) count = 0 for i in data: headers = {"Content-type": "application/json", "X-Api-Key": api_key } url = "{}/sonarr/api/series/{}?deleteFiles=false".format(baseurl,i['id']) # if 'Documentary' in i['genres']: # print('{} has these genres {}'.format(i['title'],i['genres'])) if i['episodeFileCount'] == 0: # print(json.dumps(i, indent=4, sort_keys=True)) rsp = requests.delete(url, headers=headers) if rsp.status_code == 200: count +=1 log.info ("Removing {} from Sonarr...".format(i['title'])) log.info ("Removed {} Shows.".format(count)) ================================================ FILE: requirements.txt ================================================ # pip install -r requirements.txt requests colorlog ================================================ FILE: sonarr_add_from_list.py ================================================ import os, time, requests, logging, logging.handlers, json, sys, re, csv, configparser, base64 from colorlog import ColoredFormatter from datetime import datetime show_added_count = 0 show_exist_count = 0 sonarrData = [] # Config ############################################################################################################### config = configparser.ConfigParser() config.read('./config.ini') baseurl = config['sonarr']['baseurl'] urlbase = config['sonarr']['urlbase'] api_key = config['sonarr']['api_key'] rootfolderpath = config['sonarr']['rootfolderpath'] searchForShow = config['sonarr']['searchForShow'] qualityProfileId = config['sonarr']['qualityProfileId'] omdbapi_key = config['sonarr']['omdbapi_key'] # Logging ############################################################################################################## logging.getLogger().setLevel(logging.NOTSET) formatter = ColoredFormatter( "%(log_color)s[%(levelname)s]%(reset)s %(white)s%(message)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red,bg_white', }, secondary_log_colors={}, style='%' ) logger = logging.StreamHandler() logger.setLevel(logging.INFO) # DEBUG To show all logger.setFormatter(formatter) logging.getLogger().addHandler(logger) if not os.path.exists("./logs/"): os.mkdir("./logs/") logFileName = "./logs/safl.log" filelogger = logging.handlers.RotatingFileHandler(filename=logFileName) filelogger.setLevel(logging.DEBUG) logFormatter = logging.Formatter("%(asctime)s [%(levelname)-5.5s] %(message)s") filelogger.setFormatter(logFormatter) logging.getLogger().addHandler(filelogger) log = logging.getLogger("app." + __name__) ######################################################################################################################## def add_show(title,year,imdbid): # Add Missing to sonarr Work in Progress global show_added_count global show_exist_count if imdbid == None : imdbid = get_imdbid(title,year) if imdbid == None : log.info("Not imdbid found for {}".format(title)); return imdbIds = [] tvdbIds = [] for shows_to_add in sonarrData: imdbIds.append(shows_to_add.get('imdbId')) for shows_to_add in sonarrData: tvdbIds.append(shows_to_add.get('tvdbId')) if imdbid not in imdbIds: tvdbId = get_tvdbId(title,imdbid) if tvdbId in tvdbIds: show_exist_count +=1 log.info("\033[1;36m{}\t {} ({}) already Exists in Sonarr.\u001b[0m".format(imdbid,title,year)) return session = requests.Session() adapter = requests.adapters.HTTPAdapter(max_retries=20) session.mount('https://', adapter) session.mount('http://', adapter) if tvdbId == None: log.error("No tvdbId found for {}".format(title)); return if not qualityProfileId.isdigit(): ProfileId = get_profile_from_id(qualityProfileId) elif qualityProfileId == None: log.error("\u001b[35m qualityProfileId Not Set in the config correctly.\u001b[0m") else: ProfileId = qualityProfileId headers = {"Content-type": "application/json"} url = "{}{}/api/v3/series/lookup?term=tvdb:{}&apikey={}".format(baseurl,urlbase,tvdbId, api_key ) rsp = session.get(url, headers=headers) data = json.loads(rsp.text) if rsp.text =="[]": log.error("\u001b[35mSorry. We couldn't find {} ({})\u001b[0m".format(title,year)) return if len(rsp.text)==0: log.error("Sorry. We couldn't find any Shows matching {} ({})".format(title,year)) return tvdbId = data[0]["tvdbId"] title = data[0]["title"] year = data[0]["year"] images = json.loads(json.dumps(data[0]["images"])) titleslug = data[0]["titleSlug"] seasons = json.loads(json.dumps(data[0]["seasons"])) headers = {"Content-type": "application/json", "X-Api-Key": "{}".format(api_key)} data = json.dumps({ "title": title , "year": year , "tvdbId": tvdbId , "titleslug": titleslug, "monitored": True , "seasonFolder": True, "qualityProfileId": ProfileId, "rootFolderPath": rootfolderpath , "images": images, "seasons": seasons, "addOptions": { "ignoreEpisodesWithFiles": True, "ignoreEpisodesWithoutFiles": False, "searchForMissingEpisodes": bool(searchForShow) } }) url = '{}{}/api/v3/series'.format(baseurl,urlbase) rsp = requests.post(url, headers=headers, data=data) data = json.loads(rsp.text) if rsp.status_code == 201: show_added_count +=1 if searchForShow == "True": log.info("\033[0;32m{}\t {} ({}) Added to Sonarr :) Now Searching.\u001b[0m".format(imdbid,title,year)) else: log.info("\033[0;32m{}\t {} ({}) Added to Sonarr :) \033[1;31mSearch Disabled.\u001b[0m".format(imdbid,title,year)) elif rsp.status_code == 400: show_exist_count +=1 log.info("\033[1;36m{}\t {} ({}) already Exists in Sonarr.\u001b[0m".format(imdbid,title,year)) return else: log.error("\u001b[32m{}\t {} ({}) Not found, Not added to Sonarr.\u001b[0m".format(imdbid,title,year)) return else: show_exist_count+=1 log.info("\033[1;36m{}\t {} ({}) already Exists in Sonarr.\u001b[0m".format(imdbid,title,year)) return def get_imdbid(title,year): # Get TV Show imdbid headers = {"Content-type": "application/json", 'Accept':'application/json'} r = requests.get("https://www.omdbapi.com/?t={}&y={}&apikey={}".format(title,year,omdbapi_key), headers=headers) if r.status_code == 401: log.error("omdbapi Request limit reached!") return None if r.status_code == 200: d = json.loads(r.text) if d.get('Response') == "False": return None else: return d.get('imdbID') else: return None def get_tvdbId(title,imdbid): api = str(base64.b64decode('YWE2Yjc5YTBlZDdjM2Y3NWUyOWI1MjkyOTAyNjhmOGFkNzM0ZmE3MWUzYzA3Zjg2YmE2OTVlMzQzZDFmZmNjMw==')) title = title.replace(" ","-"); title = title.replace("'","-"); title = title.replace(":","") if title.find("&"): title = title.replace(" ",""); title = title.replace("&","-") headers = {'Content-Type': 'application/json', 'trakt-api-version': '2', 'trakt-api-key': api} rsp = requests.get('https://api.trakt.tv/search/imdb/{}?type=show'.format(imdbid), headers=headers) if rsp.status_code == 403: log.error("trakt Api Failed"); return None if rsp.status_code == 200: d = json.loads(rsp.text) if d == []: rsp = requests.get('https://api.trakt.tv/shows/{}'.format(title), headers=headers) if rsp.status_code == 200: d = json.loads(rsp.text) if d == []: return None return d['ids']['tvdb'] else: return None else: return d[0]['show']['ids']['tvdb'] else: return None def get_profile_from_id(id): headers = {"Content-type": "application/json", "X-Api-Key": "{}".format(api_key)} url = "{}{}/api/v3/profile".format(baseurl,urlbase) r = requests.get(url, headers=headers) d = json.loads(r.text) profile = next((item for item in d if item["name"].lower() == id.lower()), False) if not profile: log.error('Could not find profile_id for instance profile {}'.format(id)) sys.exit(0) return profile.get('id') def main(): print('\033c') if sys.version_info[0] < 3: log.error("Must be using Python 3"); sys.exit(-1) global sonarrData if len(sys.argv)<2: log.error("No list Specified... Bye!!"); sys.exit(-1) if not os.path.exists(sys.argv[1]): log.info("{} Does Not Exist".format(sys.argv[1])); sys.exit(-1) log.info("Downloading Sonarr Show Data. :)") headers = {"Content-type": "application/json", "X-Api-Key": api_key } url = "{}{}/api/v3/series".format(baseurl,urlbase) rsp = requests.get(url , headers=headers) if rsp.status_code == 200: sonarrData = json.loads(rsp.text) else: log.error("Failed to connect to Radar...") with open(sys.argv[1], encoding="utf8") as csvfile: total_count = len(list(csv.DictReader(csvfile))) with open(sys.argv[1], encoding="utf8") as csvfile: s = csv.DictReader(csvfile) if not total_count>0: log.error("No TV Shows Found in file... Bye!!"); exit() log.info("Found {} TV Shows in {}. :)".format(total_count,sys.argv[1])) for row in s: if not (row): continue if len(row) >= 4: log.error("Invalid Format on line {} Data:{}".format(str(s.line_num),row)); continue try: row['title'] except: log.error("Invalid CSV File, Header does not contain title,year,imdbid"); sys.exit(-1) title = row['title']; year = row['year']; imdbid = row['imdbid'] try: add_show(title,year,imdbid) except Exception as e: log.error(e); sys.exit(-1) log.info("Added {} of {} Shows, {} Already Exist".format(show_added_count,total_count,show_exist_count)) if __name__ == "__main__": main()