[
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\ngithub: sirk123au\npatreon: # Replace with a single Patreon username\nopen_collective: # Replace with a single Open Collective username\nko_fi: # Replace with a single Ko-fi username\ntidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel\ncommunity_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry\nliberapay: # Replace with a single Liberapay username\nissuehunt: # Replace with a single IssueHunt username\notechie: # Replace with a single Otechie username\ncustom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']\n"
  },
  {
    "path": ".gitignore",
    "content": "syntax: glob\nconfig.ini\n*.log\n.vscode\ntrakt_search.py\n*.csv\n*config.ini\n*.pyc\n*.csv\nimport_from_tmdb.py\nyt_music_vid_get.py\ncookies.txt"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "## Radarr and Sonarr Tools\n\n*radarr_add_from_list.py* Add Movies from a csv formatted file.\n\n*sonarr_add_from_list.py* Add Shows from a csv formatted file.\n\n*lidarr_add_from_list.py* Add Artists from a csv formatted file.\n\n*radarr_remove_downloaded.py* Removes already downloaded movies and removes their entries from Radarr.\n\n*backup_radarr_2csv.py* Creates a backup of the Radarr Database for easy importing.\n\n*backup_sonarr_2csv.py* Creates a backup of the Sonarr Database for easy importing.\n\n*backup_lidarr_2csv.py* Creates a backup of the Lidarr Database for easy importing.\n\n*get_imdbid.py* Matches the imdbd from a csv list MovieName/ShowName,Year for easy importing for the list import.\n\n*arr_gui.py* Standalone GUI to import or export data for Radarr, Sonarr or Lidarr.\n\nUsing radarr_add_from_list/sonarr_add_from_list\nThe input list file has to have the format. \nIt has to have MovieName/ShowName,Year,imdbid   **imdbid is Optional Makes it easer to find movie/TV show\n\nUse pip install -r requirements.txt to install the required python modules \n\nMovies CSV\n```\ntitle,year,imdbid (This header has to be included in the csv for it to work correctly)\nBen-Hur,1959,tt0052618\nGone with the Wind,1939,tt0031381\n\nWithout imdbid\n\ntitle,year,imdbid (This header has to be included in the csv for it to work correctly)\nThe English Patient,1996\nSchindler's List,1993\n```\nTV Shows CSV\n\n```\ntitle,year,imdbid (This header has to be included in the csv for it to work correctly)\n13 Reasons Why,2017,tt1837492\n50 Central,2017,tt7261310\n\nWithout imdbID\n\ntitle,year,imdbid (This header has to be included in the csv for it to work correctly)\n60 Days In,2016\n9-1-1,2018\nA Discovery of Witches,2018\n\n```\nArtist CSV\n\n```\nartist,foreignArtistId\n10cc\n2 DJ's and One\n3 Doors Down\n3-11 Porter\n\nWith foreignArtistId\n\nartist,foreignArtistId\nWeird Al Yankovic,7746d775-9550-4360-b8d5-c37bd448ce01\nAdele,cc2c9c3c-b7bc-4b8b-84d8-4fbd8779e493\nAlanis Morissette,4bdcee62-4902-4773-8cd1-e252e2e31225\nArctic Monkeys,ada7a83c-e3e1-40f1-93f9-3e73dbc9298a\nAugie March,29070ba5-c3df-41d9-bed0-8e2f1e1c22ad\nBABYMETAL,27e2997f-f7a1-4353-bcc4-57b9274fa9a4\nBackstreet Boys,2f569e60-0a1b-4fb9-95a4-3dc1525d1aad\n\n```\n\nIf `foreignArtistId` is omitted, `lidarr_add_from_list.py` will attempt to\nretrieve the MusicBrainz ID automatically.\n\nRun the GUI with\n```\n$ python3 arr_gui.py\n```\nThe CLI scripts remain for advanced usage, but the GUI handles common import\nand export operations without calling them.\nRename config_example.ini and add your details\n\n```\n[radarr]\napi_key = Radarr Api Key\nbaseurl = http://localhost:7878 Radarr Base Url\nurlbase = ; Include URL Base if you have it enabled\nrootfolderpath = Movie Root Path (trailing slash is needed eg. /media/Movies/ or d:\\media\\Movies\\)\nsearchForMovie = Enable forced search\nqualityProfileId = \nomdbapi_key =  sign up here for free api key http://www.omdbapi.com/apikey.aspx\n\n[sonarr]\napi_key = Sonarr Api Key \nbaseurl = http://localhost:8989\nurlbase = ; Include URL Base if you have it enabled\nrootfolderpath = Show Root Path (trailing slash is needed eg. /media/shows/ or d:\\media\\shows\\)\nsearchForShow = \nqualityProfileId = \nomdbapi_key = \ntvdb_api =  ; sign up here for a api key https://thetvdb.com/api-information\ntvdb_userkey = \ntvdb_username = \n\n[lidarr]\napi_key =\nbaseurl = http://localhost:8686\nrootfolderpath =\n\n[gui]\n# Optional default CSV path used by arr_gui.py\ndefault_csv =\n\n\nStandard Profile ID\n1 Any\n2 SD\n3 HD-720p\n4 HD-1080p\n5 Ultra-HD\n6 HD - 720p/1080p\n```\n\nThanks for the support :)\n\n[![Github Sponsorship](https://img.shields.io/badge/support-me-red.svg)](https://github.com/users/sirk123au/sponsorship)\n\n[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/M4M25DUMM)\n"
  },
  {
    "path": "RadarrSync.py",
    "content": "import os\nimport logging\nimport requests\nimport json\nimport configparser\nimport sys\n\n\nDEV = False\nVER = '1.0.1'\n\n########################################################################################################################\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\nlogFormatter = logging.Formatter(\"%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s]  %(message)s\")\n\nfileHandler = logging.FileHandler(\"./Output.txt\")\nfileHandler.setFormatter(logFormatter)\nlogger.addHandler(fileHandler)\n\nconsoleHandler = logging.StreamHandler(sys.stdout)\nconsoleHandler.setFormatter(logFormatter)\nlogger.addHandler(consoleHandler)\n########################################################################################################################\n\n\ndef ConfigSectionMap(section):\n    dict1 = {}\n    options = Config.options(section)\n    for option in options:\n        try:\n            dict1[option] = Config.get(section, option)\n            if dict1[option] == -1:\n                logger.debug(\"skip: %s\" % option)\n        except:\n            print(\"exception on %s!\" % option)\n            dict1[option] = None\n    return dict1\n\nlogger.debug('RadarSync Version {}'.format(VER))\nConfig = configparser.ConfigParser()\n\n# Loads an alternate config file so that I can work on my servers without uploading config to github\nif DEV:\n    settingsFilename = os.path.join(os.getcwd(), 'Dev'\n                                                 'Config.txt')\nelse:\n    settingsFilename = os.path.join(os.getcwd(), 'Config.txt')\nConfig.read(settingsFilename)\n\nradarr_url = ConfigSectionMap(\"Radarr\")['url']\nradarr_key = ConfigSectionMap(\"Radarr\")['key']\nradarrSession = requests.Session()\nradarrSession.trust_env = False\nradarrMovies = radarrSession.get('{0}/api/movie?apikey={1}'.format(radarr_url, radarr_key))\nif radarrMovies.status_code != 200:\n    logger.error('Radarr server error - response {}'.format(radarrMovies.status_code))\n    sys.exit(0)\n\nfor server in Config.sections():\n\n    if server == 'Default' or server == \"Radarr\":\n        continue  # Default section handled previously as it always needed\n\n    else:\n        logger.debug('syncing to {0}'.format(server))\n\n        session = requests.Session()\n        session.trust_env = False\n        SyncServer_url = ConfigSectionMap(server)['url']\n        SyncServer_key = ConfigSectionMap(server)['key']\n        SyncServer_target_profile = ConfigSectionMap(server)['target_profile']\n        SyncServerMovies = session.get('{0}/api/movie?apikey={1}'.format(SyncServer_url, SyncServer_key))\n        if SyncServerMovies.status_code != 200:\n            logger.error('4K Radarr server error - response {}'.format(SyncServerMovies.status_code))\n            sys.exit(0)\n\n    # build a list of movied IDs already in the sync server, this is used later to prevent readding a movie that already\n    # exists.\n    # TODO refactor variable names to make it clear this builds list of existing not list of movies to add\n    # TODO #11 add reconcilliation to remove movies that have been deleted from source server\n    movieIds_to_syncserver = []\n    for movie_to_sync in SyncServerMovies.json():\n        movieIds_to_syncserver.append(movie_to_sync['tmdbId'])\n        #logger.debug('found movie to be added')\n\n    newMovies = 0\n    searchid = []\n    for movie in radarrMovies.json():\n        if movie['profileId'] == int(ConfigSectionMap(server)['profile']):\n            if movie['tmdbId'] not in movieIds_to_syncserver:\n                logging.debug('title: {0}'.format(movie['title']))\n                logging.debug('qualityProfileId: {0}'.format(movie['qualityProfileId']))\n                logging.debug('titleSlug: {0}'.format(movie['titleSlug']))\n                images = movie['images']\n                for image in images:\n                    image['url'] = '{0}{1}'.format(radarr_url, image['url'])\n                    logging.debug(image['url'])\n                logging.debug('tmdbId: {0}'.format(movie['tmdbId']))\n                logging.debug('path: {0}'.format(movie['path']))\n                logging.debug('monitored: {0}'.format(movie['monitored']))\n\n                # Update the path based on \"path_from\" and \"path_to\" passed to us in Config.txt\n                path = movie['path']\n                path = path.replace(ConfigSectionMap(server)['path_from'], ConfigSectionMap(server)['path_to'])\n\n                payload = {'title': movie['title'],\n                           'qualityProfileId': movie['qualityProfileId'],\n                           'titleSlug': movie['titleSlug'],\n                           'tmdbId': movie['tmdbId'],\n                           'path': path,\n                           'monitored': movie['monitored'],\n                           'images': images,\n                           'profileId': SyncServer_target_profile, \n                           'minimumAvailability': 'released'\n                           }\n\n                r = session.post('{0}/api/movie?apikey={1}'.format(SyncServer_url, SyncServer_key), data=json.dumps(payload))\n                if r.status_code == 200:\n                     searchid.append(int(r.json()['id']))\n                     logger.info('adding {0} to {1} server'.format(movie['title'], server))\n                else:\n                     logger.debug('Failed with error: {0}'.format(r.json()))\n            else:\n                logging.debug('{0} already in {1} library'.format(movie['title'], server))\n        else:\n            logging.debug('Skipping {0}, wanted profile: {1} found profile: {2}'.format(movie['title'],\n                                                                                        movie['profileId'],\n                                                                                        int(ConfigSectionMap(server)['profile'])\n                                                                                        ))\n\n\n\n    if len(searchid):\n        payload = {'name' : 'MoviesSearch', 'movieIds' : searchid}\n        session.post('{0}/api/command?apikey={1}'.format(SyncServer_url, SyncServer_key), data=json.dumps(payload))\n\n"
  },
  {
    "path": "arr_gui.py",
    "content": "import csv\nimport configparser\nimport urllib.parse\nimport requests\nimport tkinter as tk\nfrom tkinter import filedialog, messagebox\n\nCONFIG_PATH = \"./config.ini\"\n\n\ndef load_config():\n    config = configparser.ConfigParser()\n    config.read(CONFIG_PATH)\n    return config\n\n\ndef load_defaults():\n    config = load_config()\n    csv_path = \"\"\n    if config.has_section(\"gui\"):\n        csv_path = config.get(\"gui\", \"default_csv\", fallback=\"\")\n    return csv_path\n\n\ndef browse_file(entry):\n    path = filedialog.askopenfilename(filetypes=[(\"CSV files\", \"*.csv\"), (\"All files\", \"*.*\")])\n    if path:\n        entry.delete(0, tk.END)\n        entry.insert(0, path)\n\n\n# ----------------------- Radarr helpers ---------------------------------\n\ndef radarr_import(csv_path: str, cfg: configparser.ConfigParser) -> None:\n    baseurl = cfg[\"radarr\"][\"baseurl\"]\n    urlbase = cfg[\"radarr\"].get(\"urlbase\", \"\")\n    api_key = cfg[\"radarr\"][\"api_key\"]\n    root = cfg[\"radarr\"][\"rootfolderpath\"]\n    profile = cfg[\"radarr\"][\"qualityProfileId\"]\n    search = cfg.getboolean(\"radarr\", \"searchForMovie\", fallback=False)\n\n    headers = {\"Content-type\": \"application/json\", \"X-Api-Key\": api_key}\n    session = requests.Session()\n\n    with open(csv_path, encoding=\"utf-8\") as f:\n        reader = csv.DictReader(f)\n        for row in reader:\n            title = row.get(\"title\")\n            year = row.get(\"year\")\n            imdbid = row.get(\"imdbid\")\n            if imdbid:\n                url = f\"{baseurl}{urlbase}/api/v3/movie/lookup/imdb?imdbId={imdbid}\"\n            else:\n                term = urllib.parse.quote_plus(f\"{title} {year}\" if year else title)\n                url = f\"{baseurl}{urlbase}/api/v3/movie/lookup?term={term}\"\n            rsp = session.get(url, headers=headers)\n            if rsp.status_code != 200 or rsp.text in (\"\", \"[]\"):\n                messagebox.showwarning(\"Radarr\", f\"{title} not found\")\n                continue\n            data = rsp.json()\n            if isinstance(data, list):\n                data = data[0]\n            payload = {\n                \"title\": data.get(\"title\"),\n                \"tmdbId\": data.get(\"tmdbId\"),\n                \"year\": data.get(\"year\"),\n                \"titleSlug\": data.get(\"titleSlug\"),\n                \"qualityProfileId\": int(profile),\n                \"rootFolderPath\": root,\n                \"monitored\": True,\n                \"images\": data.get(\"images\", []),\n                \"addOptions\": {\"searchForMovie\": search},\n            }\n            add_url = f\"{baseurl}{urlbase}/api/v3/movie\"\n            session.post(add_url, headers=headers, json=payload)\n\n\ndef radarr_export(cfg: configparser.ConfigParser) -> None:\n    baseurl = cfg[\"radarr\"][\"baseurl\"]\n    urlbase = cfg[\"radarr\"].get(\"urlbase\", \"\")\n    api_key = cfg[\"radarr\"][\"api_key\"]\n    headers = {\"Content-type\": \"application/json\", \"X-Api-Key\": api_key}\n    url = f\"{baseurl}{urlbase}/api/v3/movie\"\n    rsp = requests.get(url, headers=headers)\n    rsp.raise_for_status()\n    data = rsp.json()\n    with open(\"radarr_backup.csv\", \"w\", newline=\"\", encoding=\"utf-8\") as f:\n        writer = csv.writer(f)\n        writer.writerow([\"title\", \"year\", \"imdbid\", \"tmdbId\"])\n        for d in data:\n            writer.writerow([d.get(\"title\"), d.get(\"year\"), d.get(\"imdbId\"), d.get(\"tmdbId\")])\n\n\n# ----------------------- Sonarr helpers ---------------------------------\n\ndef sonarr_import(csv_path: str, cfg: configparser.ConfigParser) -> None:\n    baseurl = cfg[\"sonarr\"][\"baseurl\"]\n    urlbase = cfg[\"sonarr\"].get(\"urlbase\", \"\")\n    api_key = cfg[\"sonarr\"][\"api_key\"]\n    root = cfg[\"sonarr\"][\"rootfolderpath\"]\n    profile = cfg[\"sonarr\"][\"qualityProfileId\"]\n    search = cfg.getboolean(\"sonarr\", \"searchForShow\", fallback=False)\n\n    headers = {\"Content-type\": \"application/json\", \"X-Api-Key\": api_key}\n    session = requests.Session()\n\n    with open(csv_path, encoding=\"utf-8\") as f:\n        reader = csv.DictReader(f)\n        for row in reader:\n            title = row.get(\"title\")\n            year = row.get(\"year\")\n            imdbid = row.get(\"imdbid\")\n            if imdbid:\n                url = f\"{baseurl}{urlbase}/api/v3/series/lookup?term=imdb:{imdbid}\"\n            else:\n                term = urllib.parse.quote_plus(f\"{title} {year}\" if year else title)\n                url = f\"{baseurl}{urlbase}/api/v3/series/lookup?term={term}\"\n            rsp = session.get(url, headers=headers)\n            if rsp.status_code != 200 or rsp.text in (\"\", \"[]\"):\n                messagebox.showwarning(\"Sonarr\", f\"{title} not found\")\n                continue\n            data = rsp.json()\n            if isinstance(data, list):\n                data = data[0]\n            payload = {\n                \"title\": data.get(\"title\"),\n                \"tvdbId\": data.get(\"tvdbId\"),\n                \"year\": data.get(\"year\"),\n                \"titleSlug\": data.get(\"titleSlug\"),\n                \"qualityProfileId\": int(profile),\n                \"rootFolderPath\": root,\n                \"monitored\": True,\n                \"seasonFolder\": True,\n                \"images\": data.get(\"images\", []),\n                \"seasons\": data.get(\"seasons\", []),\n                \"addOptions\": {\"searchForMissingEpisodes\": search},\n            }\n            add_url = f\"{baseurl}{urlbase}/api/v3/series\"\n            session.post(add_url, headers=headers, json=payload)\n\n\ndef sonarr_export(cfg: configparser.ConfigParser) -> None:\n    baseurl = cfg[\"sonarr\"][\"baseurl\"]\n    urlbase = cfg[\"sonarr\"].get(\"urlbase\", \"\")\n    api_key = cfg[\"sonarr\"][\"api_key\"]\n    headers = {\"Content-type\": \"application/json\", \"X-Api-Key\": api_key}\n    url = f\"{baseurl}{urlbase}/api/v3/series\"\n    rsp = requests.get(url, headers=headers)\n    rsp.raise_for_status()\n    data = rsp.json()\n    with open(\"sonarr_backup.csv\", \"w\", newline=\"\", encoding=\"utf-8\") as f:\n        writer = csv.writer(f)\n        writer.writerow([\"title\", \"year\", \"imdbid\"])\n        for d in data:\n            writer.writerow([d.get(\"title\"), d.get(\"year\"), d.get(\"imdbId\")])\n\n\n# ----------------------- Lidarr helpers ---------------------------------\n\ndef lidarr_import(csv_path: str, cfg: configparser.ConfigParser) -> None:\n    baseurl = cfg[\"lidarr\"][\"baseurl\"]\n    api_key = cfg[\"lidarr\"][\"api_key\"]\n    root = cfg[\"lidarr\"][\"rootfolderpath\"]\n\n    headers = {\"Content-type\": \"application/json\", \"X-Api-Key\": api_key}\n    session = requests.Session()\n\n    def lookup_artist(name: str) -> str | None:\n        url = f\"https://api.lidarr.audio/api/v0.4/search?type=artist&query=\\\"{urllib.parse.quote_plus(name)}\\\"\"\n        resp = session.get(url, headers=headers)\n        if resp.status_code == 200 and resp.text not in (\"\", \"[]\"):\n            data = resp.json()\n            if isinstance(data, list):\n                return data[0].get(\"id\")\n            return data.get(\"id\")\n        return None\n\n    with open(csv_path, encoding=\"utf-8\") as f:\n        reader = csv.DictReader(f)\n        for row in reader:\n            artist = row.get(\"artist\")\n            mbid = row.get(\"foreignArtistId\")\n            if not mbid:\n                mbid = lookup_artist(artist)\n            if not mbid:\n                messagebox.showwarning(\"Lidarr\", f\"{artist} not found\")\n                continue\n            payload = {\n                \"artistName\": artist,\n                \"foreignArtistId\": mbid,\n                \"QualityProfileId\": 1,\n                \"MetadataProfileId\": 1,\n                \"Path\": os.path.join(root, artist),\n                \"RootFolderPath\": root,\n                \"monitored\": True,\n                \"addOptions\": {\"searchForMissingAlbums\": False},\n            }\n            add_url = f\"{baseurl}/api/v1/artist\"\n            session.post(add_url, headers=headers, json=payload)\n\n\ndef lidarr_export(cfg: configparser.ConfigParser) -> None:\n    baseurl = cfg[\"lidarr\"][\"baseurl\"]\n    api_key = cfg[\"lidarr\"][\"api_key\"]\n    headers = {\"Content-type\": \"application/json\", \"X-Api-Key\": api_key}\n    url = f\"{baseurl}/api/v1/artist\"\n    rsp = requests.get(url, headers=headers)\n    rsp.raise_for_status()\n    data = rsp.json()\n    with open(\"lidarr_backup.csv\", \"w\", newline=\"\", encoding=\"utf-8\") as f:\n        writer = csv.writer(f)\n        writer.writerow([\"artist\", \"foreignArtistId\"])\n        for d in data:\n            writer.writerow([d.get(\"artistName\"), d.get(\"foreignArtistId\")])\n\n\n# ----------------------- GUI logic ---------------------------------\n\ndef run_action(service_var, action_var, csv_entry):\n    service = service_var.get()\n    action = action_var.get()\n    csv_path = csv_entry.get()\n\n    cfg = load_config()\n\n    if action == \"Import\" and not csv_path:\n        messagebox.showerror(\"Error\", \"Please select a CSV file for import\")\n        return\n\n    try:\n        if service == \"Radarr\" and action == \"Import\":\n            radarr_import(csv_path, cfg)\n        elif service == \"Radarr\" and action == \"Export\":\n            radarr_export(cfg)\n        elif service == \"Sonarr\" and action == \"Import\":\n            sonarr_import(csv_path, cfg)\n        elif service == \"Sonarr\" and action == \"Export\":\n            sonarr_export(cfg)\n        elif service == \"Lidarr\" and action == \"Import\":\n            lidarr_import(csv_path, cfg)\n        elif service == \"Lidarr\" and action == \"Export\":\n            lidarr_export(cfg)\n        else:\n            messagebox.showerror(\"Error\", \"Invalid selection\")\n            return\n        messagebox.showinfo(\"Success\", \"Operation completed\")\n    except Exception as exc:  # simplistic error handling\n        messagebox.showerror(\"Error\", str(exc))\n\n\ndef main():\n    root = tk.Tk()\n    root.title(\"ArrTools GUI\")\n\n    csv_default = load_defaults()\n\n    tk.Label(root, text=\"Service:\").grid(row=0, column=0, padx=5, pady=5, sticky=\"e\")\n    service_var = tk.StringVar(value=\"Radarr\")\n    tk.OptionMenu(root, service_var, \"Radarr\", \"Sonarr\", \"Lidarr\").grid(row=0, column=1, padx=5, pady=5)\n\n    tk.Label(root, text=\"Action:\").grid(row=1, column=0, padx=5, pady=5, sticky=\"e\")\n    action_var = tk.StringVar(value=\"Import\")\n    tk.OptionMenu(root, action_var, \"Import\", \"Export\").grid(row=1, column=1, padx=5, pady=5)\n\n    tk.Label(root, text=\"CSV File:\").grid(row=2, column=0, padx=5, pady=5, sticky=\"e\")\n    csv_entry = tk.Entry(root, width=40)\n    csv_entry.grid(row=2, column=1, padx=5, pady=5)\n    csv_entry.insert(0, csv_default)\n    tk.Button(root, text=\"Browse\", command=lambda: browse_file(csv_entry)).grid(row=2, column=2, padx=5, pady=5)\n\n    tk.Button(\n        root,\n        text=\"Run\",\n        command=lambda: run_action(service_var, action_var, csv_entry),\n    ).grid(row=3, column=0, columnspan=3, pady=10)\n\n    root.mainloop()\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "backup_lidarr_2csv.py",
    "content": "\"\"\"Export Lidarr artist information to a CSV file.\"\"\"\n\nimport argparse\nimport csv\nimport json\nimport sys\nimport re\nimport configparser\nfrom pathlib import Path\n\nimport requests\n\n\nif sys.version_info[0] < 3:\n    raise Exception(\"Must be using Python 3\")\n\n\ndef backup_lidarr(config_path: str, output_path: str) -> None:\n    \"\"\"Backup Lidarr artists to ``output_path`` using ``config_path``.\"\"\"\n\n    config = configparser.ConfigParser()\n    config.read(config_path)\n    baseurl = config['lidarr']['baseurl']\n    api_key = config['lidarr']['api_key']\n\n    headers = {\"Content-type\": \"application/json\", \"X-Api-Key\": api_key}\n    url = f\"{baseurl}/api/v1/artist\"\n\n    print(\"Downloading Data...\")\n    response = requests.get(url, headers=headers)\n    response.raise_for_status()\n    lidarr_data = response.json()\n\n    with open(output_path, \"w\", newline=\"\", encoding=\"utf-8\") as csvfile:\n        csvwriter = csv.writer(csvfile)\n        csvwriter.writerow([\"artist\", \"foreignArtistId\"])\n        for artist_info in lidarr_data:\n            artist = re.sub(r\"[^a-zA-Z0-9 ]\", \"\", artist_info[\"artistName\"])\n            csvwriter.writerow([artist, artist_info.get(\"foreignArtistId\")])\n\n\ndef main() -> None:\n    parser = argparse.ArgumentParser(description=\"Backup Lidarr artists to CSV\")\n    parser.add_argument(\n        \"-c\",\n        \"--config\",\n        default=\"./config.ini\",\n        help=\"Path to config.ini\",\n    )\n    parser.add_argument(\n        \"-o\",\n        \"--output\",\n        default=\"./lidarr_backup.csv\",\n        help=\"Output CSV file\",\n    )\n\n    args = parser.parse_args()\n\n    try:\n        backup_lidarr(args.config, args.output)\n        print(\"Done...\")\n    except Exception as exc:  # keep CLI simple\n        print(f\"Error: {exc}\")\n\n\nif __name__ == \"__main__\":\n    main()\n\n"
  },
  {
    "path": "backup_radarr_2csv.py",
    "content": "import requests, json, csv, sys, configparser\n\nif sys.version_info[0] < 3: raise Exception(\"Must be using Python 3\")\n\nconfig = configparser.ConfigParser()\nconfig.read('./config.ini')\nbaseurl = config['radarr']['baseurl']\napi_key = config['radarr']['api_key']\nurlbase = config['radarr']['urlbase']\n\nwith open('./radarr_backup.csv', 'w', encoding=\"utf-8\",  newline='' ) as csvfile:\n    csvwriter = csv.writer(csvfile, delimiter=',')\n    print(\"Downloading Data...\")\n    headers = {\"Content-type\": \"application/json\", \"X-Api-Key\": api_key }\n    url = f\"{baseurl}{urlbase}/api/v3/movie\"\n    rsp = requests.get(url , headers=headers)\n    csvwriter.writerow(['title','year','imdbid', 'tmdbId'])\n    if rsp.status_code == 200:\n        RadarrData = json.loads(rsp.text)\n        for d in RadarrData: csvwriter.writerow([d.get('title'),d.get('year'), d.get('imdbId'),d.get('tmdbId')])\n    else:\n        print(\"Failed to connect to Radar...\")\nprint(\"Done...\")"
  },
  {
    "path": "backup_readarr_2csv.py",
    "content": "import requests, json, csv, sys, configparser\n\nif sys.version_info[0] < 3: raise Exception(\"Must be using Python 3\")\n\nconfig = configparser.ConfigParser()\nconfig.read('./config.ini')\nbaseurl = config['readarr']['baseurl']\napi_key = config['readarr']['api_key']\n\nwith open('./readarr_backup.csv', 'w', newline='') as csvfile:\n    csvwriter = csv.writer(csvfile, delimiter=',')\n    print(\"Downloading Data...\")\n    headers = {\"Content-type\": \"application/json\", \"X-Api-Key\": api_key }\n    url = \"{}/api/v1/book\".format(baseurl)\n    rsp = requests.get(url , headers=headers)\n    csvwriter.writerow(['AuthorID','AuthorName','BookID','BookName'])\n    if rsp.status_code == 200:\n        readarrData = json.loads(rsp.text)\n        for d in readarrData: csvwriter.writerow([d['author']['foreignAuthorId'], d['author']['authorName'], d['foreignBookId'], d['title']])\n    else:\n        print(\"Failed to connect to readarr...\")\nprint(\"Done...\")"
  },
  {
    "path": "backup_sonarr_2csv.py",
    "content": "import requests, json, csv, sys, configparser\n\nif sys.version_info[0] < 3: raise Exception(\"Must be using Python 3\")\n\nconfig = configparser.ConfigParser()\nconfig.read('./config.ini')\nbaseurl = config['sonarr']['baseurl']\napi_key = config['sonarr']['api_key']\n\nwith open('./sonarr_backup.csv', 'w', newline='') as csvfile:\n    csvwriter = csv.writer(csvfile, delimiter=',')\n    print(\"Downloading Data...\")\n    headers = {\"Content-type\": \"application/json\", \"X-Api-Key\": api_key }\n    url = \"{}/api/v3/series\".format(baseurl)\n    rsp = requests.get(url , headers=headers)\n    csvwriter.writerow(['title','year','imdbid'])\n    if rsp.status_code == 200:\n        RadarrData = json.loads(rsp.text)\n        for d in RadarrData: csvwriter.writerow([d['title'],d['year'], d.get('imdbId')])\n    else:\n        print(\"Failed to connect to Radar...\")\nprint(\"Done...\")"
  },
  {
    "path": "config_example.ini",
    "content": "[radarr]\napi_key = \nbaseurl = \nurlbase = ; Include URL Base if you have it enabled\nrootfolderpath = \nsearchForMovie = \nqualityProfileId = \nomdbapi_key = ; sign up here for api key http://www.omdbapi.com/apikey.aspx\n\n[sonarr]\napi_key = \nbaseurl = \nurlbase = ; Include URL Base if you have it enabled\nrootfolderpath = \nsearchForShow = \nqualityProfileId = \nomdbapi_key = \ntvdb_api =  ; sign up here for a api key https://thetvdb.com/api-information\ntvdb_userkey = \ntvdb_username = \n\n[lidarr]\napi_key = \nbaseurl = \nrootfolderpath = \n\n; Standard Profile ID\n; 1 Any\n; 2 SD\n; 3 HD-720p\n; 4 HD-1080p\n; 5 Ultra-HD\n; 6 HD - 720p/1080p\n\n[gui]\n# Default CSV file path for the GUI\ndefault_csv = \n\n"
  },
  {
    "path": "export_trakt.py",
    "content": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#\n# (c) Copyright 2016-2018 xbgmsharp <xbgmsharp@gmail.com>\n#\n# Purpose:\n# Export Movies or TVShows IDs from Trakt.tv\n#\n# Requirement on Ubuntu/Debian Linux system\n# apt-get install python-dateutil python-simplejson python-requests python-openssl jq\n#\n# Requirement on Windows on Python 2.7\n# C:\\Python2.7\\Scripts\\easy_install-2.7.exe simplejson requests\n#\n\nimport sys, os\n# https://urllib3.readthedocs.org/en/latest/security.html#disabling-warnings\n# http://quabr.com/27981545/surpress-insecurerequestwarning-unverified-https-request-is-being-made-in-pytho\n# http://docs.python-requests.org/en/v2.4.3/user/advanced/#proxies\ntry:\n        import simplejson as json\n        import requests\n        requests.packages.urllib3.disable_warnings()\n        import csv\nexcept:\n        sys.exit(\"Please use your favorite mehtod to install the following module requests and simplejson to use this script\")\n\nimport argparse\nimport ConfigParser\nimport datetime\nimport collections\nimport pprint\n\npp = pprint.PrettyPrinter(indent=4)\n\ndesc=\"\"\"This program export Movies or TVShows IDs from Trakt.tv list.\"\"\"\n\nepilog=\"\"\"Read a list from Trakt API.\nExport them into a CSV file.\"\"\"\n\n_trakt = {\n        'client_id'     :       '', # Auth details for trakt API\n        'client_secret' :       '', # Auth details for trakt API\n        'oauth_token'   :       '', # Auth details for trakt API\n        'baseurl'       :       'https://api.trakt.tv' # Sandbox environment https://api-staging.trakt.tv\n}\n\n_headers = {\n        'Accept'            : 'application/json',   # required per API\n        'Content-Type'      : 'application/json',   # required per API\n        'User-Agent'        : 'Tratk importer',     # User-agent\n        'Connection'        : 'Keep-Alive',         # Thanks to urllib3, keep-alive is 100% automatic within a session!\n        'trakt-api-version' : '2',                  # required per API\n        'trakt-api-key'     : '',                   # required per API\n        'Authorization'     : '',                   # required per API\n}\n\n_proxy = {\n        'proxy' : False,                # True or False, trigger proxy use\n        'host'  : 'https://127.0.0.1',  # Host/IP of the proxy\n        'port'  : '3128'                # Port of the proxy\n}\n\n_proxyDict = {\n        \"http\" : _proxy['host']+':'+_proxy['port'],\n        \"https\" : _proxy['host']+':'+_proxy['port']\n}\n\nresponse_arr = []\n\ndef read_config(options):\n        \"\"\"\n        Read config file and if provided overwrite default values\n        If no config file exist, create one with default values\n        \"\"\"\n        global work_dir\n        work_dir = ''\n        if getattr(sys, 'frozen', False):\n                work_dir = os.path.dirname(sys.executable)\n        elif __file__:\n                work_dir = os.path.dirname(__file__)\n        _configfile = os.path.join(work_dir, options.config)\n        if os.path.exists(options.config):\n                _configfile = options.config\n        if options.verbose:\n                print \"Config file: {0}\".format(_configfile)\n        if os.path.exists(_configfile):\n                try:\n                        config = ConfigParser.SafeConfigParser()\n                        config.read(_configfile)\n                        if config.has_option('TRAKT','CLIENT_ID') and len(config.get('TRAKT','CLIENT_ID')) != 0:\n                                _trakt['client_id'] = config.get('TRAKT','CLIENT_ID')\n                        else:\n                                print 'Error, you must specify a trakt.tv CLIENT_ID'\n                                sys.exit(1)\n                        if config.has_option('TRAKT','CLIENT_SECRET') and len(config.get('TRAKT','CLIENT_SECRET')) != 0:\n                                _trakt['client_secret'] = config.get('TRAKT','CLIENT_SECRET')\n                        else:\n                                print 'Error, you must specify a trakt.tv CLIENT_SECRET'\n                                sys.exit(1)\n                        if config.has_option('TRAKT','OAUTH_TOKEN') and len(config.get('TRAKT','OAUTH_TOKEN')) != 0:\n                                _trakt['oauth_token'] = config.get('TRAKT','OAUTH_TOKEN')\n                        else:\n                                print 'Warning, authentification is required'\n                        if config.has_option('TRAKT','BASEURL'):\n                                _trakt['baseurl'] = config.get('TRAKT','BASEURL')\n                        if config.has_option('SETTINGS','PROXY'):\n                                _proxy['proxy'] = config.getboolean('SETTINGS','PROXY')\n                        if _proxy['proxy'] and config.has_option('SETTINGS','PROXY_HOST') and config.has_option('SETTINGS','PROXY_PORT'):\n                                _proxy['host'] = config.get('SETTINGS','PROXY_HOST')\n                                _proxy['port'] = config.get('SETTINGS','PROXY_PORT')\n                                _proxyDict['http'] = _proxy['host']+':'+_proxy['port']\n                                _proxyDict['https'] = _proxy['host']+':'+_proxy['port']\n                except:\n                        print \"Error reading configuration file {0}\".format(_configfile)\n                        sys.exit(1)\n        else:\n                try:\n                        print '%s file was not found!' % _configfile\n                        config = ConfigParser.RawConfigParser()\n                        config.add_section('TRAKT')\n                        config.set('TRAKT', 'CLIENT_ID', '')\n                        config.set('TRAKT', 'CLIENT_SECRET', '')\n                        config.set('TRAKT', 'OAUTH_TOKEN', '')\n                        config.set('TRAKT', 'BASEURL', 'https://api.trakt.tv')\n                        config.add_section('SETTINGS')\n                        config.set('SETTINGS', 'PROXY', False)\n                        config.set('SETTINGS', 'PROXY_HOST', 'https://127.0.0.1')\n                        config.set('SETTINGS', 'PROXY_PORT', '3128')\n                        with open(_configfile, 'wb') as configfile:\n                                config.write(configfile)\n                                print \"Default settings wrote to file {0}\".format(_configfile)\n                except:\n                        print \"Error writing configuration file {0}\".format(_configfile)\n                sys.exit(1)\n\ndef write_csv(options, results):\n        \"\"\"Write list output into a CSV file format\"\"\"\n        if options.verbose:\n                print \"CSV output file: {0}\".format(options.output)\n        # Write result CSV\n        with open(options.output, 'wb') as fp:\n                keys = {}\n                for i in results:\n                    for k in i.keys():\n                        keys[k] = 1\n                mycsv = csv.DictWriter(fp, fieldnames=keys.keys(), quoting=csv.QUOTE_ALL)\n                mycsv.writeheader()\n                for row in results:\n                        mycsv.writerow(row)\n        fp.close()\n\ndef api_auth(options):\n        \"\"\"API call for authentification OAUTH\"\"\"\n        print(\"Open the link in a browser and paste the pincode when prompted\")\n        print(\"https://trakt.tv/oauth/authorize?response_type=code&\"\n              \"client_id={0}&redirect_uri=urn:ietf:wg:oauth:2.0:oob\".format(\n                  _trakt[\"client_id\"]))\n        pincode = str(raw_input('Input PIN:'))\n        url = _trakt['baseurl'] + '/oauth/token'\n        values = {\n            \"code\": pincode,\n            \"client_id\": _trakt[\"client_id\"],\n            \"client_secret\": _trakt[\"client_secret\"],\n            \"redirect_uri\": \"urn:ietf:wg:oauth:2.0:oob\",\n            \"grant_type\": \"authorization_code\"\n        }\n\n        request = requests.post(url, data=values)\n        response = request.json()\n        _headers['Authorization'] = 'Bearer ' + response[\"access_token\"]\n        _headers['trakt-api-key'] = _trakt['client_id']\n        print 'Save as \"oauth_token\" in file {0}: {1}'.format(options.config, response[\"access_token\"])\n\ndef api_get_list(options, page):\n        \"\"\"API call for Sync / Get list by type\"\"\"\n        url = _trakt['baseurl'] + '/sync/{list}/{type}?page={page}&limit={limit}'.format(\n                            list=options.list, type=options.type, page=page, limit=1000)\n        if options.verbose:\n            print(url)\n        if _proxy['proxy']:\n            r = requests.get(url, headers=_headers, proxies=_proxyDict, timeout=(10, 60))\n        else:\n            r = requests.get(url, headers=_headers, timeout=(5, 60))\n        #pp.pprint(r.headers)\n        if r.status_code != 200:\n            print \"Error fetching Get {list}: {status} [{text}]\".format(\n                    list=options.list, status=r.status_code, text=r.text)\n            return None\n        else:\n            global response_arr\n            response_arr += json.loads(r.text)\n        if 'X-Pagination-Page-Count'in r.headers and r.headers['X-Pagination-Page-Count']:\n            print \"Fetched page {page} of {PageCount} pages for {list} list\".format(\n                    page=page, PageCount=r.headers['X-Pagination-Page-Count'], list=options.list)\n            if page != int(r.headers['X-Pagination-Page-Count']):\n                api_get_list(options, page+1)\n\n        return response_arr\n\ndef api_get_userlists(options, page):\n        \"\"\"API call for Sync / Get list by type\"\"\"\n        url = _trakt['baseurl'] + '/users/{user}/lists'.format(\n                            user=options.userlist, page=page, limit=1000)\n        #url = _trakt['baseurl'] + '/users/{user}/lists/{list_id}?page={page}&limit={limit}'.format(\n        #                    list=options.list, type=options.type, page=page, limit=1000)\n        if options.verbose:\n            print(url)\n        if _proxy['proxy']:\n            r = requests.get(url, headers=_headers, proxies=_proxyDict, timeout=(10, 60))\n        else:\n            r = requests.get(url, headers=_headers, timeout=(5, 60))\n        #pp.pprint(r.headers)\n        if r.status_code != 200:\n            print \"Error fetching Get {list}: {status} [{text}]\".format(\n                    list=options.list, status=r.status_code, text=r.text)\n            return None\n        else:\n            global response_arr\n            response_arr += json.loads(r.text)\n        if 'X-Pagination-Page-Count'in r.headers and r.headers['X-Pagination-Page-Count']:\n            print \"Fetched page {page} of {PageCount} pages for {list} list\".format(\n                    page=page, PageCount=r.headers['X-Pagination-Page-Count'], list=options.list)\n            if page != int(r.headers['X-Pagination-Page-Count']):\n                api_get_list(options, page+1)\n\n        return response_arr\n\ndef api_get_userlist(options, page):\n        \"\"\"API call for Sync / Get list by type\"\"\"\n        url = _trakt['baseurl'] + '/users/{user}/lists/{list_id}/items/{type}?page={page}&limit={limit}'.format(\n                            user=options.userlist, list_id=options.listid, type=options.type, page=page, limit=1000)\n        if options.verbose:\n            print(url)\n        if _proxy['proxy']:\n            r = requests.get(url, headers=_headers, proxies=_proxyDict, timeout=(10, 60))\n        else:\n            r = requests.get(url, headers=_headers, timeout=(5, 60))\n        #pp.pprint(r.headers)\n        if r.status_code != 200:\n            print \"Error fetching Get {list}: {status} [{text}]\".format(\n                    list=options.list, status=r.status_code, text=r.text)\n            return None\n        else:\n            global response_arr\n            response_arr += json.loads(r.text)\n        if 'X-Pagination-Page-Count'in r.headers and r.headers['X-Pagination-Page-Count']:\n            print \"Fetched page {page} of {PageCount} pages for {list} list\".format(\n                    page=page, PageCount=r.headers['X-Pagination-Page-Count'], list=options.list)\n            if page != int(r.headers['X-Pagination-Page-Count']):\n                api_get_userlist(options, page+1)\n\n        return response_arr\n\ndef api_remove_from_list(options, remove_data, is_id=False):\n        \"\"\"API call for Sync / Remove from list\"\"\"\n        url = _trakt['baseurl'] + '/sync/{list}/remove'.format(list=options.list)\n        if options.type == 'episodes':\n            values = { 'shows' : remove_data }\n        elif not is_id:\n            values = { options.type : remove_data }\n        else:\n            values = { 'ids' : remove_data }\n        json_data = json.dumps(values)\n        if options.verbose:\n            print(url)\n            pp.pprint(json_data)\n        if _proxy['proxy']:\n            r = requests.post(url, data=json_data, headers=_headers, proxies=_proxyDict, timeout=(10, 60))\n        else:\n            r = requests.post(url, data=json_data, headers=_headers, timeout=(5, 60))\n        if r.status_code != 200:\n            print \"Error removing items from {list}: {status} [{text}]\".format(\n                    list=options.list, status=r.status_code, text=r.text)\n            return None\n        else:\n            return json.loads(r.text)\n\ndef main():\n        \"\"\"\n        Main program loop\n        * Read configuration file and validate\n        * Authenticate if require\n        * Export data from Trakt.tv\n        * Cleanup list from Trakt.tv\n        * Write to CSV\n        \"\"\"\n        ## Parse inputs if any\n        parser = argparse.ArgumentParser(version='%(prog)s 0.3', description=desc, epilog=epilog)\n        parser.add_argument('-c', '--config',\n                      help='allow to overwrite default config filename, default %(default)s',\n                      action='store', type=str, dest='config', default='tconfig.ini')\n        parser.add_argument('-o', '--output',\n                      help='allow to overwrite default output filename, default %(default)s',\n                      nargs='?', type=str, const='export.csv', default=None)\n        parser.add_argument('-t', '--type',\n                      help='allow to overwrite type, default %(default)s',\n                      choices=['movies', 'shows', 'episodes'], dest='type', default='movies')\n        parser.add_argument('-l', '--list',\n                      help='allow to overwrite default list, default %(default)s',\n                      choices=['watchlist', 'collection', 'history'], dest='list', default='history')\n        parser.add_argument('-u', '--userlist',\n                      help='allow to export a user custom list, default %(default)s',\n                      dest='userlist', default=None)\n        parser.add_argument('-C', '--clean',\n                      help='empty list after export, default %(default)s',\n                      default=False, action='store_true', dest='clean')\n        parser.add_argument('-D', '--duplicate',\n                      help='remove duplicate from list after export, default %(default)s',\n                      default=False, action='store_true', dest='dup')\n        #parser.add_argument('-d', '--dryrun',\n        #              help='do not update the account, default %(default)s',\n        #              default=True, action='store_true', dest='dryrun')\n        parser.add_argument('-V', '--verbose',\n                      help='print additional verbose information, default %(default)s',\n                      default=True, action='store_true', dest='verbose')\n        options = parser.parse_args()\n\n        ## Display debug information\n        if options.verbose:\n            print \"Options: %s\" % options\n\n        if options.type == 'episodes' and options.list == \"collection\":\n            print \"Error, you can only fetch {0} from the history or watchlist list\".format(options.type)\n            sys.exit(1)\n\n        if options.userlist:\n            options.list = options.userlist\n\n        if not options.output:\n            options.output = 'export_{type}_{list}.csv'.format(type=options.type, list=options.list)\n\n        ## Read configuration and validate\n        read_config(options)\n\n        ## Display oauth token if exist, otherwise authenticate to get one\n        if _trakt['oauth_token']:\n            _headers['Authorization'] = 'Bearer ' + _trakt['oauth_token']\n            _headers['trakt-api-key'] = _trakt['client_id']\n        else:\n            api_auth(options)\n\n        ## Display debug information\n        if options.verbose:\n            print \"trakt: {}\".format(_trakt)\n            print \"Authorization header: {}\".format(_headers['Authorization'])\n\n        ## Get lits from Trakt user\n        export_data = []\n        if options.userlist:\n            export_data = api_get_userlists(options, 1)\n            if export_data:\n                print \"Found {0} user list\".format(len(export_data))\n                #pp.pprint(export_data)\n                for data in export_data:\n                    print \"Found list id '{id}' name '{name}' with {items} items own by {own}\".format(\n                            name=data['name'], id=data['ids']['trakt'], items=data['item_count'], own=data['user']['username'])\n                print(\"Input the custom list id to export\")\n                options.listid = str(raw_input('Input:'))\n                global response_arr ## Cleanup global....\n                response_arr = []\n                export_data = api_get_userlist(options, 1)\n                #pp.pprint(export_data)\n                if export_data:\n                    print \"Found {0} Item-Count\".format(len(export_data))\n            else:\n                print \"Error, no item return for {type} from the user list {list}\".format(\n                    type=options.type, list=options.userlist)\n                sys.exit(1)\n\n        ## Get data from Trakt\n        if not export_data:\n            export_data = api_get_list(options, 1)\n            if export_data:\n                print \"Found {0} Item-Count\".format(len(export_data))\n            else:\n                print \"Error, no item return for {type} from the {list} list\".format(\n                    type=options.type, list=options.list)\n                sys.exit(1)\n\n        if options.list == 'history':\n            options.time = 'watched_at'\n        elif options.list == 'watchlist':\n            options.time = 'listed_at'\n        elif options.list == 'collection':\n            options.time = 'collected_at'\n        elif option.userlist != None:\n            options.time = 'listed_at'\n\n        export_csv = []\n        find_dupids = []\n        for data in export_data:\n           #pp.pprint(data)\n           if options.type[:-1] != \"episode\" and 'imdb' in data[options.type[:-1]]['ids']:\n                find_dupids.append(data[options.type[:-1]]['ids']['imdb'])\n                export_csv.append({ 'imdb' : data[options.type[:-1]]['ids']['imdb'],\n                                    'trakt_id' : data[options.type[:-1]]['ids']['trakt'],\n                                    options.time : data[options.time],\n                                    'title' : data[options.type[:-1]]['title'].encode('utf-8')})\n           elif 'tmdb' in data[options.type[:-1]]['ids']:\n                find_dupids.append(data[options.type[:-1]]['ids']['tmdb'])\n                if not data['episode']['title']: data['episode']['title'] = \"no episode title\"\n                export_csv.append({ 'tmdb' : data[options.type[:-1]]['ids']['tmdb'],\n                                    'trakt_id' : data[options.type[:-1]]['ids']['trakt'],\n                                    options.time : data[options.time],\n                                    'season' : data[options.type[:-1]]['season'],\n                                    'episode' : data[options.type[:-1]]['number'],\n                                    'episode_title' : data['episode']['title'].encode('utf-8'),\n                                    'show_title' : data['show']['title'].encode('utf-8')})\n        #print export_csv\n        ## Write export data into CSV file\n        write_csv(options, export_csv)\n\n        ## Empty list after export\n        if options.clean:\n            cleanup_results = {'sentids' : 0, 'deleted' : 0, 'not_found' : 0}\n            to_remove = []\n            for data in export_data:\n                # TODO add filter\n                #if data[options.time] == \"2012-01-01T00:00:00.000Z\":\n                to_remove.append({'ids': data[options.type[:-1]]['ids']})\n                if len(to_remove) >= 10: # Remove by batch of 10\n                    cleanup_results['sentids'] += len(to_remove)\n                    result = api_remove_from_list(options, to_remove)\n                    if result:\n                        print \"Result: {0}\".format(result)\n                        if 'deleted' in result and result['deleted']:\n                            cleanup_results['deleted'] += result['deleted'][options.type]\n                        if 'not_found' in result and result['not_found']:\n                            cleanup_results['not_found'] += len(result['not_found'][options.type])\n                    to_remove = []\n            # Remove the rest\n            if len(to_remove) > 0:\n                #print pp.pprint(data)\n                cleanup_results['sentids'] += len(to_remove)\n                result = api_remove_from_list(options, to_remove)\n                if result:\n                    print \"Result: {0}\".format(result)\n                    if 'deleted' in result and result['deleted']:\n                        cleanup_results['deleted'] += result['deleted'][options.type]\n                    if 'not_found' in result and result['not_found']:\n                        cleanup_results['not_found'] += len(result['not_found'][options.type])\n            print \"Overall cleanup {sent} {type}, results deleted:{deleted}, not_found:{not_found}\".format(\n                sent=cleanup_results['sentids'], type=options.type, \n                deleted=cleanup_results['deleted'], not_found=cleanup_results['not_found'])\n\n        ## Found duplicate and remove duplicate\n        dup_ids = [item for item, count in collections.Counter(find_dupids).items() if count > 1]\n        print \"Found {dups} duplicate out of {total} {entry}\".format(\n                    entry=options.type, dups=len(dup_ids), total=len(find_dupids))\n        if options.dup:\n            if len(dup_ids) > 0:\n                print dup_ids\n            dup_results = {'sentids' : 0, 'deleted' : 0, 'not_found' : 0}\n            to_remove = []\n            for dupid in find_dupids:\n                count = 0\n                for data in export_data:\n                    if data[options.type[:-1]]['ids']['imdb'] == dupid:\n                        #print \"{0} {1}\".format(dupid, data['id'])\n                        count += 1\n                        if count > 1:\n                            print \"Removing {0} {1}\".format(dupid, data['id'])\n                            to_remove.append(data['id'])\n                            dup_results['sentids'] += len(to_remove)\n                            result = api_remove_from_list(options, to_remove, is_id=True)\n                            if len(to_remove) >= 10: # Remove by batch of 10\n                                if result:\n                                    print \"Result: {0}\".format(result)\n                                    if 'deleted' in result and result['deleted']:\n                                        dup_results['deleted'] += result['deleted'][options.type]\n                                    if 'not_found' in result and result['not_found']:\n                                        dup_results['not_found'] += len(result['not_found'][options.type])\n                                    to_remove = []\n            ## Remove the rest\n            if len(to_remove) > 0:\n                dup_results['sentids'] += len(to_remove)\n                result = api_remove_from_list(options, to_remove, is_id=True)\n                if result:\n                    print \"Result: {0}\".format(result)\n                    if 'deleted' in result and result['deleted']:\n                        dup_results['deleted'] += result['deleted'][options.type]\n                    if 'not_found' in result and result['not_found']:\n                        dup_results['not_found'] += len(result['not_found'][options.type])\n                    to_remove = []\n            print \"Overall {dup} duplicate {sent} {type}, results deleted:{deleted}, not_found:{not_found}\".format(\n                dup=len(dup_ids), sent=dup_results['sentids'], type=options.type, \n                deleted=dup_results['deleted'], not_found=dup_results['not_found'])\n\nif __name__ == '__main__':\n        main()\n"
  },
  {
    "path": "get_imdbid.py",
    "content": "import os, time, requests, json, sys, re, configparser\r\n\r\nconfig = configparser.ConfigParser()\r\nconfig.read('./config.ini')\r\nomdbapi_key = config['sonarr']['omdbapi_key']\r\nadd_count = 0\r\nfailed_count = 0\r\nres = 0\r\n\r\ndef main():\r\n    global add_count \r\n    global failed_count\r\n    global res\r\n    if len(sys.argv)<2: print (\"No list Specified... Bye!!\"); sys.exit(-1)\r\n    f=open(sys.argv[1], \"r\")\r\n    if f.mode == 'r': f1 = f.readlines()\r\n    print('\\033c')\r\n    res = input(\"This list contains S) TV Shows or M) Movies [S/M]? : \")\r\n    if res == \"S\" or \"s\": res = 'series'\r\n    elif res == \"M\" or \"m\": res = 'movie'\r\n    else: print(\"Invalid Entry\"); sys.exit(0)\r\n    fo = open(\"{}.csv\".format(res), \"a\")\r\n    fo.write(\"title,year,imdbid\\n\")\r\n    for x in f1:\r\n        r = requests.get(\"https://www.omdbapi.com/?t={}&type={}&apikey={}\".format(x.rstrip(),res,omdbapi_key))\r\n        if r.status_code == 200:\r\n            item = json.loads(r.text)\r\n            if item.get('Response') == \"False\": \r\n                failed_count +=1\r\n                ff = open(\"{}_failed\".format(res), \"a\")\r\n                ff.write(\"{} Failed to be Matched\\n\".format(x.rstrip()))\r\n                ff.close()\r\n                continue\r\n            else:\r\n                year = item.get('Year')\r\n                imdbid = item.get('imdbID')\r\n                title = item.get('Title')\r\n                title = re.sub('[(]\\d{4}[)]','',title)\r\n                fo.write(\"{},{},{}\\n\".format(title.rstrip(),year[:4],imdbid))\r\n                #print (\"{},{},{}\".format(title.rstrip(),year[:4],imdbid))\r\n                print('\\033c')\r\n                print(\"Matching {} {}.\".format(title,year[:4]))\r\n                add_count +=1\r\n    print(\"\\u001b[32mMatched {} of {}, {} Failed to match. {} file was created.\\u001b[0m\".format(add_count,len(f1),failed_count,res))\r\n    fo.close()\r\n\r\nif __name__ == \"__main__\":\r\n    main()\r\n\r\n"
  },
  {
    "path": "lidarr_add_from_list.py",
    "content": "\"\"\"Add artists from a CSV list into Lidarr.\"\"\"\n\nimport csv\nimport json\nimport logging\nimport logging.handlers\nimport os\nimport sys\n\nimport configparser\nimport requests\nfrom requests.adapters import HTTPAdapter, Retry\nfrom colorlog import ColoredFormatter\n\nLidarrData: list = []\n\nartist_added_count = 0\nartist_exist_count = 0\n\n# Config ###############################################################################################################\n\nconfig = configparser.ConfigParser()\nconfig.read('./config.ini')\nbaseurl = config['lidarr']['baseurl']\n# urlbase = config['lidarr']['urlbase']\napi_key = config['lidarr']['api_key']\nrootfolderpath = config['lidarr']['rootfolderpath']\n\n# Logging ######################################################################\n\nlogging.getLogger().setLevel(logging.NOTSET)\n\nformatter = ColoredFormatter(\n    \"%(log_color)s[%(levelname)s]%(reset)s %(white)s%(message)s\",\n    datefmt=None,\n    reset=True,\n    log_colors={\n        'DEBUG': 'cyan',\n        'INFO': 'green',\n        'WARNING': 'yellow',\n        'ERROR': 'red',\n        'CRITICAL': 'red,bg_white',\n    },\n    secondary_log_colors={},\n    style=\"%\",\n)\n\nconsole = logging.StreamHandler()\nconsole.setLevel(logging.INFO)\nconsole.setFormatter(formatter)\nlogging.getLogger().addHandler(console)\n\nif not os.path.exists(\"./logs\"):\n    os.mkdir(\"./logs\")\nlog_file_name = \"./logs/lafl.log\"\nfilelogger = logging.handlers.RotatingFileHandler(filename=log_file_name)\nfilelogger.setLevel(logging.DEBUG)\nlog_formatter = logging.Formatter(\"%(asctime)s [%(levelname)-5.5s]  %(message)s\")\nfilelogger.setFormatter(log_formatter)\nlogging.getLogger().addHandler(filelogger)\n\nlog = logging.getLogger(\"app.\" + __name__)\n\n########################################################################################################################\n\ndef create_session() -> requests.Session:\n    \"\"\"Return a session with retry and backoff configured.\"\"\"\n\n    retries = Retry(total=5, backoff_factor=1, status_forcelist=[500, 502, 503, 504], allowed_methods=[\"GET\", \"POST\"])\n    session = requests.Session()\n    adapter = HTTPAdapter(max_retries=retries)\n    session.mount(\"https://\", adapter)\n    session.mount(\"http://\", adapter)\n    return session\n\ndef add_artist(artist_name: str, foreign_artist_id: str, session: requests.Session) -> None:\n    \"\"\"Add an artist to Lidarr if it does not already exist.\"\"\"\n\n    \n    payload = {\n        \"artistName\": artist_name,\n        \"foreignArtistId\": foreign_artist_id,\n        \"QualityProfileId\": 1,\n        \"MetadataProfileId\": 1,\n        \"Path\": os.path.join(rootfolderpath, artist_name),\n        \"albumFolder\": True,\n        \"RootFolderPath\": rootfolderpath,\n        \"monitored\": True,\n        \"addOptions\": {\"searchForMissingAlbums\": False},\n    }\n    url = f\"{baseurl}/api/v1/artist\"\n    headers = {\"Content-type\": \"application/json\", \"X-Api-Key\": api_key}\n    try:\n        rsp = session.post(url, headers=headers, json=payload, timeout=10)\n    except requests.RequestException as exc:\n        log.error(f\"Error adding {artist_name}: {exc}\")\n        return\n    if rsp.status_code == 201:\n        artist_added_count += 1\n        log.info(f\"{artist_name} added to Lidarr :)\")\n    elif rsp.status_code == 400:\n        artist_exist_count += 1\n        log.info(f\"{artist_name} already exists in Lidarr.\")\n    else:\n        log.error(f\"{artist_name} not found. Status: {rsp.status_code}\")\n\ndef get_artist_id(artist: str, session: requests.Session) -> str | None:\n    \"\"\"Query Lidarr's search API to resolve an artist's MBID.\"\"\"\n\n    url = f\"https://api.lidarr.audio/api/v0.4/search?type=artist&query=\\\"{artist}\\\"\"\n    headers = {\"Content-type\": \"application/json\", \"X-Api-Key\": api_key}\n    try:\n        rsp = session.get(url, headers=headers, timeout=10)\n    except requests.RequestException as exc:\n        log.error(f\"Error searching for {artist}: {exc}\")\n        return None\n\n    if rsp.text == \"[]\":\n        log.error(f\"Sorry. We couldn't find {artist}\")\n        with open(\"not_found.txt\", \"a+\", encoding=\"utf-8\") as fo:\n            fo.write(f\"{artist}\\n\")\n        return None\n\n    data = json.loads(rsp.text)\n    if rsp.status_code == 200:\n        try:\n            return data[0][\"id\"]\n        except Exception:\n            return data.get(\"id\")\n    return None\n\n\ndef lookup_musicbrainz(artist: str, session: requests.Session) -> str | None:\n    \"\"\"Query MusicBrainz directly for the artist MBID.\"\"\"\n\n    url = \"https://musicbrainz.org/ws/2/artist/\"\n    params = {\"query\": f'artist:\"{artist}\"', \"fmt\": \"json\"}\n    headers = {\n        \"User-Agent\": \"ArrTools (https://github.com/sirk123au/ArrTools)\",\n    }\n\n    try:\n        rsp = session.get(url, headers=headers, params=params, timeout=10)\n    except requests.RequestException as exc:\n        log.error(f\"Error searching MusicBrainz for {artist}: {exc}\")\n        return None\n\n    if rsp.status_code != 200:\n        log.error(\n            f\"MusicBrainz search failed for {artist}. Status: {rsp.status_code}\"\n        )\n        return None\n\n    data = rsp.json()\n    artists = data.get(\"artists\")\n    if not artists:\n        log.error(f\"Sorry. We couldn't find {artist} on MusicBrainz\")\n        with open(\"not_found.txt\", \"a+\", encoding=\"utf-8\") as fo:\n            fo.write(f\"{artist}\\n\")\n        return None\n\n    return artists[0].get(\"id\")\n\ndef main() -> None:\n    \"\"\"Entry point for the script.\"\"\"\n\n    global LidarrData, artist_exist_count, artist_added_count\n\n    if sys.version_info[0] < 3:\n        log.error(\"Must be using Python 3\")\n        sys.exit(-1)\n    if len(sys.argv) < 2:\n        log.error(\"No list specified... bye!!\")\n        sys.exit(-1)\n    if not os.path.exists(sys.argv[1]):\n        log.error(f\"{sys.argv[1]} does not exist\")\n        sys.exit(-1)\n\n    session = create_session()\n\n    log.info(\"Downloading Lidarr data...\")\n    headers = {\"Content-type\": \"application/json\", \"X-Api-Key\": api_key}\n    url = f\"{baseurl}/api/v1/artist\"\n    try:\n        rsp = session.get(url, headers=headers, timeout=10)\n    except requests.RequestException as exc:\n        log.error(f\"Error connecting to Lidarr: {exc}\")\n        sys.exit(-1)\n    if rsp.status_code == 200:\n        LidarrData = json.loads(rsp.text)\n    elif rsp.status_code == 401:\n        log.error(\"Failed to connect to Lidarr - unauthorized. Check API key in config.\")\n        sys.exit(-1)\n    else:\n        log.error(f\"URL -> {url} Status Code -> {rsp.status_code}\")\n        log.error(\"Failed to connect to Lidarr...\")\n        sys.exit(-1)\n\n    with open(sys.argv[1], encoding=\"utf-8\") as csvfile:\n        rows = list(csv.DictReader(csvfile))\n    total_count = len(rows)\n    if total_count == 0:\n        log.error(\"No artists found in file... bye!!\")\n        sys.exit(0)\n    if rows and \"artist\" not in rows[0]:\n        log.error(\"Invalid CSV file - header must contain artist and foreignArtistId\")\n        sys.exit(-1)\n    log.info(f\"Found {total_count} artists in {sys.argv[1]} :)\")\n\n    for row in rows:\n        artist = row.get(\"artist\")\n        foreign_artist_id = row.get(\"foreignArtistId\")\n        if not artist:\n            continue\n        if not foreign_artist_id:\n            foreign_artist_id = get_artist_id(artist, session)\n        if not foreign_artist_id:\n            foreign_artist_id = lookup_musicbrainz(artist, session)\n        if not foreign_artist_id:\n            continue\n        try:\n            existing_ids = [artist.get(\"foreignArtistId\") for artist in LidarrData]\n            if foreign_artist_id in existing_ids:\n                artist_exist_count += 1\n                log.info(f\"{artist} already exists in Lidarr Data.\")\n            else:\n                add_artist(artist, foreign_artist_id, session)\n        except Exception as err:\n            log.error(err)\n            sys.exit(-1)\n\n    log.info(\n        f\"Added {artist_added_count} of {total_count} artists, {artist_exist_count} already exist\"\n    )\n\nif __name__ == \"__main__\":\n    main()"
  },
  {
    "path": "radarr_add_from_list.py",
    "content": "import configparser\nimport csv\nimport json\nimport logging.handlers\nimport os\nimport requests\nimport sys\nimport urllib.parse\n\nfrom colorlog import ColoredFormatter\n\nmovie_added_count = 0\nmovie_exist_count = 0\n\n\n\n# Config ###############################################################################################################\n\nconfig = configparser.ConfigParser()\nconfig.read('./config.ini')\nbaseurl = config['radarr']['baseurl']\nurlbase = config['radarr']['urlbase']\napi_key = config['radarr']['api_key']\nrootfolderpath = config['radarr']['rootfolderpath']\nsearchForMovie = config['radarr']['searchForMovie']\nif searchForMovie == \"1\" or searchForMovie == \"True\":\n    searchForMovie = True\nelse:\n    searchForMovie = False\nquality_profile_id = config['radarr']['qualityProfileId']\nomdbapi_key = config['radarr']['omdbapi_key']\n\n# Logging ##############################################################################################################\n\nlogging.getLogger().setLevel(logging.NOTSET)\n\nformatter = ColoredFormatter(\n    \"%(log_color)s[%(levelname)s]%(reset)s %(white)s%(message)s\",\n    datefmt=None,\n    reset=True,\n    log_colors={\n        'DEBUG':    'cyan',\n        'INFO':     'green',\n        'WARNING':  'yellow',\n        'ERROR':    'red',\n        'CRITICAL': 'red,bg_white',\n    },\n    secondary_log_colors={},\n    style='%'\n)\n\nlogger = logging.StreamHandler()\nlogger.setLevel(logging.INFO)  # DEBUG To show all\nlogger.setFormatter(formatter)\nlogging.getLogger().addHandler(logger)\nif not os.path.exists(\"./logs/\"): os.mkdir(\"./logs/\")\nlogFileName = \"./logs/rafl.log\"  # .format(datetime.now().strftime(\"%Y-%m-%d-%H.%M.%S\"))\nfilelogger = logging.handlers.RotatingFileHandler(filename=logFileName)\nfilelogger.setLevel(logging.DEBUG)\nlogFormatter = logging.Formatter(\"%(asctime)s [%(levelname)-5.5s]  %(message)s\")\nfilelogger.setFormatter(logFormatter)\nlogging.getLogger().addHandler(filelogger)\n\nlog = logging.getLogger(\"app.\" + __name__)\n\n\n########################################################################################################################\n\ndef add_movie(title, year, imdbid, quality_profile_id):\n\n    global movie_added_count\n    global movie_exist_count\n\n    if year == \"\" or year is None:\n        year = get_year(title)\n    if imdbid == \"\" or imdbid is None:\n        imdbid = get_imdbid(title, year)\n\n    # Store Radarr Server imdbid for faster matching\n    current_movie_ids = [movie.get('imdbId') for movie in RadarrData]\n\n    if match_profile_id(quality_profile_id): ProfileId = get_profile_from_name(quality_profile_id)\n\n    if imdbid is None:\n        log.warning(f\"Cannot find IMDbId for {title}, attempting to add without it...\")\n        # Search by Movie Title in Radarr\n        headers = {\"Content-type\": \"application/json\", 'Accept': 'application/json'}\n        url = f\"{baseurl}{urlbase}/api/v3/movie/lookup?term={title.replace(' ', '%20')}&apikey={api_key}\"\n        radarr_api_response = requests.get(url, headers=headers)\n        data = json.loads(radarr_api_response.text)\n        if radarr_api_response.text == \"[]\":\n            log.error(f\"Sorry. We couldn't find any movies matching {title} ({year})\")\n            return\n        if radarr_api_response.status_code == 200:\n            tmdbid = data[0][\"tmdbId\"]\n            title = data[0][\"title\"]\n            year = data[0]['year']\n            images = json.loads(json.dumps(data[0][\"images\"]))\n            titleslug = data[0][\"titleSlug\"]\n            movie_data = json.dumps({\n                \"title\":               title,\n                \"qualityProfileId\":    ProfileId,\n                \"year\":                year,\n                \"tmdbId\":              tmdbid,\n                \"titleslug\":           titleslug,\n                \"monitored\":           True,\n                \"minimumAvailability\": \"released\",\n                \"rootFolderPath\":      rootfolderpath,\n                \"images\":              images,\n                \"addOptions\":          {\"searchForMovie\": searchForMovie}\n            })\n            # Add Movie To Radarr\n            headers = {\"Content-type\": \"application/json\", 'Accept': 'application/json', \"X-Api-Key\": api_key}\n            url = f'{baseurl}{urlbase}/api/v3/movie'\n            radarr_api_response = requests.post(url, headers=headers, data=movie_data)\n            log.debug(f\"Radarr response: {radarr_api_response.status_code}: {radarr_api_response.text}\")\n            if radarr_api_response.status_code == 201:\n                movie_added_count += 1\n                if searchForMovie:\n                    log.info(f\"{tmdbid}\\t {title} ({year}) Added to Radarr :) NowSearching.\")\n                else:\n                    log.info(f\"{tmdbid}\\t {title} ({year}) Added to Radarr :) Search Disabled.\")\n            elif radarr_api_response.status_code == 400:\n                movie_exist_count += 1\n                log.info(f\"{tmdbid}\\t {title} ({year}) already Exists in Radarr.\")\n                return\n        else:\n            log.error(f\"{imdbid}\\t {title} ({year}) Not found, Not added to Radarr.\")\n            return\n\n    elif imdbid not in current_movie_ids:\n        log.warning(f\"Found IMDbId for {title} - attempting to add to Radarr...\")\n        # Build json Data to import into radarr\n        session = requests.Session()\n        adapter = requests.adapters.HTTPAdapter(max_retries=20)\n        session.mount('https://', adapter)\n        session.mount('http://', adapter)\n\n        headers = {\"Content-type\": \"application/json\", 'Accept': 'application/json'}\n        url = f\"{baseurl}{urlbase}/api/v3/movie/lookup/imdb?imdbId={imdbid}&apikey={api_key}\"\n        radarr_api_response = session.get(url, headers=headers)\n        if len(radarr_api_response.text) == 0:\n            log.error(f\"Sorry. We couldn't find any movies matching {title} ({year})\")\n            return\n        if radarr_api_response.status_code == 200:\n            data = json.loads(radarr_api_response.text)\n            tmdbid = data[\"tmdbId\"]\n            title = data[\"title\"]\n            year = data['year']\n            images = json.loads(json.dumps(data[\"images\"]))\n            titleslug = data[\"titleSlug\"]\n            movie_data = json.dumps({\n                \"title\":               title,\n                \"qualityProfileId\":    ProfileId,\n                \"year\":                year,\n                \"tmdbId\":              tmdbid,\n                \"titleslug\":           titleslug,\n                \"monitored\":           True,\n                \"minimumAvailability\": \"released\",\n                \"rootFolderPath\":      rootfolderpath,\n                \"images\":              images,\n                \"addOptions\":          {\"searchForMovie\": searchForMovie}})\n        elif radarr_api_response.status_code == 404:\n            log.error(f\"{imdbid}\\t {title} ({year}) Movie not found... unable to add to Radarr\")\n            return\n        elif radarr_api_response.status_code == 500:\n            log.error(f\"{imdbid}\\t {title} ({year}) Can't find TMDB ID - movie may have been removed!\")\n            return\n        else:\n            log.error(\"Something else has happened.\")\n            return\n        # Add Movie To Radarr\n        headers = {\"Content-type\": \"application/json\", 'Accept': 'application/json', \"X-Api-Key\": api_key}\n        url = f'{baseurl}{urlbase}/api/v3/movie'\n        radarr_api_response = requests.post(url, headers=headers, data=movie_data)\n        log.debug(f\"Radarr response: {radarr_api_response.status_code}: {radarr_api_response.text}\")\n        if radarr_api_response.status_code == 201:\n            log.debug(\"Connected to Radarr!\")\n            movie_added_count += 1\n            if searchForMovie:  # Check If you want to force download search\n                log.info(\n                    f\"{imdbid}\\t {title} ({year}) Added to Radarr :) Now Searching.\")\n            else:\n                log.info(\n                    f\"{imdbid}\\t {title} ({year}) Added to Radarr :) Search Disabled.\")\n    else:\n        movie_exist_count += 1\n        log.info(f\"{imdbid}\\t {title} ({year}) already exists in Radarr!\")\n        return\n\ndef get_profile_from_name(name :str) -> int:\n    \"\"\"\nConverts Profile Name -> ID\n    :return: ID\n    :type: any\n    \"\"\"  \n    try: \n        number = int(name)\n        return name\n    except ValueError: \n        profiles = quality_profiles\n        profile = next((item for item in profiles if item[\"name\"] == name), False)\n        if not profile:\n            log.error(f\"Could not find profile_id for instance profile ID {name}\")\n            return select_profile_id()\n        return  profile.get('id')\n\n\ndef get_quality_profiles() -> list:\n    \"\"\"\nParses local Radarr API to get the server's quality profiles and return them to calling\nfunctions\n    :return: The server's quality profiles as a list\n    :type: list\n    \"\"\"\n    log.info(\"Getting quality profiles...\")\n    headers = {\"Content-type\": \"application/json\", \"X-Api-Key\": f\"{api_key}\"}\n    url = f\"{baseurl}{urlbase}/api/v3/qualityProfile\"\n    r = requests.get(url, headers=headers)\n    profiles_json = json.loads(r.text)\n    return profiles_json\n\n\ndef select_profile_id():\n    \"\"\"\nAllows the user to select a quality profile ID at runtime using console input\n    :return: Returns an integer that matches the specified quality profile Id\n    :type: int\n\n    \"\"\"\n    selected = False\n    profile_choice = -1\n    print(\"\\nPlease enter a valid profile ID:\")\n    for profile in quality_profiles:\n        print(f\"{profile.get('id')}: {profile.get('name')}\")\n    while not selected:\n        user_input = input(\"> \")\n        selected = match_profile_id(user_input)\n        if selected:\n            profile_choice = user_input\n    return profile_choice\n\n\ndef match_profile_id(quality_id) -> bool:\n    \"\"\"\nChecks if a given quality profile ID matches with one from the API.\n    :type: bool\n    :param quality_id: Quality profile ID as a string of int\n    :return: Returns true if the quality profile is matched/found\n    \"\"\"\n    profiles = quality_profiles\n    if not quality_id.isdigit():\n        profile = next((p for p in profiles if p[\"name\"] == quality_id), False)\n    else:\n        profile = next((p for p in profiles if p['id'] == int(quality_id)), False)\n    if not profile:\n        log.error(f'Could not find profile_id for instance profile ID: {quality_id}')\n        if match_profile_id(select_profile_id()): return True\n    return True\n\n\ndef get_imdbid(title: str, year: str) -> str | None:\n    \"\"\"\nUses OMDB to return the IMDB ID (ttXXXXXXX) of a movie\n    :param title: Title of the movie\n    :param year: Year the movie released\n    :return: IMDB ID of the movie if found, or None if not.\n    \"\"\"\n    # Get Movie imdbid\n    log.info(f\"Getting IMDbId for {title}\")\n    parsed_movie_title = urllib.parse.quote(title, \"UTF-8\")\n    headers = {\"Content-type\": \"application/json\", 'Accept': 'application/json'}\n    r = requests.get(f\"https://www.omdbapi.com/?t={parsed_movie_title}&y={year}&type=movie&apikey={omdbapi_key}\",\n                     headers=headers)\n    if r.status_code == 401:\n        log.error(\"OMDb API Request limit reached!\")\n    d = json.loads(r.text)\n    if r.status_code == 200:\n        if d.get('Response') == \"False\":\n            return None\n        else:\n            return d.get('imdbID')\n    else:\n        return None\n\n\ndef get_year(imdbid: str) -> str | None:\n    \"\"\"\nUses OMDB to check the year that a given movie released\n    :param imdbid: The IMDB ID of a movie\n    :return: Year the movie released if found, None if not\n    \"\"\"\n    # Get Movie Year\n    headers = {\"Content-type\": \"application/json\", 'Accept': 'application/json'}\n    r = requests.get(f\"https://www.omdbapi.com/?t={imdbid}&apikey={omdbapi_key}\", headers=headers)\n    if r.status_code == 401:\n        log.error(\"OMDb API Request limit reached!\")\n    d = json.loads(r.text)\n    if r.status_code == 200:\n        if d.get('Response') == \"False\":\n            return None\n        else:\n            return d.get('Year')\n    else:\n        return None\n\n\ndef main():\n    global RadarrData\n    global quality_profiles \n    global quality_profile_id\n\n    print('\\033c')\n    if sys.version_info[0] < 3:\n        log.error(\"Must be using Python 3\")\n        sys.exit(-1)\n    if len(sys.argv) < 2:\n        log.error(\"No CSV file specified... bye!!\")\n        sys.exit(-1)\n    if not os.path.exists(sys.argv[1]):\n        log.error(f\"{sys.argv[1]} does not exist!\")\n        sys.exit(-1)\n\n    log.info(\"Downloading Radarr Movie Data. :)\")\n    headers = {\"Content-type\": \"application/json\", \"X-Api-Key\": api_key}\n    url = f\"{baseurl}{urlbase}/api/v3/movie\"\n    rsp = requests.get(url, headers=headers)\n    if rsp.status_code == 200:\n        if len(rsp.text) == 0:\n            log.error(\"No data downloaded from Radarr.\")\n            sys.exit(-1)\n        RadarrData = json.loads(rsp.text)\n        if not RadarrData:\n            log.error(\"No data downloaded from Radarr.\")\n            sys.exit(-1)\n        quality_profiles = get_quality_profiles()\n    else:\n        log.error(\"Failed to connect to Radarr...\")\n        sys.exit(-1)\n\n    log.info(f\"Loading {sys.argv[1]}...\")\n    with open(sys.argv[1], encoding=\"ISO-8859-1\", errors='ignore') as csvfile:\n        total_count = len(list(csv.DictReader(csvfile)))\n    with open(sys.argv[1], encoding=\"ISO-8859-1\", errors='ignore') as csvfile:\n        movies_list = csv.DictReader(csvfile)\n        if not total_count > 0:\n            log.error(\"No movies found in CSV file.\")\n            exit()\n        if movies_list.fieldnames != [\"title\", \"year\", \"imdbid\"]:\n            log.error(\"Invalid CSV file - header does not contain title,year,imdbid\")\n            sys.exit(-1)\n        log.info(f\"Found {total_count} movies in {sys.argv[1]} :)\")\n        for row in movies_list:\n            title = row['title']\n            year = row['year']\n            imdbid = row['imdbid']\n            try:\n                if quality_profile_id is None or quality_profile_id == '':\n                    log.warning(\"Quality profile not set in config file.\")\n                    quality_profile_id = select_profile_id()\n                add_movie(title, year, imdbid,quality_profile_id)\n            except Exception as e:\n                exc_type, exc_obj, exc_tb = sys.exc_info()\n                fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n                log.error(exc_type, fname, exc_tb.tb_lineno)\n                sys.exit(-1)\n    log.info(f\"Added {movie_added_count} of {total_count} movies - {movie_exist_count} already existed ;)\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "radarr_remove_downloaded.py",
    "content": "import os, requests, json, logging, logging.handlers, sys\r\nfrom colorlog import ColoredFormatter\r\nimport configparser\r\n\r\n# Config ###############################################################################################################\r\n\r\nconfig = configparser.ConfigParser()\r\nconfig.read('./config.ini')\r\nbaseurl = config['radarr']['baseurl']\r\napi_key = config['radarr']['api_key']\r\n\r\n\r\n# Logging ##############################################################################################################\r\n\r\nformatter = ColoredFormatter(\r\n\t\"%(log_color)s[%(levelname)s]%(reset)s %(white)s%(message)s\",\r\n\tdatefmt=None,\r\n\treset=True,\r\n\tlog_colors={\r\n\t\t'DEBUG':    'cyan',\r\n\t\t'INFO':     'green',\r\n\t\t'WARNING':  'yellow',\r\n\t\t'ERROR':    'red',\r\n\t\t'CRITICAL': 'red,bg_white',\r\n\t},\r\n\tsecondary_log_colors={},\r\n\tstyle='%'\r\n)\r\n\r\nlogging.getLogger().setLevel(logging.NOTSET)\r\n\r\nlogger = logging.StreamHandler(sys.stdout)\r\nlogger.setLevel(logging.INFO) # DEBUG To show all\r\n# logFormatter = logging.Formatter(\"\\033[1;31;32m[%(levelname)s]  \\u001b[0m%(message)s\")\r\nlogger.setFormatter(formatter)\r\nlogging.getLogger().addHandler(logger)\r\n\r\n\r\nrotatingHandler = logging.handlers.RotatingFileHandler(filename='./rrd.log')\r\nrotatingHandler.setLevel(logging.DEBUG)\r\nlogFormatter = logging.Formatter(\"%(asctime)s [%(levelname)-5.5s]  %(message)s\")\r\nrotatingHandler.setFormatter(logFormatter)\r\nlogging.getLogger().addHandler(rotatingHandler)\r\n\r\nlog = logging.getLogger(\"app.\" + __name__)\r\n\r\n########################################################################################################################\r\n\r\nprint('\\033c')\r\nif sys.version_info[0] < 3: log.error(\"Must be using Python 3\"); sys.exit(-1)\r\nlog.info(\"Downloading Radarr Movie Data...\")\r\nheaders = {\"Content-type\": \"application/json\", \"X-Api-Key\": api_key }\r\nurl = \"{}/api/v3/movie\".format(baseurl)\r\nrsp = requests.get(url, headers=headers)\r\ndata = json.loads(rsp.text)\r\ncount = 0\r\nfor i in data:\r\n    headers = {\"Content-type\": \"application/json\", \"X-Api-Key\": api_key }\r\n    url = \"{}/api/v3/movie/{}?deleteFiles=false&addExclusion=false\".format(baseurl,i['id'])\r\n    rsp = requests.delete(url, headers=headers)\r\n    print(rsp.text)\r\n    if rsp.status_code == 200:\r\n        log.info (\"\\u001b[36m{} ({})\\u001b[0m \\u001b[31mRemoving from Radarr...\\u001b[0m\".format(i['title'],i['year']))\r\n\r\n    # if i['hasFile']: print(json.dumps(i, indent=4, sort_keys=True))\r\n    # if i['year'] < 1980 and i['hasFile']:\r\n    #     if os.path.exists(i['path']):\r\n    #         rsp = requests.delete(url, headers=headers)\r\n    #         if rsp.status_code == 200:\r\n    #             count +=1\r\n    #             log.info (\"\\u001b[36m{} ({})\\u001b[0m is older than 1980, \\u001b[31mRemoving from Radarr...\\u001b[0m\".format(i['title'],i['year']))\r\n    if i['hasFile']: \r\n        if os.path.exists(i['path']):\r\n            # if \"720\" or \"1080\" in i['movieFile']['quality']['quality']['name']:\r\n            rsp = requests.delete(url, headers=headers)\r\n            if rsp.status_code == 200:\r\n                count +=1\r\n                log.info (\"\\u001b[36m{} ({})\\u001b[0m Has been downloaded, \\u001b[31mRemoving from Radarr...\\u001b[0m\".format(i['title'],i['year']))\r\nlog.info (\"Removed {} Movies.\".format(count))\r\n"
  },
  {
    "path": "radarr_unmonitor_downloaded.py",
    "content": "import os, requests, json, logging, logging.handlers, sys\nfrom colorlog import ColoredFormatter\nimport configparser\n\n# Config ###############################################################################################################\n\nconfig = configparser.ConfigParser()\nconfig.read('./config.ini')\nbaseurl = config['radarr']['baseurl']\nurlbase  = config['radarr']['urlbase']\napi_key = config['radarr']['api_key']\nif urlbase != \"\": baseurl = \"{}{}\".format(baseurl,urlbase)\n\n# Logging ##############################################################################################################\n\nformatter = ColoredFormatter(\n\t\"%(log_color)s[%(levelname)s]%(reset)s %(white)s%(message)s\",\n\tdatefmt=None,\n\treset=True,\n\tlog_colors={\n\t\t'DEBUG':    'cyan',\n\t\t'INFO':     'green',\n\t\t'WARNING':  'yellow',\n\t\t'ERROR':    'red',\n\t\t'CRITICAL': 'red,bg_white',\n\t},\n\tsecondary_log_colors={},\n\tstyle='%'\n)\n\nlogging.getLogger().setLevel(logging.NOTSET)\n\nlogger = logging.StreamHandler(sys.stdout)\nlogger.setLevel(logging.INFO) # DEBUG To show all\n# logFormatter = logging.Formatter(\"\\033[1;31;32m[%(levelname)s]  \\u001b[0m%(message)s\")\nlogger.setFormatter(formatter)\nlogging.getLogger().addHandler(logger)\nlog = logging.getLogger(\"app.\" + __name__)\n\n########################################################################################################################\n\nprint('\\033c')\nif sys.version_info[0] < 3: log.error(\"Must be using Python 3\"); sys.exit(-1)\nlog.info(\"Downloading Radarr Movie Data...\")\nheaders = {\"Content-type\": \"application/json\", \"X-Api-Key\": api_key }\nurl = \"{}/api/v3/movie\".format(baseurl)\nrsp = requests.get(url, headers=headers)\ndata = json.loads(rsp.text)\ncount = 0\nfor i in data:\n    headers = {\"Content-type\": \"application/json\", \"X-Api-Key\": api_key }\n    url = \"{}/api/v3/movie/{}\".format(baseurl,i['id'])\n    rsp = requests.get(url, headers=headers)\n    if rsp.status_code == 200:\n        if i['hasFile']: \n            if os.path.exists(i['path']):\n                if i['monitored'] == True:\n                    # print(json.dumps(i, indent=4, sort_keys=True))\n                    data = json.loads(json.dumps(i))\n                    data['monitored'] = False\n                    data = json.dumps(data, indent=4, sort_keys=True)\n                    headers = {\"Content-type\": \"application/json\", 'Accept':'application/json', \"X-Api-Key\": api_key}\n                    url = '{}/api/movie'.format(baseurl)\n                    rsp = requests.put(url, headers=headers, data=data)\n                    if rsp.status_code == 201:\n                        count += 1\n                        log.info (\"\\u001b[36m{} ({})\\u001b[0m Has been downloaded, \\u001b[31mUnmonitoring....\\u001b[0m\".format(i['title'],i['year']))\nlog.info (\"Unmonitored {} Movies.\".format(count))\n"
  },
  {
    "path": "remove_from_sonarr.py",
    "content": "import os, requests, json, logging, logging.handlers, sys\nfrom colorlog import ColoredFormatter\nimport configparser\n\n# Config ###############################################################################################################\n\nconfig = configparser.ConfigParser()\nconfig.read('./config.ini')\nbaseurl = config['sonarr']['baseurl']\napi_key = config['sonarr']['api_key']\n\n\n# Logging ##############################################################################################################\n\nformatter = ColoredFormatter(\n\t\"%(log_color)s[%(levelname)s]%(reset)s %(white)s%(message)s\",\n\tdatefmt=None,\n\treset=True,\n\tlog_colors={\n\t\t'DEBUG':    'cyan',\n\t\t'INFO':     'green',\n\t\t'WARNING':  'yellow',\n\t\t'ERROR':    'red',\n\t\t'CRITICAL': 'red,bg_white',\n\t},\n\tsecondary_log_colors={},\n\tstyle='%'\n)\n\nlogging.getLogger().setLevel(logging.NOTSET)\n\nlogger = logging.StreamHandler(sys.stdout)\nlogger.setLevel(logging.INFO) # DEBUG To show all\n# logFormatter = logging.Formatter(\"\\033[1;31;32m[%(levelname)s]  \\u001b[0m%(message)s\")\nlogger.setFormatter(formatter)\nlogging.getLogger().addHandler(logger)\n\n\nrotatingHandler = logging.handlers.RotatingFileHandler(filename='./rfs.log')\nrotatingHandler.setLevel(logging.DEBUG)\nlogFormatter = logging.Formatter(\"%(asctime)s [%(levelname)-5.5s]  %(message)s\")\nrotatingHandler.setFormatter(logFormatter)\nlogging.getLogger().addHandler(rotatingHandler)\n\nlog = logging.getLogger(\"app.\" + __name__)\n\n########################################################################################################################\n\nprint('\\033c')\nif sys.version_info[0] < 3: log.error(\"Must be using Python 3\"); sys.exit(-1)\nlog.info(\"Downloading Sonarr Series Data...\")\nheaders = {\"Content-type\": \"application/json\", \"X-Api-Key\": api_key }\nurl = \"{}/sonarr/api/series\".format(baseurl)\nrsp = requests.get(url, headers=headers)\ndata = json.loads(rsp.text)\ncount = 0\nfor i in data:\n\theaders = {\"Content-type\": \"application/json\", \"X-Api-Key\": api_key }\n\turl = \"{}/sonarr/api/series/{}?deleteFiles=false\".format(baseurl,i['id'])\n\t# if 'Documentary' in i['genres']:\n\t# \tprint('{} has these genres {}'.format(i['title'],i['genres']))\n\tif i['episodeFileCount'] == 0:\n\t\t# print(json.dumps(i, indent=4, sort_keys=True))\n\t\trsp = requests.delete(url, headers=headers)\n\t\tif rsp.status_code == 200:\n\t\t\tcount +=1\n\t\t\tlog.info (\"Removing {} from Sonarr...\".format(i['title']))\nlog.info (\"Removed {} Shows.\".format(count))"
  },
  {
    "path": "requirements.txt",
    "content": "# pip install -r requirements.txt\nrequests\ncolorlog"
  },
  {
    "path": "sonarr_add_from_list.py",
    "content": "import os, time, requests, logging, logging.handlers, json, sys, re, csv, configparser, base64\r\nfrom colorlog import ColoredFormatter\r\nfrom datetime import  datetime\r\n\r\nshow_added_count = 0\r\nshow_exist_count = 0\r\nsonarrData = []\r\n# Config ###############################################################################################################\r\n\r\nconfig = configparser.ConfigParser()\r\nconfig.read('./config.ini')\r\nbaseurl = config['sonarr']['baseurl']\r\nurlbase = config['sonarr']['urlbase']\r\napi_key = config['sonarr']['api_key']\r\nrootfolderpath = config['sonarr']['rootfolderpath']\r\nsearchForShow = config['sonarr']['searchForShow']\r\nqualityProfileId = config['sonarr']['qualityProfileId']\r\nomdbapi_key = config['sonarr']['omdbapi_key']\r\n\r\n# Logging ##############################################################################################################\r\n\r\nlogging.getLogger().setLevel(logging.NOTSET)\r\n\r\nformatter = ColoredFormatter(\r\n    \"%(log_color)s[%(levelname)s]%(reset)s %(white)s%(message)s\",\r\n    datefmt=None,\r\n    reset=True,\r\n    log_colors={\r\n        'DEBUG':    'cyan',\r\n        'INFO':     'green',\r\n        'WARNING':  'yellow',\r\n        'ERROR':    'red',\r\n        'CRITICAL': 'red,bg_white',\r\n    },\r\n    secondary_log_colors={},\r\n    style='%'\r\n)\r\n\r\nlogger = logging.StreamHandler()\r\nlogger.setLevel(logging.INFO) # DEBUG To show all\r\nlogger.setFormatter(formatter)\r\nlogging.getLogger().addHandler(logger)\r\n\r\nif not os.path.exists(\"./logs/\"): os.mkdir(\"./logs/\")\r\nlogFileName =  \"./logs/safl.log\"\r\nfilelogger = logging.handlers.RotatingFileHandler(filename=logFileName)\r\nfilelogger.setLevel(logging.DEBUG)\r\nlogFormatter = logging.Formatter(\"%(asctime)s [%(levelname)-5.5s]  %(message)s\")\r\nfilelogger.setFormatter(logFormatter)\r\nlogging.getLogger().addHandler(filelogger)\r\n\r\nlog = logging.getLogger(\"app.\" + __name__)\r\n\r\n########################################################################################################################\r\n\r\ndef add_show(title,year,imdbid):\r\n    \r\n    # Add Missing to sonarr Work in Progress\r\n    global show_added_count\r\n    global show_exist_count\r\n    if imdbid == None : imdbid = get_imdbid(title,year)\r\n    if imdbid == None : log.info(\"Not imdbid found for {}\".format(title)); return\r\n    imdbIds = []\r\n    tvdbIds = []\r\n    for shows_to_add in sonarrData:  imdbIds.append(shows_to_add.get('imdbId'))\r\n    for shows_to_add in sonarrData:  tvdbIds.append(shows_to_add.get('tvdbId'))\r\n   \r\n    if imdbid not in imdbIds:\r\n        tvdbId = get_tvdbId(title,imdbid)\r\n        if tvdbId in tvdbIds: \r\n            show_exist_count +=1\r\n            log.info(\"\\033[1;36m{}\\t {} ({}) already Exists in Sonarr.\\u001b[0m\".format(imdbid,title,year))\r\n            return\r\n        session = requests.Session()\r\n        adapter = requests.adapters.HTTPAdapter(max_retries=20)\r\n        session.mount('https://', adapter)\r\n        session.mount('http://', adapter) \r\n\r\n        if tvdbId == None: log.error(\"No tvdbId found for {}\".format(title)); return\r\n        if not qualityProfileId.isdigit(): \r\n            ProfileId = get_profile_from_id(qualityProfileId)\r\n        elif qualityProfileId == None: \r\n            log.error(\"\\u001b[35m qualityProfileId Not Set in the config correctly.\\u001b[0m\")\r\n        else: \r\n            ProfileId = qualityProfileId\r\n        \r\n        headers = {\"Content-type\": \"application/json\"}\r\n        url = \"{}{}/api/v3/series/lookup?term=tvdb:{}&apikey={}\".format(baseurl,urlbase,tvdbId, api_key )\r\n        rsp = session.get(url, headers=headers)\r\n        data = json.loads(rsp.text)\r\n        if rsp.text ==\"[]\":\r\n            log.error(\"\\u001b[35mSorry. We couldn't find {} ({})\\u001b[0m\".format(title,year))\r\n            return \r\n        if len(rsp.text)==0: \r\n            log.error(\"Sorry. We couldn't find any Shows matching {} ({})\".format(title,year))\r\n            return \r\n        tvdbId = data[0][\"tvdbId\"]\r\n        title = data[0][\"title\"]\r\n        year = data[0][\"year\"]\r\n        images = json.loads(json.dumps(data[0][\"images\"]))\r\n        titleslug = data[0][\"titleSlug\"] \r\n        seasons = json.loads(json.dumps(data[0][\"seasons\"]))\r\n        headers = {\"Content-type\": \"application/json\", \"X-Api-Key\": \"{}\".format(api_key)}\r\n        data = json.dumps({\r\n            \"title\": title ,\r\n            \"year\": year ,\r\n            \"tvdbId\": tvdbId ,\r\n            \"titleslug\": titleslug,\r\n            \"monitored\": True ,\r\n            \"seasonFolder\": True,\r\n            \"qualityProfileId\": ProfileId,\r\n            \"rootFolderPath\": rootfolderpath ,\r\n            \"images\": images,\r\n            \"seasons\": seasons,\r\n            \"addOptions\":\r\n                        {\r\n                        \"ignoreEpisodesWithFiles\": True,\r\n                        \"ignoreEpisodesWithoutFiles\": False,\r\n                        \"searchForMissingEpisodes\": bool(searchForShow)\r\n                        }\r\n\r\n            })\r\n        \r\n        url = '{}{}/api/v3/series'.format(baseurl,urlbase)\r\n        rsp = requests.post(url, headers=headers, data=data)\r\n        data = json.loads(rsp.text)\r\n\r\n        if rsp.status_code == 201:\r\n            show_added_count +=1\r\n            if searchForShow == \"True\":\r\n                log.info(\"\\033[0;32m{}\\t {} ({}) Added to Sonarr :) Now Searching.\\u001b[0m\".format(imdbid,title,year))\r\n            else:\r\n                log.info(\"\\033[0;32m{}\\t {} ({}) Added to Sonarr :) \\033[1;31mSearch Disabled.\\u001b[0m\".format(imdbid,title,year))\r\n        elif rsp.status_code == 400:\r\n            show_exist_count +=1\r\n            log.info(\"\\033[1;36m{}\\t {} ({}) already Exists in Sonarr.\\u001b[0m\".format(imdbid,title,year))\r\n            return\r\n        else:\r\n            log.error(\"\\u001b[32m{}\\t {} ({}) Not found, Not added to Sonarr.\\u001b[0m\".format(imdbid,title,year))\r\n            return\r\n    \r\n    else:\r\n        show_exist_count+=1\r\n        log.info(\"\\033[1;36m{}\\t {} ({}) already Exists in Sonarr.\\u001b[0m\".format(imdbid,title,year))\r\n        return\r\n\r\ndef get_imdbid(title,year):\r\n    # Get TV Show imdbid \r\n    headers = {\"Content-type\": \"application/json\", 'Accept':'application/json'}\r\n    r = requests.get(\"https://www.omdbapi.com/?t={}&y={}&apikey={}\".format(title,year,omdbapi_key), headers=headers)\r\n    if r.status_code == 401:\r\n        log.error(\"omdbapi Request limit reached!\")\r\n        return None\r\n     \r\n    if r.status_code == 200: \r\n        d = json.loads(r.text)\r\n        if d.get('Response') == \"False\": \r\n            return  None\r\n        else: \r\n            return d.get('imdbID')\r\n    else: \r\n        return None \r\n\r\ndef get_tvdbId(title,imdbid):\r\n    api = str(base64.b64decode('YWE2Yjc5YTBlZDdjM2Y3NWUyOWI1MjkyOTAyNjhmOGFkNzM0ZmE3MWUzYzA3Zjg2YmE2OTVlMzQzZDFmZmNjMw=='))\r\n    title = title.replace(\" \",\"-\"); title = title.replace(\"'\",\"-\"); title = title.replace(\":\",\"\")\r\n    if title.find(\"&\"): title = title.replace(\" \",\"\"); title = title.replace(\"&\",\"-\")\r\n    headers = {'Content-Type': 'application/json', 'trakt-api-version': '2', 'trakt-api-key': api}\r\n    rsp = requests.get('https://api.trakt.tv/search/imdb/{}?type=show'.format(imdbid), headers=headers)\r\n    if rsp.status_code == 403: log.error(\"trakt Api Failed\"); return None\r\n    if rsp.status_code == 200:\r\n        d = json.loads(rsp.text)\r\n        if d == []: \r\n            rsp = requests.get('https://api.trakt.tv/shows/{}'.format(title), headers=headers)\r\n            if rsp.status_code == 200:\r\n                d = json.loads(rsp.text)\r\n                if d == []: return None \r\n                return d['ids']['tvdb']\r\n            else:\r\n                return None\r\n        else:\r\n            return d[0]['show']['ids']['tvdb']\r\n    else:\r\n         return None\r\n\r\ndef get_profile_from_id(id): \r\n    headers = {\"Content-type\": \"application/json\", \"X-Api-Key\": \"{}\".format(api_key)}\r\n    url = \"{}{}/api/v3/profile\".format(baseurl,urlbase)\r\n    r = requests.get(url, headers=headers)\r\n    d = json.loads(r.text)\r\n    profile = next((item for item in d if item[\"name\"].lower() == id.lower()), False)\r\n    if not profile:\r\n        log.error('Could not find profile_id for instance profile {}'.format(id))\r\n        sys.exit(0)\r\n    return  profile.get('id')\r\n\r\n\r\ndef main():\r\n    print('\\033c')\r\n    if sys.version_info[0] < 3: log.error(\"Must be using Python 3\"); sys.exit(-1)\r\n    global sonarrData\r\n    if len(sys.argv)<2: log.error(\"No list Specified... Bye!!\"); sys.exit(-1)\r\n    if not os.path.exists(sys.argv[1]): log.info(\"{} Does Not Exist\".format(sys.argv[1])); sys.exit(-1)\r\n    log.info(\"Downloading Sonarr Show Data. :)\")\r\n    headers = {\"Content-type\": \"application/json\", \"X-Api-Key\": api_key }\r\n    url = \"{}{}/api/v3/series\".format(baseurl,urlbase)\r\n    rsp = requests.get(url , headers=headers)\r\n    if rsp.status_code == 200:\r\n        sonarrData = json.loads(rsp.text)\r\n    else:\r\n        log.error(\"Failed to connect to Radar...\")\r\n    with open(sys.argv[1], encoding=\"utf8\") as csvfile: total_count = len(list(csv.DictReader(csvfile)))\r\n    with open(sys.argv[1], encoding=\"utf8\") as csvfile:\r\n        s = csv.DictReader(csvfile)\r\n        if not total_count>0: log.error(\"No TV Shows Found in file... Bye!!\"); exit()\r\n        log.info(\"Found {} TV Shows in {}. :)\".format(total_count,sys.argv[1]))\r\n\r\n        for row in s:\r\n            if not (row): continue\r\n            if len(row) >= 4: log.error(\"Invalid Format on line {} Data:{}\".format(str(s.line_num),row)); continue\r\n            try: row['title']\r\n            except: log.error(\"Invalid CSV File, Header does not contain title,year,imdbid\"); sys.exit(-1)\r\n            title = row['title']; year = row['year']; imdbid = row['imdbid']\r\n            try: add_show(title,year,imdbid)\r\n            except Exception as e: log.error(e); sys.exit(-1)\r\n    log.info(\"Added {} of {} Shows, {} Already Exist\".format(show_added_count,total_count,show_exist_count))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    main()\r\n\r\n"
  }
]