summaryrefslogtreecommitdiffstats
path: root/addons/metadata.tvshows.themoviedb.org.python
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-10 18:07:22 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-10 18:07:22 +0000
commitc04dcc2e7d834218ef2d4194331e383402495ae1 (patch)
tree7333e38d10d75386e60f336b80c2443c1166031d /addons/metadata.tvshows.themoviedb.org.python
parentInitial commit. (diff)
downloadkodi-c04dcc2e7d834218ef2d4194331e383402495ae1.tar.xz
kodi-c04dcc2e7d834218ef2d4194331e383402495ae1.zip
Adding upstream version 2:20.4+dfsg.upstream/2%20.4+dfsg
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'addons/metadata.tvshows.themoviedb.org.python')
-rw-r--r--addons/metadata.tvshows.themoviedb.org.python/LICENSE.txt674
-rw-r--r--addons/metadata.tvshows.themoviedb.org.python/addon.xml70
-rw-r--r--addons/metadata.tvshows.themoviedb.org.python/changelog.txt152
-rw-r--r--addons/metadata.tvshows.themoviedb.org.python/libs/actions.py240
-rw-r--r--addons/metadata.tvshows.themoviedb.org.python/libs/api_utils.py79
-rw-r--r--addons/metadata.tvshows.themoviedb.org.python/libs/cache.py81
-rw-r--r--addons/metadata.tvshows.themoviedb.org.python/libs/data_utils.py451
-rw-r--r--addons/metadata.tvshows.themoviedb.org.python/libs/debugger.py115
-rw-r--r--addons/metadata.tvshows.themoviedb.org.python/libs/imdbratings.py72
-rw-r--r--addons/metadata.tvshows.themoviedb.org.python/libs/settings.py111
-rw-r--r--addons/metadata.tvshows.themoviedb.org.python/libs/tmdb.py466
-rw-r--r--addons/metadata.tvshows.themoviedb.org.python/libs/traktratings.py66
-rw-r--r--addons/metadata.tvshows.themoviedb.org.python/libs/utils.py72
-rw-r--r--addons/metadata.tvshows.themoviedb.org.python/main.py32
-rw-r--r--addons/metadata.tvshows.themoviedb.org.python/resources/icon.pngbin0 -> 6500 bytes
-rw-r--r--addons/metadata.tvshows.themoviedb.org.python/resources/language/resource.language.en_gb/strings.po157
-rw-r--r--addons/metadata.tvshows.themoviedb.org.python/resources/settings.xml299
17 files changed, 3137 insertions, 0 deletions
diff --git a/addons/metadata.tvshows.themoviedb.org.python/LICENSE.txt b/addons/metadata.tvshows.themoviedb.org.python/LICENSE.txt
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/addons/metadata.tvshows.themoviedb.org.python/LICENSE.txt
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<https://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<https://www.gnu.org/licenses/why-not-lgpl.html>.
diff --git a/addons/metadata.tvshows.themoviedb.org.python/addon.xml b/addons/metadata.tvshows.themoviedb.org.python/addon.xml
new file mode 100644
index 0000000..4cc91b1
--- /dev/null
+++ b/addons/metadata.tvshows.themoviedb.org.python/addon.xml
@@ -0,0 +1,70 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<addon id="metadata.tvshows.themoviedb.org.python"
+ name="TMDb TV Shows"
+ version="1.6.0"
+ provider-name="Team Kodi">
+ <requires>
+ <import addon="xbmc.python" version="3.0.0"/>
+ <import addon="xbmc.metadata" version="2.1.0"/>
+ </requires>
+ <extension point="xbmc.metadata.scraper.tvshows" library="main.py" cachepersistence="00:15"/>
+ <extension point="xbmc.addon.metadata">
+ <news>1.6.0
+change to use new JSON based episodeguide format to handle multiple providers
+fixes for last minute changes to new Nexus Python bindings
+ </news>
+ <platform>all</platform>
+ <license>GPL-3.0-or-later</license>
+ <assets>
+ <icon>resources/icon.png</icon>
+ </assets>
+ <forum>https://forum.kodi.tv/showthread.php?tid=357232</forum>
+ <website>https://www.themoviedb.org</website>
+ <source>https://github.com/xbmc/metadata.tvshows.themoviedb.org.python</source>
+ <summary lang="be_BY">Атрымліваць метаданыя серыялаў з themoviedb.org</summary>
+ <summary lang="ca_ES">Agafa les metadades de les sèries de themoviedb.org</summary>
+ <summary lang="cs_CZ">Získat metadata pro seriály z themoviedb.org</summary>
+ <summary lang="da_DK">Hent metadata til tv-shows fra themoviedb.org</summary>
+ <summary lang="de_DE">TV-Show-Metadaten von themoviedb.org abrufen</summary>
+ <summary lang="en_GB">Fetch TV Show metadata from themoviedb.org</summary>
+ <summary lang="es_ES">Obtener metadatos de Serie de TV de themoviedb.org</summary>
+ <summary lang="es_MX">Obtener metadatos de series de themoviedb.org</summary>
+ <summary lang="et_EE">Hangi seriaali metaandmed allikast themoviedb.org</summary>
+ <summary lang="fi_FI">The Movie Database (TMDB) -tietolähde televisiosarjoille</summary>
+ <summary lang="fr_FR">Récupérer les métadonnées d&apos;une série depuis themoviedb.org</summary>
+ <summary lang="id_ID">Ambil metadata Acara TV dari themoviedb.org</summary>
+ <summary lang="is_IS">Sækja lýsigögn sjónvarpsþátta frá themoviedb.org</summary>
+ <summary lang="it_IT">Recupera i metadati dei programmi TV da themovedb.org</summary>
+ <summary lang="ko_KR">themoviedb.org에서 TV쇼 메타데이터를 가져옵니다</summary>
+ <summary lang="nl_NL">Haal metadata van tv-programma&apos;s op van themoviedb.org</summary>
+ <summary lang="pl_PL">Pobieraj metadane programów telewizyjnch z themoviedb.org</summary>
+ <summary lang="pt_BR">Obter metadados de Séries em themoviedb.org</summary>
+ <summary lang="ru_RU">Получение метаданных о сериалах с сайта themoviedb.org</summary>
+ <summary lang="sv_SE">Hämta metadata för TV-serier från themoviedb.org</summary>
+ <summary lang="tr_TR">TV Programları meta verilerini themoviedb.org sitesinden al</summary>
+ <summary lang="zh_CN">从 themoviedb.org 获取剧集信息</summary>
+ <description lang="be_BY">The Movie Database (TMDb) - база даных фільмаў і серыялаў, створаная супольнасцю. Усе даныя дадавалі ўдзельнікі гэтай цудоўнай супольнасці, пачынаючы з 2008. Шматнацыянасць і разнастайнасць даных - тое, чым мы вельмі ганарымся. Калі сказаць прасцей, то мы жывем супольнасцю, і гэта адрознівае нас ад іншых.</description>
+ <description lang="ca_ES">The Movie Database (TMDb) és una base de dades de pel·lícules i sèries creada per la comunitat. Cada dada ha estat afegida per la nostra increïble comunitat que data de 2008. El fort enfoc internacional i la quantitat de dades de TMDb és en gran mesura inigualable i una cosa de la qual estem increïblement orgullosos. En poques paraules, vivim i respirem comunitat i això és precisament el que ens fa diferents.</description>
+ <description lang="cs_CZ">The Movie Database (TMDb) je komunitní databáze filmů a seriálů. Každý kousek dat byl přidán naší úžasnou komunitou sahající až do roku 2008. Silné mezinárodní zaměření a rozsah dat TMDb jsou do značné míry bezkonkurenční a jsme na ně nesmírně hrdí. Jednoduše řečeno, žijeme a dýcháme komunitou, a to je přesně to, co nás odlišuje.</description>
+ <description lang="da_DK">The Movie Database (TMDb) er en community-bygget film- og tv-database. Hvert stykke data er blevet tilføjet af vores fantastiske community, der går tilbage til 2008. TMDbs stærke internationale fokus og bredde af data er stort set uovertruffen, og noget vi er utroligt stolte af. Enkelt sagt, vi lever og ånder community, og det er netop det, der gør os forskellige.</description>
+ <description lang="de_DE">The Movie Database (TMDb) ist eine Film- und TV-Datenbank. Seit 2008 wurde jeder einzelne Datensatz von einer tollen Community beigesteuert. TMDb&apos;s starker internationaler Fokus und die Vielfalt der Daten ist weitgehend unübertroffen. Die Betreiber von TMDb sind darauf sehr stolz. Vereinfacht gesagt, lebt und atmet TMDb den Community-Gedanken und das genau macht den Unterschied.</description>
+ <description lang="en_GB">The Movie Database (TMDb) is a community built movie and TV database. Every piece of data has been added by our amazing community dating back to 2008. TMDb&apos;s strong international focus and breadth of data is largely unmatched and something we&apos;re incredibly proud of. Put simply, we live and breathe community and that&apos;s precisely what makes us different.</description>
+ <description lang="es_ES">The Movie Database (TMDb) es una base de datos contruida comunitariamente sobre películas y TV. Cada pedazo de información ha sido añadida por nuestra increible comunidad desde 2008. El sólido enfoque internacional y la amplitud de datos de TMDb son en gran medida incomparables y es algo de lo que estamos increíblemente orgullosos. En pocas palabras, vivimos y respiramos en comunidad y eso es precisamente lo que nos hace diferentes.</description>
+ <description lang="es_MX">The Movie Database (TMDb) es una base de datos de películas y series creada por la comunidad. Cada pedazo de información ha sido agregada por nuestra increíble comunidad desde 2008. El fuerte enfoque internacional de TMDb y la variedad de información son en gran medida incomparables y algo de lo que estamos increíblemente orgullosos. En pocas palabras, vivimos y respiramos comunidad y eso es precisamente lo que nos hace diferentes.</description>
+ <description lang="et_EE">The Movie Database (TMDb) on kogukonna loodud filmide ja sarjade andmebaas. Meie imeline kogukond on lisanud kõik need andmed alates aastast 2008. TMDb tugev rahvusvaheline fookus ja andmete laius on suures osas võrreldamatud ja selle üle oleme ääretult uhked. Lihtsamalt öeldes elame ja hingame kogukonnas ning just see teebki meid erinevaks.</description>
+ <description lang="fi_FI">The Movie Database (TMDB) on yhteisön ylläpitämä, ilmainen ja avoin tietokanta elokuville ja televisiosarjoille. Palvelulla on miljoonia kuukausittaisia käyttäjiä ja sen tehokkaan rajapinnan avulla Kodi ja monet muut mediasovellukset voivat hyödyntää palvelun metatietoja ja mediakuvituksia käyttökokemuksen parantamiseen. Tietokannan vahva painotus kansaivälisyyteen ja kattava tietomäärä on suurelta osin ylivertainen ja olemme tästä erittäin ylpeitä. Yksinkertaisesti sanoen, elämme ja hengitämme yhteisönä ja juuri se tekee meistä erilaisia.</description>
+ <description lang="fr_FR">La base de données The Movie Database (TMDb) est un projet communautaire visant à référencer les informations de films et séries télé. Chaque information a été ajoutée par notre incroyable communauté, et ce depuis 2008. La force internationale du projet TMBd, ainsi que la diversité et l&apos;étendue de ces données l&apos;ont rendu leader dans ce domaine et nous en sommes extrêmement fière. Décrit simplement, nous vivons et respirons communauté et c&apos;est précisément ce qui nous rend différent.</description>
+ <description lang="id_ID">The Movie Database (TMDb) adalah database film dan TV yang dibangun oleh komunitas. Setiap bagian data telah ditambahkan oleh komunitas kami yang luar biasa sejak tahun 2008. Fokus internasional TMDb yang kuat dan luasnya data sebagian besar tak tertandingi dan sesuatu yang sangat kami banggakan. Sederhananya, kita hidup dan bernafas dalam komunitas dan justru itulah yang membuat kita berbeda.</description>
+ <description lang="is_IS">The Movie Database (TMDb) er samfélagslegur gagnagrunnur kvikmynda- og sjónvarpsefnis. Hver einasti gagnabútur hefur verið settur inn af frábærum liðsmönnum okkar allar götur síðan 2008. Mikil alþjóðleg áhersla TMDb ásamt breiðu sviði gagna sést óvíða og er eitthvað sem við erum ótrúlega stolt af. Sett fram á einfaldan máta, við lifum og hrærumst í þessu samfélagi og það er nákvæmlega þess vegna sem við erum öðruvísi.</description>
+ <description lang="it_IT">Il Movie Database (TMDb) è un database di film e TV creato dalla comunità. Ogni dato è stato aggiunto dalla nostra straordinaria comunità che risale al 2008. La forte attenzione internazionale e l&apos;ampiezza dei dati di TMDb sono in gran parte impareggiabili e qualcosa di cui siamo incredibilmente orgogliosi. In parole povere, viviamo e respiriamo in comunità ed è proprio questo che ci rende diversi.</description>
+ <description lang="ko_KR">The Movie Database (TMDb)는 영화와 TV 데이터베이스를 구축한 커뮤니티입니다. 모든 자료들은 우리 놀라운 커뮤니티에서 2008년부터 추가돼 온 것들입니다. TMDb의 강력한 국제적 초점과 광범위한 데이터는 타의 추종을 불허하며 우리가 자랑스러워하는 점입니다. 간단히 말해, 우리는 커뮤니티와 살고 호흡하며 그것이 우리가 다른 점입니다.</description>
+ <description lang="nl_NL">De Movie Database (TMDb) is een door de gemeenschap gebouwde film- en tv-database. Elk stukje data is toegevoegd door onze geweldige community die teruggaat tot 2008. TMDb&apos;s sterke internationale focus en brede waaier aan data is grotendeels ongeëvenaard en iets waar we ongelooflijk trots op zijn. Simpel gezegd, we leven en ademen gemeenschap en dat is precies wat ons anders maakt.</description>
+ <description lang="pl_PL">The Movie Database (TMDb) to baza filmów i programów telewizyjnych zbudowana przez społeczność. Każdy element danych został dodany przez naszą niesamowitą społeczność od 2008 roku. Silna międzynarodowa koncentracja TMDb i zakres danych są w dużej mierze niezrównane i jesteśmy z tego niesamowicie dumni. Mówiąc prościej, żyjemy i oddychamy wspólnotą i właśnie to nas wyróżnia.</description>
+ <description lang="pt_BR">The Movie Database (TMDb) é um banco de dados de filmes e séries criado pela comunidade. Cada um dos pedaços de dados foram adicionados por nossa incrível comunidade desde 2008. O forte foco internacional e a amplitude de dados do TMDb são incomparáveis, algo do qual temos muito orgulho. Resumindo, vivemos e respiramos comunidade e é precisamente isso que nos torna diferentes.</description>
+ <description lang="ru_RU">The Movie Database (TMDb) - это база данных фильмов и сериалов, созданная сообществом. Все данные были добавлены нашим замечательным сообществом, начиная с 2008 года. Международная направленность и широта данных TMDb во многом не имеют себе равных, и это то, чем мы невероятно гордимся. Проще говоря, мы живём и дышим сообществом, и именно это отличает нас от других.</description>
+ <description lang="sv_SE">The Movie Database (TMDb) är en communitybyggd film- och TV-databas. All data har lagts till av våra fantastiska medlemmar ända sen 2008. TMDbs starka internationella fokus och bredd är i stort sett oöverträffad och något vi är väldigt stolta över. Communityn är hjärtat i det hela och det är det som skiljer oss från mängden.</description>
+ <description lang="tr_TR">The Movie Database (TMDb), topluluk tarafından oluşturulmuş bir film ve TV veritabanıdır. Her bir veri parçası, 2008 yılına dayanan muhteşem topluluğumuz tarafından eklenmiştir. TMDb&apos;nin güçlü uluslararası odağı ve veri genişliği büyük ölçüde benzersizdir ve inanılmaz derecede gurur duyduğumuz bir şeydir. Basitçe söylemek gerekirse, topluluk içinde yaşıyor ve nefes alıyoruz ve bizi farklı kılan da tam olarak bu.</description>
+ <description lang="zh_CN">TMDb 是一个由网络社区创建的影视数据库。每一条数据都是由我们令人惊叹的社区添加的,可以追溯到2008年。TMDb 强大的国际关注度和数据广度在很大程度上是无与伦比的,我们对此感到无比自豪。简单地说,我们生活在社区中,呼吸着社区的气息,这正是我们与众不同的原因。</description>
+ </extension>
+</addon>
+
diff --git a/addons/metadata.tvshows.themoviedb.org.python/changelog.txt b/addons/metadata.tvshows.themoviedb.org.python/changelog.txt
new file mode 100644
index 0000000..9fd1813
--- /dev/null
+++ b/addons/metadata.tvshows.themoviedb.org.python/changelog.txt
@@ -0,0 +1,152 @@
+1.6.0
+change to use new JSON based episodeguide format to handle multiple providers
+fixes for last minute changes to new Nexus Python bindings
+
+1.5.6
+fix for scraper ignoring NFO files with TVDB artwork URL
+
+1.5.5
+fix for cast order in episode lists
+remove use of depreciated logos categorization
+filter out SVG artwork
+updated language files
+
+1.5.4
+unreleased
+
+1.5.3
+fix to properly parse NFO file for show ID
+
+1.5.2
+added episode runtime from TMDb API
+updated language files
+
+1.5.1
+added two language options to the settings (kn-IN and te-IN)
+updated language files
+added additional error catching for bad JSON from API
+added typing for all calls
+
+1.5.0
+Nexus only updates to use new VideoInfoTag setters
+general code cleanup
+updated language files
+
+1.4.10
+updates to image reduction algorithm to better deal with shows with lots of seasons
+
+1.4.9
+fix to fallback to English trailer if no trailer found in selected language
+
+1.4.8
+changed IMDB parsing to use JSON from application/ld+json section instead of HTML
+updated language files
+
+1.4.7
+fix for shows with large number of images causing SQL error when using mySQL/MariaDB
+
+1.4.6
+fix IMDB HTML scrape to work with new IMDB site
+language updates
+
+1.4.5
+fix settings file to show correct default for studio and country storage
+
+1.4.4
+fix so studios get added even if there is no country
+change the default setting so that studio and country are stored separately
+
+1.4.3
+fix for crash if episode group has a season with no episodes
+
+1.4.2
+fix for crash if Kodi calls the scraper without passing the source settings
+change so that old TVDB XML scraper episodeguide URL will work to get new episodeguide from TMDb
+
+1.4.1
+fix for crash if TMDb returns no TV show results when using external ID in parsing nfo file
+
+1.4.0
+TV show trailers from YouTube now included in metadata (with option to turn it off)
+option to select which YouTube addon is used to play trailers
+scraper now parses IDs from TVDB and IMDB URLs for identifying shows
+(thanks to tielis for these contributions)
+
+1.3.14
+fix for named seasons in NFO files being ignored
+
+1.3.13
+original title is now saved along with title in selected language
+added option (default to true) to separate fanart from landscape art
+
+1.3.12
+writer credits now include anyone with TMDb department of Writing
+changed location of cache files to special://temp/metadata.tvshows.themoviedb.org.python/cache
+
+1.3.10
+fix for issue with episode group seasons not being numbered correctly
+fix for incorrect parsing of episode guide URL from XML scraper
+fix for crash in certain circumstances if TMDb returns no results
+fix for failed searches if show has extended characters in title
+fix for changes in the data delivered by the TMDb API
+
+1.3.2
+fix for shows/episodes not loading cast correctly
+fix for crash when episode has no name
+
+1.3.1
+scraper returns primary poster as the first poster from TMDb if no posters for the chosen language are available
+updated debug logging
+
+1.3.0
+scraper now returns URL references for all possible art so Kodi can decide what to display based on system settings
+
+1.2.3
+fix for crash if show had no network listed on TMDb
+
+1.2.2
+change so that scraper returns English data for a show if data is missing in selected language
+fixed order of certification preferences in setting
+
+1.2.1
+pull configuration for TMDb API from the API server and cache it
+provide preview image for art lists (provides faster loading of small images)
+delete expired cache files periodically
+first version available via the Kodi repo
+
+
+1.2.0
+removed external module dependencies
+version number change to reflect that Leia and Matrix code are no longer in sync (Leia will remain on 1.1.x, Matrix will be 1.2.x and higher)
+
+
+1.1.13
+added back Trakt ratings (different method to avoid crashes)
+changed how images are retrieved to ensure something is returned in most cases (see post below for more details)
+
+
+1.1.12
+fix for crash if scraping an episode with an nfo file that doesn't have the TMDb ID in it
+
+
+1.1.11
+fix for source settings being ignored
+
+
+1.1.10
+removed Trakt support due to periodic crashes
+
+
+1.1.9
+added option to get ratings from Trakt and IMDb
+added option to disable the text prepended to the content rating
+re-arranged settings
+since the code is shared between the two releases, synced version numbers
+
+
+1.1.8
+fix for crash if scraping a show with lots of artwork
+
+
+1.1.7
+added support for fanarttv client key \ No newline at end of file
diff --git a/addons/metadata.tvshows.themoviedb.org.python/libs/actions.py b/addons/metadata.tvshows.themoviedb.org.python/libs/actions.py
new file mode 100644
index 0000000..100476a
--- /dev/null
+++ b/addons/metadata.tvshows.themoviedb.org.python/libs/actions.py
@@ -0,0 +1,240 @@
+# -*- coding: UTF-8 -*-
+#
+# Copyright (C) 2020, Team Kodi
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+# pylint: disable=missing-docstring
+#
+# This is based on the metadata.tvmaze scrapper by Roman Miroshnychenko aka Roman V.M.
+
+"""Plugin route actions"""
+
+from __future__ import absolute_import, unicode_literals
+
+import sys
+import json
+import urllib.parse
+import xbmcgui
+import xbmcplugin
+from . import tmdb, data_utils
+from .utils import logger, safe_get
+try:
+ from typing import Optional, Text, Union, ByteString # pylint: disable=unused-import
+except ImportError:
+ pass
+
+HANDLE = int(sys.argv[1]) # type: int
+
+
+def find_show(title, year=None):
+ # type: (Union[Text, bytes], Optional[Text]) -> None
+ """Find a show by title"""
+ if not isinstance(title, str):
+ title = title.decode('utf-8')
+ logger.debug('Searching for TV show {} ({})'.format(title, year))
+ search_results = tmdb.search_show(title, year)
+ for search_result in search_results:
+ show_name = search_result['name']
+ if safe_get(search_result, 'first_air_date') is not None:
+ show_name += ' ({})'.format(search_result['first_air_date'][:4])
+ list_item = xbmcgui.ListItem(show_name, offscreen=True)
+ show_info = search_result
+ list_item = data_utils.add_main_show_info(
+ list_item, show_info, full_info=False)
+ # Below "url" is some unique ID string (may be an actual URL to a show page)
+ # that is used to get information about a specific TV show.
+ xbmcplugin.addDirectoryItem(
+ HANDLE,
+ url=str(search_result['id']),
+ listitem=list_item,
+ isFolder=True
+ )
+
+
+def get_show_id_from_nfo(nfo):
+ # type: (Text) -> None
+ """
+ Get show ID by NFO file contents
+
+ This function is called first instead of find_show
+ if a NFO file is found in a TV show folder.
+
+ :param nfo: the contents of a NFO file
+ """
+ if isinstance(nfo, bytes):
+ nfo = nfo.decode('utf-8', 'replace')
+ logger.debug('Parsing NFO file:\n{}'.format(nfo))
+ parse_result, named_seasons = data_utils.parse_nfo_url(nfo)
+ if parse_result:
+ if parse_result.provider == 'themoviedb':
+ show_info = tmdb.load_show_info(
+ parse_result.show_id, ep_grouping=parse_result.ep_grouping, named_seasons=named_seasons)
+ else:
+ show_info = None
+ if show_info is not None:
+ list_item = xbmcgui.ListItem(show_info['name'], offscreen=True)
+ # "url" is some string that unique identifies a show.
+ # It may be an actual URL of a TV show page.
+ xbmcplugin.addDirectoryItem(
+ HANDLE,
+ url=str(show_info['id']),
+ listitem=list_item,
+ isFolder=True
+ )
+
+
+def get_details(show_id):
+ # type: (Text) -> None
+ """Get details about a specific show"""
+ logger.debug('Getting details for show id {}'.format(show_id))
+ show_info = tmdb.load_show_info(show_id)
+ if show_info is not None:
+ list_item = xbmcgui.ListItem(show_info['name'], offscreen=True)
+ list_item = data_utils.add_main_show_info(
+ list_item, show_info, full_info=True)
+ xbmcplugin.setResolvedUrl(HANDLE, True, list_item)
+ else:
+ xbmcplugin.setResolvedUrl(
+ HANDLE, False, xbmcgui.ListItem(offscreen=True))
+
+
+def get_episode_list(show_ids): # pylint: disable=missing-docstring
+ # type: (Text) -> None
+ # Kodi has a bug: when a show directory contains an XML NFO file with
+ # episodeguide URL, that URL is always passed here regardless of
+ # the actual parsing result in get_show_from_nfo()
+ # so much of this weird logic is to deal with that
+ try:
+ all_ids = json.loads(show_ids)
+ show_id = all_ids.get('tmdb')
+ if not show_id:
+ for key, value in all_ids.items():
+ show_id = str(data_utils._convert_ext_id(key, value))
+ if show_id:
+ break
+ if not show_id:
+ show_id = str(show_ids)
+ except (ValueError, AttributeError):
+ show_id = str(show_ids)
+ if show_id.isdigit():
+ logger.error(
+ 'using deprecated episodeguide format, this show should be refreshed or rescraped')
+ if not show_id:
+ raise RuntimeError(
+ 'No TMDb TV show id found in episode guide, this show should be refreshed or rescraped')
+ elif not show_id.isdigit():
+ parse_result, named_seasons = data_utils.parse_nfo_url(show_id)
+ if parse_result:
+ show_id = parse_result.show_id
+ else:
+ raise RuntimeError(
+ 'No TMDb TV show id found in episode guide, this show should be refreshed or rescraped')
+ logger.debug('Getting episode list for show id {}'.format(show_id))
+ show_info = tmdb.load_show_info(show_id)
+ if show_info is not None:
+ theindex = 0
+ for episode in show_info['episodes']:
+ epname = episode.get('name', 'Episode ' +
+ str(episode['episode_number']))
+ list_item = xbmcgui.ListItem(epname, offscreen=True)
+ list_item = data_utils.add_episode_info(
+ list_item, episode, full_info=False)
+ encoded_ids = urllib.parse.urlencode(
+ {'show_id': str(show_info['id']), 'episode_id': str(theindex)}
+ )
+ theindex = theindex + 1
+ # Below "url" is some unique ID string (may be an actual URL to an episode page)
+ # that allows to retrieve information about a specific episode.
+ url = urllib.parse.quote(encoded_ids)
+ xbmcplugin.addDirectoryItem(
+ HANDLE,
+ url=url,
+ listitem=list_item,
+ isFolder=True
+ )
+ else:
+ logger.error(
+ 'unable to get show information using show id {}'.format(show_id))
+ logger.error('you may need to refresh the show to get a valid show id')
+
+
+def get_episode_details(encoded_ids): # pylint: disable=missing-docstring
+ # type: (Text) -> None
+ encoded_ids = urllib.parse.unquote(encoded_ids)
+ decoded_ids = dict(urllib.parse.parse_qsl(encoded_ids))
+ logger.debug('Getting episode details for {}'.format(decoded_ids))
+ episode_info = tmdb.load_episode_info(
+ decoded_ids['show_id'], decoded_ids['episode_id']
+ )
+ if episode_info:
+ list_item = xbmcgui.ListItem(episode_info['name'], offscreen=True)
+ list_item = data_utils.add_episode_info(
+ list_item, episode_info, full_info=True)
+ xbmcplugin.setResolvedUrl(HANDLE, True, list_item)
+ else:
+ xbmcplugin.setResolvedUrl(
+ HANDLE, False, xbmcgui.ListItem(offscreen=True))
+
+
+def get_artwork(show_id):
+ # type: (Text) -> None
+ """
+ Get available artwork for a show
+
+ :param show_id: default unique ID set by setUniqueIDs() method
+ """
+ if not show_id:
+ return
+ logger.debug('Getting artwork for show ID {}'.format(show_id))
+ show_info = tmdb.load_show_info(show_id)
+ if show_info is not None:
+ list_item = xbmcgui.ListItem(show_info['name'], offscreen=True)
+ list_item = data_utils.set_show_artwork(show_info, list_item)
+ xbmcplugin.setResolvedUrl(HANDLE, True, list_item)
+ else:
+ xbmcplugin.setResolvedUrl(
+ HANDLE, False, xbmcgui.ListItem(offscreen=True))
+
+
+def router(paramstring):
+ # type: (Text) -> None
+ """
+ Route addon calls
+
+ :param paramstring: url-encoded query string
+ :raises RuntimeError: on unknown call action
+ """
+ params = dict(urllib.parse.parse_qsl(paramstring))
+ logger.debug('Called addon with params: {}'.format(sys.argv))
+ if params['action'] == 'find':
+ logger.debug('performing find action')
+ find_show(params['title'], params.get('year'))
+ elif params['action'].lower() == 'nfourl':
+ logger.debug('performing nfourl action')
+ get_show_id_from_nfo(params['nfo'])
+ elif params['action'] == 'getdetails':
+ logger.debug('performing getdetails action')
+ get_details(params['url'])
+ elif params['action'] == 'getepisodelist':
+ logger.debug('performing getepisodelist action')
+ get_episode_list(params['url'])
+ elif params['action'] == 'getepisodedetails':
+ logger.debug('performing getepisodedetails action')
+ get_episode_details(params['url'])
+ elif params['action'] == 'getartwork':
+ logger.debug('performing getartwork action')
+ get_artwork(params.get('id'))
+ else:
+ raise RuntimeError('Invalid addon call: {}'.format(sys.argv))
+ xbmcplugin.endOfDirectory(HANDLE)
diff --git a/addons/metadata.tvshows.themoviedb.org.python/libs/api_utils.py b/addons/metadata.tvshows.themoviedb.org.python/libs/api_utils.py
new file mode 100644
index 0000000..ce65fa3
--- /dev/null
+++ b/addons/metadata.tvshows.themoviedb.org.python/libs/api_utils.py
@@ -0,0 +1,79 @@
+# coding: utf-8
+#
+# Copyright (C) 2020, Team Kodi
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+"""Functions to interact with various web site APIs"""
+
+from __future__ import absolute_import, unicode_literals
+
+import json
+from urllib.request import Request, urlopen
+from urllib.error import URLError
+from urllib.parse import urlencode
+from pprint import pformat
+from .utils import logger
+try:
+ from typing import Text, Optional, Union, List, Dict, Any # pylint: disable=unused-import
+ InfoType = Dict[Text, Any] # pylint: disable=invalid-name
+except ImportError:
+ pass
+
+HEADERS = {}
+
+
+def set_headers(headers):
+ # type: (Dict) -> None
+ HEADERS.update(headers)
+
+
+def load_info(url, params=None, default=None, resp_type='json', verboselog=False):
+ # type: (Text, Dict, Text, Text, bool) -> Optional[Text]
+ """
+ Load info from external api
+
+ :param url: API endpoint URL
+ :param params: URL query params
+ :default: object to return if there is an error
+ :resp_type: what to return to the calling function
+ :return: API response or default on error
+ """
+ if params:
+ url = url + '?' + urlencode(params)
+ logger.debug('Calling URL "{}"'.format(url))
+ req = Request(url, headers=HEADERS)
+ try:
+ response = urlopen(req)
+ except URLError as e:
+ if hasattr(e, 'reason'):
+ logger.debug(
+ 'failed to reach the remote site\nReason: {}'.format(e.reason))
+ elif hasattr(e, 'code'):
+ logger.debug(
+ 'remote site unable to fulfill the request\nError code: {}'.format(e.code))
+ response = None
+ if response is None:
+ resp = default
+ elif resp_type.lower() == 'json':
+ try:
+ resp = json.loads(response.read().decode('utf-8'))
+ except json.decoder.JSONDecodeError:
+ logger.debug('remote site sent back bad JSON')
+ resp = default
+ else:
+ resp = response.read().decode('utf-8')
+ if verboselog:
+ logger.debug('the api response:\n{}'.format(pformat(resp)))
+ return resp
diff --git a/addons/metadata.tvshows.themoviedb.org.python/libs/cache.py b/addons/metadata.tvshows.themoviedb.org.python/libs/cache.py
new file mode 100644
index 0000000..272f339
--- /dev/null
+++ b/addons/metadata.tvshows.themoviedb.org.python/libs/cache.py
@@ -0,0 +1,81 @@
+# -*- coding: UTF-8 -*-
+#
+# Copyright (C) 2020, Team Kodi
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+# pylint: disable=missing-docstring
+#
+# This is based on the metadata.tvmaze scrapper by Roman Miroshnychenko aka Roman V.M.
+
+"""Cache-related functionality"""
+
+from __future__ import absolute_import, unicode_literals
+
+import os
+import pickle
+import xbmc
+import xbmcvfs
+
+from .utils import ADDON, logger
+
+try:
+ from typing import Optional, Text, Dict, Any # pylint: disable=unused-import
+except ImportError:
+ pass
+
+
+def _get_cache_directory(): # pylint: disable=missing-docstring
+ # type: () -> Text
+ temp_dir = xbmcvfs.translatePath('special://temp')
+ cache_dir = os.path.join(temp_dir, 'scrapers', ADDON.getAddonInfo('id'))
+ if not xbmcvfs.exists(cache_dir):
+ xbmcvfs.mkdir(cache_dir)
+ logger.debug('the cache dir is ' + cache_dir)
+ return cache_dir
+
+
+CACHE_DIR = _get_cache_directory() # type: Text
+
+
+def cache_show_info(show_info):
+ # type: (Dict[Text, Any]) -> None
+ """
+ Save show_info dict to cache
+ """
+ file_name = str(show_info['id']) + '.pickle'
+ cache = {
+ 'show_info': show_info
+ }
+ with open(os.path.join(CACHE_DIR, file_name), 'wb') as fo:
+ pickle.dump(cache, fo, protocol=2)
+
+
+def load_show_info_from_cache(show_id):
+ # type: (Text) -> Optional[Dict[Text, Any]]
+ """
+ Load show info from a local cache
+
+ :param show_id: show ID on TVmaze
+ :return: show_info dict or None
+ """
+ file_name = str(show_id) + '.pickle'
+ try:
+ with open(os.path.join(CACHE_DIR, file_name), 'rb') as fo:
+ load_kwargs = {}
+ load_kwargs['encoding'] = 'bytes'
+ cache = pickle.load(fo, **load_kwargs)
+ return cache['show_info']
+ except (IOError, pickle.PickleError) as exc:
+ logger.debug('Cache message: {} {}'.format(type(exc), exc))
+ return None
diff --git a/addons/metadata.tvshows.themoviedb.org.python/libs/data_utils.py b/addons/metadata.tvshows.themoviedb.org.python/libs/data_utils.py
new file mode 100644
index 0000000..779789a
--- /dev/null
+++ b/addons/metadata.tvshows.themoviedb.org.python/libs/data_utils.py
@@ -0,0 +1,451 @@
+# -*- coding: UTF-8 -*-
+#
+# Copyright (C) 2020, Team Kodi
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+# pylint: disable=missing-docstring
+#
+# This is based on the metadata.tvmaze scrapper by Roman Miroshnychenko aka Roman V.M.
+
+"""Functions to process data"""
+
+from __future__ import absolute_import, unicode_literals
+
+import re
+import json
+from xbmc import Actor, VideoStreamDetail
+from collections import namedtuple
+from .utils import safe_get, logger
+from . import settings, api_utils
+
+try:
+ from typing import Optional, Tuple, Text, Dict, List, Any # pylint: disable=unused-import
+ from xbmcgui import ListItem # pylint: disable=unused-import
+ InfoType = Dict[Text, Any] # pylint: disable=invalid-name
+except ImportError:
+ pass
+
+TMDB_PARAMS = {'api_key': settings.TMDB_CLOWNCAR, 'language': settings.LANG}
+BASE_URL = 'https://api.themoviedb.org/3/{}'
+FIND_URL = BASE_URL.format('find/{}')
+TAG_RE = re.compile(r'<[^>]+>')
+
+# Regular expressions are listed in order of priority.
+# "TMDB" provider is preferred than other providers (IMDB and TheTVDB),
+# because external providers IDs need to be converted to TMDB_ID.
+SHOW_ID_REGEXPS = (
+ r'(themoviedb)\.org/tv/(\d+).*/episode_group/(.*)', # TMDB_http_link
+ r'(themoviedb)\.org/tv/(\d+)', # TMDB_http_link
+ r'(themoviedb)\.org/./tv/(\d+)', # TMDB_http_link
+ r'(tmdb)\.org/./tv/(\d+)', # TMDB_http_link
+ r'(imdb)\.com/.+/(tt\d+)', # IMDB_http_link
+ r'(thetvdb)\.com.+&id=(\d+)', # TheTVDB_http_link
+ r'(thetvdb)\.com/series/(\d+)', # TheTVDB_http_link
+ r'(thetvdb)\.com/api/.*series/(\d+)', # TheTVDB_http_link
+ r'(thetvdb)\.com/.*?"id":(\d+)', # TheTVDB_http_link
+ r'<uniqueid.+?type="(tvdb|imdb)".*?>([t\d]+?)</uniqueid>'
+)
+
+
+SUPPORTED_ARTWORK_TYPES = {'poster', 'banner'}
+IMAGE_SIZES = ('large', 'original', 'medium')
+CLEAN_PLOT_REPLACEMENTS = (
+ ('<b>', '[B]'),
+ ('</b>', '[/B]'),
+ ('<i>', '[I]'),
+ ('</i>', '[/I]'),
+ ('</p><p>', '[CR]'),
+)
+VALIDEXTIDS = ['tmdb_id', 'imdb_id', 'tvdb_id']
+
+UrlParseResult = namedtuple(
+ 'UrlParseResult', ['provider', 'show_id', 'ep_grouping'])
+
+
+def _clean_plot(plot):
+ # type: (Text) -> Text
+ """Replace HTML tags with Kodi skin tags"""
+ for repl in CLEAN_PLOT_REPLACEMENTS:
+ plot = plot.replace(repl[0], repl[1])
+ plot = TAG_RE.sub('', plot)
+ return plot
+
+
+def _set_cast(cast_info, vtag):
+ # type: (InfoType, ListItem) -> ListItem
+ """Save cast info to list item"""
+ cast = []
+ for item in cast_info:
+ actor = {
+ 'name': item['name'],
+ 'role': item.get('character', item.get('character_name', '')),
+ 'order': item['order'],
+ }
+ thumb = None
+ if safe_get(item, 'profile_path') is not None:
+ thumb = settings.IMAGEROOTURL + item['profile_path']
+ cast.append(Actor(actor['name'], actor['role'], actor['order'], thumb))
+ vtag.setCast(cast)
+
+
+def _get_credits(show_info):
+ # type: (InfoType) -> List[Text]
+ """Extract show creator(s) and writer(s) from show info"""
+ credits = []
+ for item in show_info.get('created_by', []):
+ credits.append(item['name'])
+ for item in show_info.get('credits', {}).get('crew', []):
+ isWriter = item.get('job', '').lower() == 'writer' or item.get(
+ 'department', '').lower() == 'writing'
+ if isWriter and item.get('name') not in credits:
+ credits.append(item['name'])
+ return credits
+
+
+def _get_directors(episode_info):
+ # type: (InfoType) -> List[Text]
+ """Extract episode writer(s) from episode info"""
+ directors_ = []
+ for item in episode_info.get('credits', {}).get('crew', []):
+ if item.get('job') == 'Director':
+ directors_.append(item['name'])
+ return directors_
+
+
+def _set_unique_ids(ext_ids, vtag):
+ # type: (Dict, ListItem) -> ListItem
+ """Extract unique ID in various online databases"""
+ return_ids = {}
+ for key, value in ext_ids.items():
+ if key in VALIDEXTIDS and value:
+ if key == 'tmdb_id':
+ isTMDB = True
+ else:
+ isTMDB = False
+ shortkey = key[:-3]
+ str_value = str(value)
+ vtag.setUniqueID(str_value, type=shortkey, isdefault=isTMDB)
+ return_ids[shortkey] = str_value
+ return return_ids
+
+
+def _set_rating(the_info, vtag):
+ # type: (InfoType, ListItem) -> None
+ """Set show/episode rating"""
+ first = True
+ for rating_type in settings.RATING_TYPES:
+ logger.debug('adding rating type of %s' % rating_type)
+ rating = float(the_info.get('ratings', {}).get(
+ rating_type, {}).get('rating', '0'))
+ votes = int(the_info.get('ratings', {}).get(
+ rating_type, {}).get('votes', '0'))
+ logger.debug("adding rating of %s and votes of %s" %
+ (str(rating), str(votes)))
+ if rating > 0:
+ vtag.setRating(rating, votes=votes,
+ type=rating_type, isdefault=first)
+ first = False
+
+
+def _add_season_info(show_info, vtag):
+ # type: (InfoType, ListItem) -> None
+ """Add info for show seasons"""
+ for season in show_info['seasons']:
+ logger.debug('adding information for season %s to list item' %
+ season['season_number'])
+ vtag.addSeason(season['season_number'],
+ safe_get(season, 'name', ''))
+ for image_type, image_list in season.get('images', {}).items():
+ if image_type == 'posters':
+ destination = 'poster'
+ else:
+ destination = image_type
+ for image in image_list:
+ theurl, previewurl = get_image_urls(image)
+ if theurl:
+ vtag.addAvailableArtwork(
+ theurl, arttype=destination, preview=previewurl, season=season['season_number'])
+
+
+def get_image_urls(image):
+ # type: (Dict) -> Tuple[Text, Text]
+ """Get image URLs from image information"""
+ if image.get('file_path', '').endswith('.svg'):
+ return None, None
+ if image.get('type') == 'fanarttv':
+ theurl = image['file_path']
+ previewurl = theurl.replace(
+ '.fanart.tv/fanart/', '.fanart.tv/preview/')
+ else:
+ theurl = settings.IMAGEROOTURL + image['file_path']
+ previewurl = settings.PREVIEWROOTURL + image['file_path']
+ return theurl, previewurl
+
+
+def set_show_artwork(show_info, list_item):
+ # type: (InfoType, ListItem) -> ListItem
+ """Set available images for a show"""
+ vtag = list_item.getVideoInfoTag()
+ for image_type, image_list in show_info.get('images', {}).items():
+ if image_type == 'backdrops':
+ fanart_list = []
+ for image in image_list:
+ theurl, previewurl = get_image_urls(image)
+ if image.get('iso_639_1') != None and settings.CATLANDSCAPE and theurl:
+ vtag.addAvailableArtwork(
+ theurl, arttype="landscape", preview=previewurl)
+ elif theurl:
+ fanart_list.append({'image': theurl})
+ if fanart_list:
+ list_item.setAvailableFanart(fanart_list)
+ else:
+ if image_type == 'posters':
+ destination = 'poster'
+ elif image_type == 'logos':
+ destination = 'clearlogo'
+ else:
+ destination = image_type
+ for image in image_list:
+ theurl, previewurl = get_image_urls(image)
+ if theurl:
+ vtag.addAvailableArtwork(
+ theurl, arttype=destination, preview=previewurl)
+ return list_item
+
+
+def add_main_show_info(list_item, show_info, full_info=True):
+ # type: (ListItem, InfoType, bool) -> ListItem
+ """Add main show info to a list item"""
+ vtag = list_item.getVideoInfoTag()
+ original_name = show_info.get('original_name')
+ if settings.KEEPTITLE and original_name:
+ showname = original_name
+ else:
+ showname = show_info['name']
+ plot = _clean_plot(safe_get(show_info, 'overview', ''))
+ vtag.setTitle(showname)
+ vtag.setOriginalTitle(original_name)
+ vtag.setTvShowTitle(showname)
+ vtag.setPlot(plot)
+ vtag.setPlotOutline(plot)
+ vtag.setMediaType('tvshow')
+ ext_ids = {'tmdb_id': show_info['id']}
+ ext_ids.update(show_info.get('external_ids', {}))
+ epguide_ids = _set_unique_ids(ext_ids, vtag)
+ vtag.setEpisodeGuide(json.dumps(epguide_ids))
+ if show_info.get('first_air_date'):
+ vtag.setYear(int(show_info['first_air_date'][:4]))
+ vtag.setPremiered(show_info['first_air_date'])
+ if full_info:
+ vtag.setTvShowStatus(safe_get(show_info, 'status', ''))
+ genre_list = safe_get(show_info, 'genres', {})
+ genres = []
+ for genre in genre_list:
+ genres.append(genre['name'])
+ vtag.setGenres(genres)
+ networks = show_info.get('networks', [])
+ if networks:
+ network = networks[0]
+ country = network.get('origin_country', '')
+ else:
+ network = None
+ country = None
+ if network and country and settings.STUDIOCOUNTRY:
+ vtag.setStudios(['{0} ({1})'.format(network['name'], country)])
+ elif network:
+ vtag.setStudios([network['name']])
+ if country:
+ vtag.setCountries([country])
+ content_ratings = show_info.get(
+ 'content_ratings', {}).get('results', {})
+ if content_ratings:
+ mpaa = ''
+ mpaa_backup = ''
+ for content_rating in content_ratings:
+ iso = content_rating.get('iso_3166_1', '').lower()
+ if iso == 'us':
+ mpaa_backup = content_rating.get('rating')
+ if iso == settings.CERT_COUNTRY.lower():
+ mpaa = content_rating.get('rating', '')
+ if not mpaa:
+ mpaa = mpaa_backup
+ if mpaa:
+ vtag.setMpaa(settings.CERT_PREFIX + mpaa)
+ vtag.setWriters(_get_credits(show_info))
+ if settings.ENABTRAILER:
+ trailer = _parse_trailer(show_info.get(
+ 'videos', {}).get('results', {}))
+ if trailer:
+ vtag.setTrailer(trailer)
+ list_item = set_show_artwork(show_info, list_item)
+ _add_season_info(show_info, vtag)
+ _set_cast(show_info['credits']['cast'], vtag)
+ _set_rating(show_info, vtag)
+ else:
+ image = show_info.get('poster_path', '')
+ if image and not image.endswith('.svg'):
+ theurl = settings.IMAGEROOTURL + image
+ previewurl = settings.PREVIEWROOTURL + image
+ vtag.addAvailableArtwork(
+ theurl, arttype='poster', preview=previewurl)
+ logger.debug('adding tv show information for %s to list item' % showname)
+ return list_item
+
+
+def add_episode_info(list_item, episode_info, full_info=True):
+ # type: (ListItem, InfoType, bool) -> ListItem
+ """Add episode info to a list item"""
+ title = episode_info.get('name', 'Episode ' +
+ str(episode_info['episode_number']))
+ vtag = list_item.getVideoInfoTag()
+ vtag.setTitle(title)
+ vtag.setSeason(episode_info['season_number'])
+ vtag.setEpisode(episode_info['episode_number'])
+ vtag.setMediaType('episode')
+ if safe_get(episode_info, 'air_date') is not None:
+ vtag.setFirstAired(episode_info['air_date'])
+ if full_info:
+ summary = safe_get(episode_info, 'overview')
+ if summary is not None:
+ plot = _clean_plot(summary)
+ vtag.setPlot(plot)
+ vtag.setPlotOutline(plot)
+ if safe_get(episode_info, 'air_date') is not None:
+ vtag.setPremiered(episode_info['air_date'])
+ duration = episode_info.get('runtime')
+ if duration:
+ videostream = VideoStreamDetail(duration=int(duration)*60)
+ vtag.addVideoStream(videostream)
+ _set_cast(
+ episode_info['season_cast'] + episode_info['credits']['guest_stars'], vtag)
+ ext_ids = {'tmdb_id': episode_info['id']}
+ ext_ids.update(episode_info.get('external_ids', {}))
+ _set_unique_ids(ext_ids, vtag)
+ _set_rating(episode_info, vtag)
+ for image in episode_info.get('images', {}).get('stills', []):
+ theurl, previewurl = get_image_urls(image)
+ if theurl:
+ vtag.addAvailableArtwork(
+ theurl, arttype='thumb', preview=previewurl)
+ vtag.setWriters(_get_credits(episode_info))
+ vtag.setDirectors(_get_directors(episode_info))
+ logger.debug('adding episode information for S%sE%s - %s to list item' %
+ (episode_info['season_number'], episode_info['episode_number'], title))
+ return list_item
+
+
+def parse_nfo_url(nfo):
+ # type: (Text) -> Optional[UrlParseResult]
+ """Extract show ID and named seasons from NFO file contents"""
+ # work around for xbmcgui.ListItem.addSeason overwriting named seasons from NFO files
+ ns_regex = r'<namedseason number="(.*)">(.*)</namedseason>'
+ ns_match = re.findall(ns_regex, nfo, re.I)
+ sid_match = None
+ ep_grouping = None
+ for regexp in SHOW_ID_REGEXPS:
+ logger.debug('trying regex to match service from parsing nfo:')
+ logger.debug(regexp)
+ show_id_match = re.search(regexp, nfo, re.I)
+ if show_id_match:
+ logger.debug('match group 1: ' + show_id_match.group(1))
+ logger.debug('match group 2: ' + show_id_match.group(2))
+ if show_id_match.group(1) == "themoviedb" or show_id_match.group(1) == "tmdb":
+ try:
+ ep_grouping = show_id_match.group(3)
+ except IndexError:
+ pass
+ tmdb_id = show_id_match.group(2)
+ else:
+ tmdb_id = _convert_ext_id(
+ show_id_match.group(1), show_id_match.group(2))
+ if tmdb_id:
+ logger.debug('match group 3: ' + str(ep_grouping))
+ sid_match = UrlParseResult('tmdb', tmdb_id, ep_grouping)
+ break
+ return sid_match, ns_match
+
+
+def _convert_ext_id(ext_provider, ext_id):
+ # type: (Text, Text) -> Text
+ """get a TMDb ID from an external ID"""
+ providers_dict = {'imdb': 'imdb_id',
+ 'thetvdb': 'tvdb_id',
+ 'tvdb': 'tvdb_id'}
+ show_url = FIND_URL.format(ext_id)
+ params = TMDB_PARAMS.copy()
+ provider = providers_dict.get(ext_provider)
+ if provider:
+ params['external_source'] = provider
+ show_info = api_utils.load_info(show_url, params=params)
+ else:
+ show_info = None
+ if show_info:
+ tv_results = show_info.get('tv_results')
+ if tv_results:
+ return tv_results[0].get('id')
+ return None
+
+
+def parse_media_id(title):
+ # type: (Text) -> Dict
+ """get the ID from a title and return with the type"""
+ title = title.lower()
+ if title.startswith('tt') and title[2:].isdigit():
+ # IMDB ID works alone because it is clear
+ return {'type': 'imdb_id', 'title': title}
+ # IMDB ID with prefix to match
+ elif title.startswith('imdb/tt') and title[7:].isdigit():
+ # IMDB ID works alone because it is clear
+ return {'type': 'imdb_id', 'title': title[5:]}
+ elif title.startswith('tmdb/') and title[5:].isdigit(): # TMDB ID
+ return {'type': 'tmdb_id', 'title': title[5:]}
+ elif title.startswith('tvdb/') and title[5:].isdigit(): # TVDB ID
+ return {'type': 'tvdb_id', 'title': title[5:]}
+ return None
+
+
+def _parse_trailer(results):
+ # type: (Text) -> Text
+ """create a valid Tubed or YouTube plugin trailer URL"""
+ if results:
+ if settings.PLAYERSOPT == 'tubed':
+ addon_player = 'plugin://plugin.video.tubed/?mode=play&video_id='
+ elif settings.PLAYERSOPT == 'youtube':
+ addon_player = 'plugin://plugin.video.youtube/?action=play_video&videoid='
+ backup_keys = []
+ for video_lang in [settings.LANG[0:2], 'en']:
+ for result in results:
+ if result.get('site') == 'YouTube' and result.get('iso_639_1') == video_lang:
+ key = result.get('key')
+ if result.get('type') == 'Trailer':
+ if _check_youtube(key):
+ # video is available and is defined as "Trailer" by TMDB. Perfect link!
+ return addon_player+key
+ else:
+ # video is available, but NOT defined as "Trailer" by TMDB. Saving it as backup in case it doesn't find any perfect link.
+ backup_keys.append(key)
+ for keybackup in backup_keys:
+ if _check_youtube(keybackup):
+ return addon_player+keybackup
+ return None
+
+
+def _check_youtube(key):
+ # type: (Text) -> bool
+ """check to see if the YouTube key returns a valid link"""
+ chk_link = "https://www.youtube.com/watch?v="+key
+ check = api_utils.load_info(chk_link, resp_type='not_json')
+ if not check or "Video unavailable" in check: # video not available
+ return False
+ return True
diff --git a/addons/metadata.tvshows.themoviedb.org.python/libs/debugger.py b/addons/metadata.tvshows.themoviedb.org.python/libs/debugger.py
new file mode 100644
index 0000000..6414722
--- /dev/null
+++ b/addons/metadata.tvshows.themoviedb.org.python/libs/debugger.py
@@ -0,0 +1,115 @@
+# -*- coding: UTF-8 -*-
+#
+# Copyright (C) 2020, Team Kodi
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+# pylint: disable=missing-docstring
+#
+# This is based on the metadata.tvmaze scrapper by Roman Miroshnychenko aka Roman V.M.
+
+"""
+Provides a context manager that writes extended debugging info
+in the Kodi log on unhandled exceptions
+"""
+from __future__ import absolute_import, unicode_literals
+
+import inspect
+from contextlib import contextmanager
+from platform import uname
+from pprint import pformat
+
+import xbmc
+
+from .utils import logger
+
+try:
+ from typing import Text, Generator, Callable, Dict, Any # pylint: disable=unused-import
+except ImportError:
+ pass
+
+
+def _format_vars(variables):
+ # type: (Dict[Text, Any]) -> Text
+ """
+ Format variables dictionary
+
+ :param variables: variables dict
+ :type variables: dict
+ :return: formatted string with sorted ``var = val`` pairs
+ :rtype: str
+ """
+ var_list = [(var, val) for var, val in variables.items()
+ if not (var.startswith('__') or var.endswith('__'))]
+ var_list.sort(key=lambda i: i[0])
+ lines = []
+ for var, val in var_list:
+ lines.append('{0} = {1}'.format(var, pformat(val)))
+ return '\n'.join(lines)
+
+
+@contextmanager
+def debug_exception(logger_func=logger.error):
+ # type: (Callable[[Text], None]) -> Generator[None]
+ """
+ Diagnostic helper context manager
+
+ It controls execution within its context and writes extended
+ diagnostic info to the Kodi log if an unhandled exception
+ happens within the context. The info includes the following items:
+
+ - System info
+ - Kodi version
+ - Module path.
+ - Code fragment where the exception has happened.
+ - Global variables.
+ - Local variables.
+
+ After logging the diagnostic info the exception is re-raised.
+
+ Example::
+
+ with debug_exception():
+ # Some risky code
+ raise RuntimeError('Fatal error!')
+
+ :param logger_func: logger function which must accept a single argument
+ which is a log message.
+ """
+ try:
+ yield
+ except Exception as exc:
+ frame_info = inspect.trace(5)[-1]
+ logger_func(
+ '*** Unhandled exception detected: {} {} ***'.format(type(exc), exc))
+ logger_func('*** Start diagnostic info ***')
+ logger_func('System info: {0}'.format(uname()))
+ logger_func('OS info: {0}'.format(
+ xbmc.getInfoLabel('System.OSVersionInfo')))
+ logger_func('Kodi version: {0}'.format(
+ xbmc.getInfoLabel('System.BuildVersion')))
+ logger_func('File: {0}'.format(frame_info[1]))
+ context = ''
+ if frame_info[4] is not None:
+ for i, line in enumerate(frame_info[4], frame_info[2] - frame_info[5]):
+ if i == frame_info[2]:
+ context += '{0}:>{1}'.format(str(i).rjust(5), line)
+ else:
+ context += '{0}: {1}'.format(str(i).rjust(5), line)
+ logger_func('Code context:\n' + context)
+ logger_func('Global variables:\n' +
+ _format_vars(frame_info[0].f_globals))
+ logger_func('Local variables:\n' +
+ _format_vars(frame_info[0].f_locals))
+ logger_func('**** End diagnostic info ****')
+ raise exc
diff --git a/addons/metadata.tvshows.themoviedb.org.python/libs/imdbratings.py b/addons/metadata.tvshows.themoviedb.org.python/libs/imdbratings.py
new file mode 100644
index 0000000..f74f0a4
--- /dev/null
+++ b/addons/metadata.tvshows.themoviedb.org.python/libs/imdbratings.py
@@ -0,0 +1,72 @@
+# -*- coding: UTF-8 -*-
+#
+# Copyright (C) 2020, Team Kodi
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+#
+# IMDb ratings based on code in metadata.themoviedb.org.python by Team Kodi
+# pylint: disable=missing-docstring
+
+
+import re
+import json
+from . import api_utils
+from . import settings
+try:
+ from typing import Optional, Tuple, Text, Dict, List, Any # pylint: disable=unused-import
+except ImportError:
+ pass
+
+IMDB_RATINGS_URL = 'https://www.imdb.com/title/{}/'
+IMDB_JSON_REGEX = re.compile(
+ r'<script type="application\/ld\+json">(.*?)<\/script>')
+
+
+def get_details(imdb_id):
+ # type: (Text) -> Dict
+ """get the IMDB ratings details"""
+ if not imdb_id:
+ return {}
+ votes, rating = _get_ratinginfo(imdb_id)
+ return _assemble_imdb_result(votes, rating)
+
+
+def _get_ratinginfo(imdb_id):
+ # type: (Text) -> Tuple[Text, Text]
+ """get the IMDB ratings details"""
+ response = api_utils.load_info(IMDB_RATINGS_URL.format(
+ imdb_id), default='', resp_type='text', verboselog=settings.VERBOSELOG)
+ return _parse_imdb_result(response)
+
+
+def _assemble_imdb_result(votes, rating):
+ # type: (Text, Text) -> Dict
+ """assemble to IMDB ratings into a Dict"""
+ result = {}
+ if votes and rating:
+ result['ratings'] = {'imdb': {'votes': votes, 'rating': rating}}
+ return result
+
+
+def _parse_imdb_result(input_html):
+ # type: (Text) -> Tuple[Text, Text]
+ """parse the IMDB ratings from the JSON in the raw HTML"""
+ match = re.search(IMDB_JSON_REGEX, input_html)
+ if not match:
+ return None, None
+ imdb_json = json.loads(match.group(1))
+ imdb_ratings = imdb_json.get("aggregateRating", {})
+ rating = imdb_ratings.get("ratingValue", None)
+ votes = imdb_ratings.get("ratingCount", None)
+ return votes, rating
diff --git a/addons/metadata.tvshows.themoviedb.org.python/libs/settings.py b/addons/metadata.tvshows.themoviedb.org.python/libs/settings.py
new file mode 100644
index 0000000..3d6cf7d
--- /dev/null
+++ b/addons/metadata.tvshows.themoviedb.org.python/libs/settings.py
@@ -0,0 +1,111 @@
+# -*- coding: UTF-8 -*-
+#
+# Copyright (C) 2020, Team Kodi
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+# pylint: disable=missing-docstring
+
+import json
+import sys
+import urllib.parse
+from .utils import logger
+from . import api_utils
+from xbmcaddon import Addon
+from datetime import datetime, timedelta
+
+
+def _get_date_numeric(datetime_):
+ return (datetime_ - datetime(1970, 1, 1)).total_seconds()
+
+
+def _get_configuration():
+ logger.debug('getting configuration details')
+ return api_utils.load_info('https://api.themoviedb.org/3/configuration', params={'api_key': TMDB_CLOWNCAR}, verboselog=VERBOSELOG)
+
+
+def _load_base_urls():
+ image_root_url = ADDON.getSettingString('originalUrl')
+ preview_root_url = ADDON.getSettingString('previewUrl')
+ last_updated = ADDON.getSettingString('lastUpdated')
+ if not image_root_url or not preview_root_url or not last_updated or \
+ float(last_updated) < _get_date_numeric(datetime.now() - timedelta(days=30)):
+ conf = _get_configuration()
+ if conf:
+ image_root_url = conf['images']['secure_base_url'] + 'original'
+ preview_root_url = conf['images']['secure_base_url'] + 'w780'
+ ADDON.setSetting('originalUrl', image_root_url)
+ ADDON.setSetting('previewUrl', preview_root_url)
+ ADDON.setSetting('lastUpdated', str(
+ _get_date_numeric(datetime.now())))
+ return image_root_url, preview_root_url
+
+
+ADDON = Addon()
+TMDB_CLOWNCAR = 'af3a53eb387d57fc935e9128468b1899'
+FANARTTV_CLOWNCAR = 'b018086af0e1478479adfc55634db97d'
+TRAKT_CLOWNCAR = '90901c6be3b2de5a4fa0edf9ab5c75e9a5a0fef2b4ee7373d8b63dcf61f95697'
+MAXIMAGES = 200
+FANARTTV_MAPPING = {'showbackground': 'backdrops',
+ 'tvposter': 'posters',
+ 'tvbanner': 'banner',
+ 'hdtvlogo': 'clearlogo',
+ 'clearlogo': 'clearlogo',
+ 'hdclearart': 'clearart',
+ 'clearart': 'clearart',
+ 'tvthumb': 'landscape',
+ 'characterart': 'characterart',
+ 'seasonposter': 'seasonposters',
+ 'seasonbanner': 'seasonbanner',
+ 'seasonthumb': 'seasonlandscape'
+ }
+
+try:
+ source_params = dict(urllib.parse.parse_qsl(sys.argv[2]))
+except IndexError:
+ source_params = {}
+source_settings = json.loads(source_params.get('pathSettings', '{}'))
+
+KEEPTITLE = source_settings.get(
+ 'keeporiginaltitle', ADDON.getSettingBool('keeporiginaltitle'))
+CATLANDSCAPE = source_settings.get('cat_landscape', True)
+STUDIOCOUNTRY = source_settings.get('studio_country', False)
+ENABTRAILER = source_settings.get(
+ 'enab_trailer', ADDON.getSettingBool('enab_trailer'))
+PLAYERSOPT = source_settings.get(
+ 'players_opt', ADDON.getSettingString('players_opt')).lower()
+VERBOSELOG = source_settings.get(
+ 'verboselog', ADDON.getSettingBool('verboselog'))
+LANG = source_settings.get('language', ADDON.getSettingString('language'))
+CERT_COUNTRY = source_settings.get(
+ 'tmdbcertcountry', ADDON.getSettingString('tmdbcertcountry')).lower()
+IMAGEROOTURL, PREVIEWROOTURL = _load_base_urls()
+
+if source_settings.get('usecertprefix', ADDON.getSettingBool('usecertprefix')):
+ CERT_PREFIX = source_settings.get(
+ 'certprefix', ADDON.getSettingString('certprefix'))
+else:
+ CERT_PREFIX = ''
+primary_rating = source_settings.get(
+ 'ratings', ADDON.getSettingString('ratings')).lower()
+RATING_TYPES = [primary_rating]
+if source_settings.get('imdbanyway', ADDON.getSettingBool('imdbanyway')) and primary_rating != 'imdb':
+ RATING_TYPES.append('imdb')
+if source_settings.get('traktanyway', ADDON.getSettingBool('traktanyway')) and primary_rating != 'trakt':
+ RATING_TYPES.append('trakt')
+if source_settings.get('tmdbanyway', ADDON.getSettingBool('tmdbanyway')) and primary_rating != 'tmdb':
+ RATING_TYPES.append('tmdb')
+FANARTTV_ENABLE = source_settings.get(
+ 'enable_fanarttv', ADDON.getSettingBool('enable_fanarttv'))
+FANARTTV_CLIENTKEY = source_settings.get(
+ 'fanarttv_clientkey', ADDON.getSettingString('fanarttv_clientkey'))
diff --git a/addons/metadata.tvshows.themoviedb.org.python/libs/tmdb.py b/addons/metadata.tvshows.themoviedb.org.python/libs/tmdb.py
new file mode 100644
index 0000000..3b5019f
--- /dev/null
+++ b/addons/metadata.tvshows.themoviedb.org.python/libs/tmdb.py
@@ -0,0 +1,466 @@
+# -*- coding: UTF-8 -*-
+#
+# Copyright (C) 2020, Team Kodi
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+# pylint: disable=missing-docstring
+
+"""Functions to interact with TMDb API"""
+
+from __future__ import absolute_import, unicode_literals
+
+import unicodedata
+from math import floor
+from pprint import pformat
+from . import cache, data_utils, api_utils, settings, imdbratings, traktratings
+from .utils import logger
+try:
+ from typing import Text, Optional, Union, List, Dict, Any # pylint: disable=unused-import
+ InfoType = Dict[Text, Any] # pylint: disable=invalid-name
+except ImportError:
+ pass
+
+HEADERS = (
+ ('User-Agent', 'Kodi TV Show scraper by Team Kodi; contact pkscout@kodi.tv'),
+ ('Accept', 'application/json'),
+)
+api_utils.set_headers(dict(HEADERS))
+
+TMDB_PARAMS = {'api_key': settings.TMDB_CLOWNCAR, 'language': settings.LANG}
+BASE_URL = 'https://api.themoviedb.org/3/{}'
+EPISODE_GROUP_URL = BASE_URL.format('tv/episode_group/{}')
+SEARCH_URL = BASE_URL.format('search/tv')
+FIND_URL = BASE_URL.format('find/{}')
+SHOW_URL = BASE_URL.format('tv/{}')
+SEASON_URL = BASE_URL.format('tv/{}/season/{}')
+EPISODE_URL = BASE_URL.format('tv/{}/season/{}/episode/{}')
+FANARTTV_URL = 'https://webservice.fanart.tv/v3/tv/{}'
+FANARTTV_PARAMS = {'api_key': settings.FANARTTV_CLOWNCAR}
+if settings.FANARTTV_CLIENTKEY:
+ FANARTTV_PARAMS['client_key'] = settings.FANARTTV_CLIENTKEY
+
+
+def search_show(title, year=None):
+ # type: (Text, Text) -> List
+ """
+ Search for a single TV show
+
+ :param title: TV show title to search
+ : param year: the year to search (optional)
+ :return: a list with found TV shows
+ """
+ params = TMDB_PARAMS.copy()
+ results = []
+ ext_media_id = data_utils.parse_media_id(title)
+ if ext_media_id:
+ logger.debug('using %s of %s to find show' %
+ (ext_media_id['type'], ext_media_id['title']))
+ if ext_media_id['type'] == 'tmdb_id':
+ search_url = SHOW_URL.format(ext_media_id['title'])
+ else:
+ search_url = FIND_URL.format(ext_media_id['title'])
+ params['external_source'] = ext_media_id['type']
+ else:
+ logger.debug('using title of %s to find show' % title)
+ search_url = SEARCH_URL
+ params['query'] = unicodedata.normalize('NFKC', title)
+ if year:
+ params['first_air_date_year'] = str(year)
+ resp = api_utils.load_info(
+ search_url, params=params, verboselog=settings.VERBOSELOG)
+ if resp is not None:
+ if ext_media_id:
+ if ext_media_id['type'] == 'tmdb_id':
+ if resp.get('success') == 'false':
+ results = []
+ else:
+ results = [resp]
+ else:
+ results = resp.get('tv_results', [])
+ else:
+ results = resp.get('results', [])
+ return results
+
+
+def load_episode_list(show_info, season_map, ep_grouping):
+ # type: (InfoType, Dict, Text) -> Optional[InfoType]
+ """get the IMDB ratings details"""
+ """Load episode list from themoviedb.org API"""
+ episode_list = []
+ if ep_grouping is not None:
+ logger.debug(
+ 'Getting episodes with episode grouping of ' + ep_grouping)
+ episode_group_url = EPISODE_GROUP_URL.format(ep_grouping)
+ custom_order = api_utils.load_info(
+ episode_group_url, params=TMDB_PARAMS, verboselog=settings.VERBOSELOG)
+ if custom_order is not None:
+ show_info['seasons'] = []
+ for custom_season in custom_order.get('groups', []):
+ season_episodes = []
+ try:
+ current_season = season_map.get(
+ str(custom_season['episodes'][0]['season_number']), {}).copy()
+ except IndexError:
+ continue
+ current_season['name'] = custom_season['name']
+ current_season['season_number'] = custom_season['order']
+ for episode in custom_season['episodes']:
+ episode['org_seasonnum'] = episode['season_number']
+ episode['org_epnum'] = episode['episode_number']
+ episode['season_number'] = custom_season['order']
+ episode['episode_number'] = episode['order'] + 1
+ season_episodes.append(episode)
+ episode_list.append(episode)
+ current_season['episodes'] = season_episodes
+ show_info['seasons'].append(current_season)
+ else:
+ logger.debug('Getting episodes from standard season list')
+ show_info['seasons'] = []
+ for key, value in season_map.items():
+ show_info['seasons'].append(value)
+ for season in show_info.get('seasons', []):
+ for episode in season.get('episodes', []):
+ episode['org_seasonnum'] = episode['season_number']
+ episode['org_epnum'] = episode['episode_number']
+ episode_list.append(episode)
+ show_info['episodes'] = episode_list
+ return show_info
+
+
+def load_show_info(show_id, ep_grouping=None, named_seasons=None):
+ # type: (Text, Text, Dict) -> Optional[InfoType]
+ """
+ Get full info for a single show
+
+ :param show_id: themoviedb.org show ID
+ :param ep_grouping: the episode group from TMDb
+ :param named_seasons: the named seasons from the NFO file
+ :return: show info or None
+ """
+ if named_seasons == None:
+ named_seasons = []
+ show_info = cache.load_show_info_from_cache(show_id)
+ if show_info is None:
+ logger.debug('no cache file found, loading from scratch')
+ show_url = SHOW_URL.format(show_id)
+ params = TMDB_PARAMS.copy()
+ params['append_to_response'] = 'credits,content_ratings,external_ids,images,videos'
+ params['include_image_language'] = '%s,en,null' % settings.LANG[0:2]
+ params['include_video_language'] = '%s,en,null' % settings.LANG[0:2]
+ show_info = api_utils.load_info(
+ show_url, params=params, verboselog=settings.VERBOSELOG)
+ if show_info is None:
+ return None
+ if show_info['overview'] == '' and settings.LANG != 'en-US':
+ params['language'] = 'en-US'
+ del params['append_to_response']
+ show_info_backup = api_utils.load_info(
+ show_url, params=params, verboselog=settings.VERBOSELOG)
+ if show_info_backup is not None:
+ show_info['overview'] = show_info_backup.get('overview', '')
+ params['language'] = settings.LANG
+ season_map = {}
+ params['append_to_response'] = 'credits,images'
+ for season in show_info.get('seasons', []):
+ season_url = SEASON_URL.format(
+ show_id, season.get('season_number', 0))
+ season_info = api_utils.load_info(
+ season_url, params=params, default={}, verboselog=settings.VERBOSELOG)
+ if (season_info.get('overview', '') == '' or season_info.get('name', '').lower().startswith('season')) and settings.LANG != 'en-US':
+ params['language'] = 'en-US'
+ season_info_backup = api_utils.load_info(
+ season_url, params=params, default={}, verboselog=settings.VERBOSELOG)
+ params['language'] = settings.LANG
+ if season_info.get('overview', '') == '':
+ season_info['overview'] = season_info_backup.get(
+ 'overview', '')
+ if season_info.get('name', '').lower().startswith('season'):
+ season_info['name'] = season_info_backup.get('name', '')
+ # this is part of a work around for xbmcgui.ListItem.addSeasons() not respecting NFO file information
+ for named_season in named_seasons:
+ if str(named_season[0]) == str(season.get('season_number')):
+ logger.debug('adding season name of %s from named seasons in NFO for season %s' % (
+ named_season[1], season['season_number']))
+ season_info['name'] = named_season[1]
+ break
+ # end work around
+ season_info['images'] = _sort_image_types(
+ season_info.get('images', {}))
+ season_map[str(season.get('season_number', 0))] = season_info
+ show_info = load_episode_list(show_info, season_map, ep_grouping)
+ show_info['ratings'] = load_ratings(show_info)
+ show_info = load_fanarttv_art(show_info)
+ show_info['images'] = _sort_image_types(show_info.get('images', {}))
+ show_info = trim_artwork(show_info)
+ cast_check = []
+ cast = []
+ for season in reversed(show_info.get('seasons', [])):
+ for cast_member in season.get('credits', {}).get('cast', []):
+ if cast_member.get('name', '') not in cast_check:
+ cast.append(cast_member)
+ cast_check.append(cast_member.get('name', ''))
+ show_info['credits']['cast'] = cast
+ logger.debug('saving show info to the cache')
+ if settings.VERBOSELOG:
+ logger.debug(format(pformat(show_info)))
+ cache.cache_show_info(show_info)
+ else:
+ logger.debug('using cached show info')
+ return show_info
+
+
+def load_episode_info(show_id, episode_id):
+ # type: (Text, Text) -> Optional[InfoType]
+ """
+ Load episode info
+
+ :param show_id:
+ :param episode_id:
+ :return: episode info or None
+ """
+ show_info = load_show_info(show_id)
+ if show_info is not None:
+ try:
+ episode_info = show_info['episodes'][int(episode_id)]
+ except KeyError:
+ return None
+ # this ensures we are using the season/ep from the episode grouping if provided
+ ep_url = EPISODE_URL.format(
+ show_info['id'], episode_info['org_seasonnum'], episode_info['org_epnum'])
+ params = TMDB_PARAMS.copy()
+ params['append_to_response'] = 'credits,external_ids,images'
+ params['include_image_language'] = '%s,en,null' % settings.LANG[0:2]
+ ep_return = api_utils.load_info(
+ ep_url, params=params, verboselog=settings.VERBOSELOG)
+ if ep_return is None:
+ return None
+ bad_return_name = False
+ bad_return_overview = False
+ check_name = ep_return.get('name')
+ if check_name == None:
+ bad_return_name = True
+ ep_return['name'] = 'Episode ' + \
+ str(episode_info['episode_number'])
+ elif check_name.lower().startswith('episode') or check_name == '':
+ bad_return_name = True
+ if ep_return.get('overview', '') == '':
+ bad_return_overview = True
+ if (bad_return_overview or bad_return_name) and settings.LANG != 'en-US':
+ params['language'] = 'en-US'
+ del params['append_to_response']
+ ep_return_backup = api_utils.load_info(
+ ep_url, params=params, verboselog=settings.VERBOSELOG)
+ if ep_return_backup is not None:
+ if bad_return_overview:
+ ep_return['overview'] = ep_return_backup.get(
+ 'overview', '')
+ if bad_return_name:
+ ep_return['name'] = ep_return_backup.get(
+ 'name', 'Episode ' + str(episode_info['episode_number']))
+ ep_return['images'] = _sort_image_types(ep_return.get('images', {}))
+ ep_return['season_number'] = episode_info['season_number']
+ ep_return['episode_number'] = episode_info['episode_number']
+ ep_return['org_seasonnum'] = episode_info['org_seasonnum']
+ ep_return['org_epnum'] = episode_info['org_epnum']
+ ep_return['ratings'] = load_ratings(
+ ep_return, show_imdb_id=show_info.get('external_ids', {}).get('imdb_id'))
+ for season in show_info.get('seasons', []):
+ if season.get('season_number') == episode_info['season_number']:
+ ep_return['season_cast'] = season.get(
+ 'credits', {}).get('cast', [])
+ break
+ show_info['episodes'][int(episode_id)] = ep_return
+ cache.cache_show_info(show_info)
+ return ep_return
+ return None
+
+
+def load_ratings(the_info, show_imdb_id=''):
+ # type: (InfoType, Text) -> Dict
+ """
+ Load the ratings for the show/episode
+
+ :param the_info: show or episode info
+ :param show_imdb_id: show IMDB
+ :return: ratings or empty dict
+ """
+ ratings = {}
+ imdb_id = the_info.get('external_ids', {}).get('imdb_id')
+ for rating_type in settings.RATING_TYPES:
+ logger.debug('setting rating using %s' % rating_type)
+ if rating_type == 'tmdb':
+ ratings['tmdb'] = {'votes': the_info['vote_count'],
+ 'rating': the_info['vote_average']}
+ elif rating_type == 'imdb' and imdb_id:
+ imdb_rating = imdbratings.get_details(imdb_id).get('ratings')
+ if imdb_rating:
+ ratings.update(imdb_rating)
+ elif rating_type == 'trakt':
+ if show_imdb_id:
+ season = the_info['org_seasonnum']
+ episode = the_info['org_epnum']
+ resp = traktratings.get_details(
+ show_imdb_id, season=season, episode=episode)
+ else:
+ resp = traktratings.get_details(imdb_id)
+ trakt_rating = resp.get('ratings')
+ if trakt_rating:
+ ratings.update(trakt_rating)
+ logger.debug('returning ratings of\n{}'.format(pformat(ratings)))
+ return ratings
+
+
+def load_fanarttv_art(show_info):
+ # type: (InfoType) -> Optional[InfoType]
+ """
+ Add fanart.tv images for a show
+
+ :param show_info: the current show info
+ :return: show info
+ """
+ tvdb_id = show_info.get('external_ids', {}).get('tvdb_id')
+ if tvdb_id and settings.FANARTTV_ENABLE:
+ fanarttv_url = FANARTTV_URL.format(tvdb_id)
+ artwork = api_utils.load_info(
+ fanarttv_url, params=FANARTTV_PARAMS, verboselog=settings.VERBOSELOG)
+ if artwork is None:
+ return show_info
+ for fanarttv_type, tmdb_type in settings.FANARTTV_MAPPING.items():
+ if not show_info['images'].get(tmdb_type) and not tmdb_type.startswith('season'):
+ show_info['images'][tmdb_type] = []
+ for item in artwork.get(fanarttv_type, []):
+ lang = item.get('lang')
+ if lang == '' or lang == '00':
+ lang = None
+ filepath = ''
+ if lang is None or lang == settings.LANG[0:2] or lang == 'en':
+ filepath = item.get('url')
+ if filepath:
+ if tmdb_type.startswith('season'):
+ image_type = tmdb_type[6:]
+ for s in range(len(show_info.get('seasons', []))):
+ season_num = show_info['seasons'][s]['season_number']
+ artseason = item.get('season', '')
+ if not show_info['seasons'][s].get('images'):
+ show_info['seasons'][s]['images'] = {}
+ if not show_info['seasons'][s]['images'].get(image_type):
+ show_info['seasons'][s]['images'][image_type] = []
+ if artseason == '' or artseason == str(season_num):
+ show_info['seasons'][s]['images'][image_type].append(
+ {'file_path': filepath, 'type': 'fanarttv', 'iso_639_1': lang})
+ else:
+ show_info['images'][tmdb_type].append(
+ {'file_path': filepath, 'type': 'fanarttv', 'iso_639_1': lang})
+ return show_info
+
+
+def trim_artwork(show_info):
+ # type: (InfoType) -> Optional[InfoType]
+ """
+ Trim artwork to keep the text blob below 65K characters
+
+ :param show_info: the current show info
+ :return: show info
+ """
+ image_counts = {}
+ image_total = 0
+ backdrops_total = 0
+ for image_type, image_list in show_info.get('images', {}).items():
+ total = len(image_list)
+ if image_type == 'backdrops':
+ backdrops_total = backdrops_total + total
+ else:
+ image_counts[image_type] = {'total': total}
+ image_total = image_total + total
+ for season in show_info.get('seasons', []):
+ for image_type, image_list in season.get('images', {}).items():
+ total = len(image_list)
+ thetype = '%s_%s' % (str(season['season_number']), image_type)
+ image_counts[thetype] = {'total': total}
+ image_total = image_total + total
+ if image_total <= settings.MAXIMAGES and backdrops_total <= settings.MAXIMAGES:
+ return show_info
+ if backdrops_total > settings.MAXIMAGES:
+ logger.error('there are %s fanart images' % str(backdrops_total))
+ logger.error('that is more than the max of %s, image results will be trimmed to the max' % str(
+ settings.MAXIMAGES))
+ reduce = -1 * (backdrops_total - settings.MAXIMAGES)
+ del show_info['images']['backdrops'][reduce:]
+ if image_total > settings.MAXIMAGES:
+ reduction = (image_total - settings.MAXIMAGES)/image_total
+ logger.error('there are %s non-fanart images' % str(image_total))
+ logger.error('that is more than the max of %s, image results will be trimmed by %s' % (
+ str(settings.MAXIMAGES), str(reduction)))
+ for key, value in image_counts.items():
+ image_counts[key]['reduce'] = -1 * \
+ int(floor(value['total'] * reduction))
+ logger.debug('%s: %s' % (key, pformat(image_counts[key])))
+ for image_type, image_list in show_info.get('images', {}).items():
+ if image_type == 'backdrops':
+ continue # already handled backdrops above
+ reduce = image_counts[image_type]['reduce']
+ if reduce != 0:
+ del show_info['images'][image_type][reduce:]
+ for s in range(len(show_info.get('seasons', []))):
+ for image_type, image_list in show_info['seasons'][s].get('images', {}).items():
+ thetype = '%s_%s' % (
+ str(show_info['seasons'][s]['season_number']), image_type)
+ reduce = image_counts[thetype]['reduce']
+ if reduce != 0:
+ del show_info['seasons'][s]['images'][image_type][reduce:]
+ return show_info
+
+
+def _sort_image_types(imagelist):
+ # type: (Dict) -> Dict
+ """
+ sort the images by language
+
+ :param imagelist:
+ :return: imagelist
+ """
+ for image_type, images in imagelist.items():
+ imagelist[image_type] = _image_sort(images, image_type)
+ return imagelist
+
+
+def _image_sort(images, image_type):
+ # type: (List, Text) -> List
+ """
+ sort the images by language
+
+ :param images:
+ :param image_type:
+ :return: list of images
+ """
+ lang_pref = []
+ lang_null = []
+ lang_en = []
+ firstimage = True
+ for image in images:
+ image_lang = image.get('iso_639_1')
+ if image_lang == settings.LANG[0:2]:
+ lang_pref.append(image)
+ elif image_lang == 'en':
+ lang_en.append(image)
+ else:
+ if firstimage:
+ lang_pref.append(image)
+ else:
+ lang_null.append(image)
+ firstimage = False
+ if image_type == 'posters':
+ return lang_pref + lang_en + lang_null
+ else:
+ return lang_pref + lang_null + lang_en
diff --git a/addons/metadata.tvshows.themoviedb.org.python/libs/traktratings.py b/addons/metadata.tvshows.themoviedb.org.python/libs/traktratings.py
new file mode 100644
index 0000000..48091b5
--- /dev/null
+++ b/addons/metadata.tvshows.themoviedb.org.python/libs/traktratings.py
@@ -0,0 +1,66 @@
+# -*- coding: UTF-8 -*-
+#
+# Copyright (C) 2020, Team Kodi
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+# pylint: disable=missing-docstring
+
+"""Functions to interact with Trakt API"""
+
+from __future__ import absolute_import, unicode_literals
+
+from . import api_utils, settings
+try:
+ from typing import Text, Optional, Union, List, Dict, Any # pylint: disable=unused-import
+except ImportError:
+ pass
+
+
+HEADERS = (
+ ('User-Agent', 'Kodi TV Show scraper by Team Kodi; contact pkscout@kodi.tv'),
+ ('Accept', 'application/json'),
+ ('trakt-api-key', settings.TRAKT_CLOWNCAR),
+ ('trakt-api-version', '2'),
+ ('Content-Type', 'application/json'),
+)
+api_utils.set_headers(dict(HEADERS))
+
+SHOW_URL = 'https://api.trakt.tv/shows/{}'
+EP_URL = SHOW_URL + '/seasons/{}/episodes/{}/ratings'
+
+
+def get_details(imdb_id, season=None, episode=None):
+ # type: (Text, Text, Text) -> Dict
+ """
+ get the Trakt ratings
+
+ :param imdb_id:
+ :param season:
+ :param episode:
+ :return: trackt ratings
+ """
+ result = {}
+ if season and episode:
+ url = EP_URL.format(imdb_id, season, episode)
+ params = None
+ else:
+ url = SHOW_URL.format(imdb_id)
+ params = {'extended': 'full'}
+ resp = api_utils.load_info(
+ url, params=params, default={}, verboselog=settings.VERBOSELOG)
+ rating = resp.get('rating')
+ votes = resp.get('votes')
+ if votes and rating:
+ result['ratings'] = {'trakt': {'votes': votes, 'rating': rating}}
+ return result
diff --git a/addons/metadata.tvshows.themoviedb.org.python/libs/utils.py b/addons/metadata.tvshows.themoviedb.org.python/libs/utils.py
new file mode 100644
index 0000000..a9dbfbb
--- /dev/null
+++ b/addons/metadata.tvshows.themoviedb.org.python/libs/utils.py
@@ -0,0 +1,72 @@
+# -*- coding: UTF-8 -*-
+#
+# Copyright (C) 2020, Team Kodi
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+# pylint: disable=missing-docstring
+
+"""Misc utils"""
+
+from __future__ import absolute_import, unicode_literals
+
+import xbmc
+from xbmcaddon import Addon
+
+try:
+ from typing import Text, Optional, Any, Dict # pylint: disable=unused-import
+except ImportError:
+ pass
+
+ADDON_ID = 'metadata.tvshows.themoviedb.org.python'
+ADDON = Addon()
+
+
+class logger:
+ log_message_prefix = '[{} ({})]: '.format(
+ ADDON_ID, ADDON.getAddonInfo('version'))
+
+ @staticmethod
+ def log(message, level=xbmc.LOGDEBUG):
+ # type: (Text, int) -> None
+ if isinstance(message, bytes):
+ message = message.decode('utf-8')
+ message = logger.log_message_prefix + message
+ xbmc.log(message, level)
+
+ @staticmethod
+ def info(message):
+ # type: (Text) -> None
+ logger.log(message, xbmc.LOGINFO)
+
+ @staticmethod
+ def error(message):
+ # type: (Text) -> None
+ logger.log(message, xbmc.LOGERROR)
+
+ @staticmethod
+ def debug(message):
+ # type: (Text) -> None
+ logger.log(message, xbmc.LOGDEBUG)
+
+
+def safe_get(dct, key, default=None):
+ # type: (Dict[Text, Any], Text, Any) -> Any
+ """
+ Get a key from dict
+
+ Returns the respective value or default if key is missing or the value is None.
+ """
+ if key in dct and dct[key] is not None:
+ return dct[key]
+ return default
diff --git a/addons/metadata.tvshows.themoviedb.org.python/main.py b/addons/metadata.tvshows.themoviedb.org.python/main.py
new file mode 100644
index 0000000..a81c519
--- /dev/null
+++ b/addons/metadata.tvshows.themoviedb.org.python/main.py
@@ -0,0 +1,32 @@
+# -*- coding: UTF-8 -*-
+#
+# Copyright (C) 2020, Team Kodi
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+#
+# Code attribution:
+# core based on metadata.tvmaze scrapper by Roman Miroshnychenko aka Roman V.M.
+# IMDb ratings based on code in metadata.themoviedb.org.python by Team Kodi
+# pylint: disable=missing-docstring
+
+from __future__ import absolute_import
+
+import sys
+
+from libs.actions import router
+from libs.debugger import debug_exception
+
+if __name__ == '__main__':
+ with debug_exception():
+ router(sys.argv[2][1:])
diff --git a/addons/metadata.tvshows.themoviedb.org.python/resources/icon.png b/addons/metadata.tvshows.themoviedb.org.python/resources/icon.png
new file mode 100644
index 0000000..1aa8275
--- /dev/null
+++ b/addons/metadata.tvshows.themoviedb.org.python/resources/icon.png
Binary files differ
diff --git a/addons/metadata.tvshows.themoviedb.org.python/resources/language/resource.language.en_gb/strings.po b/addons/metadata.tvshows.themoviedb.org.python/resources/language/resource.language.en_gb/strings.po
new file mode 100644
index 0000000..7ece84d
--- /dev/null
+++ b/addons/metadata.tvshows.themoviedb.org.python/resources/language/resource.language.en_gb/strings.po
@@ -0,0 +1,157 @@
+# Kodi Media Center language file
+# Addon Name: The Movie Database
+# Addon id: metadata.themoviedb.org
+# Addon Provider: XBMC Foundation
+msgid ""
+msgstr ""
+"Project-Id-Version: XBMC Addons\n"
+"Report-Msgid-Bugs-To: alanwww1@xbmc.org\n"
+"POT-Creation-Date: YEAR-MO-DA HO:MI+ZONE\n"
+"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
+"Last-Translator: Kodi Translation Team\n"
+"Language-Team: English (http://www.transifex.com/projects/p/xbmc-addons/language/en/)\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Language: en\n"
+"Plural-Forms: nplurals=2; plural=(n != 1);\n"
+
+msgctxt "Addon Summary"
+msgid "Fetch TV Show metadata from themoviedb.org"
+msgstr ""
+
+msgctxt "Addon Description"
+msgid "The Movie Database (TMDb) is a community built movie and TV database. Every piece of data has been added by our amazing community dating back to 2008. TMDb's strong international focus and breadth of data is largely unmatched and something we're incredibly proud of. Put simply, we live and breathe community and that's precisely what makes us different."
+msgstr ""
+
+msgctxt "#30000"
+msgid "Preferred language"
+msgstr ""
+
+msgctxt "#30001"
+msgid "Preferred certification country"
+msgstr ""
+
+msgctxt "#30002"
+msgid "Include certification prefix"
+msgstr ""
+
+msgctxt "#30003"
+msgid "Prefix"
+msgstr ""
+
+msgctxt "#30004"
+msgid "Keep original title"
+msgstr ""
+
+msgctxt "#30005"
+msgid "Categorize fanart with text as landscape art"
+msgstr ""
+
+msgctxt "#30006"
+msgid "Include country code with studio"
+msgstr ""
+
+# empty strings from 30006 to 30099
+
+msgctxt "#30100"
+msgid "Fanart.tv"
+msgstr ""
+
+msgctxt "#30101"
+msgid "Client key (optional)"
+msgstr ""
+
+msgctxt "#30102"
+msgid "Enable fanart"
+msgstr ""
+
+msgctxt "#30103"
+msgid "Enable poster"
+msgstr ""
+
+msgctxt "#30104"
+msgid "Enable banner"
+msgstr ""
+
+msgctxt "#30105"
+msgid "Enable clearlogo"
+msgstr ""
+
+msgctxt "#30106"
+msgid "Enable clearart"
+msgstr ""
+
+msgctxt "#30107"
+msgid "Enable landscape"
+msgstr ""
+
+msgctxt "#30108"
+msgid "Enable character art"
+msgstr ""
+
+msgctxt "#30109"
+msgid "Include art from fanart.tv"
+msgstr ""
+
+# empty strings from 30110 to 30149
+
+msgctxt "#30150"
+msgid "Enable season poster"
+msgstr ""
+
+msgctxt "#30151"
+msgid "Enable season banner"
+msgstr ""
+
+msgctxt "#30152"
+msgid "Enable season landscape"
+msgstr ""
+
+# empty strings from 30153 to 30200
+
+msgctxt "#30200"
+msgid "Advanced"
+msgstr ""
+
+msgctxt "#30201"
+msgid "Verbose debug logging"
+msgstr ""
+
+# emptry strings from 30202 to 30299
+
+msgctxt "#30300"
+msgid "Ratings"
+msgstr ""
+
+msgctxt "#30301"
+msgid "Default rating from"
+msgstr ""
+
+msgctxt "#30302"
+msgid "Also add IMDb ratings"
+msgstr ""
+
+msgctxt "#30303"
+msgid "Also add Trakt.tv ratings"
+msgstr ""
+
+msgctxt "#30304"
+msgid "Also add TMDb ratings"
+msgstr ""
+
+msgctxt "#30305"
+msgid "Enable Trailer"
+msgstr ""
+
+msgctxt "#30306"
+msgid "Addon Player"
+msgstr ""
+
+msgctxt "#30307"
+msgid "YouTube"
+msgstr ""
+
+msgctxt "#30308"
+msgid "Tubed"
+msgstr ""
diff --git a/addons/metadata.tvshows.themoviedb.org.python/resources/settings.xml b/addons/metadata.tvshows.themoviedb.org.python/resources/settings.xml
new file mode 100644
index 0000000..df5de24
--- /dev/null
+++ b/addons/metadata.tvshows.themoviedb.org.python/resources/settings.xml
@@ -0,0 +1,299 @@
+<?xml version="1.0" ?>
+<settings version="1">
+ <section id="metadata.tvshows.themoviedb.org.python">
+ <category id="general" label="128" help="">
+ <group id="1">
+ <setting id="language" type="string" label="30000" help="">
+ <level>0</level>
+ <default>en-US</default>
+ <constraints>
+ <options>
+ <option>ar-AE</option>
+ <option>ar-SA</option>
+ <option>be-BY</option>
+ <option>bg-BG</option>
+ <option>bn-BD</option>
+ <option>ca-ES</option>
+ <option>ch-GU</option>
+ <option>cs-CZ</option>
+ <option>da-DK</option>
+ <option>de-DE</option>
+ <option>el-GR</option>
+ <option>en-US</option>
+ <option>eo-EO</option>
+ <option>es-ES</option>
+ <option>es-MX</option>
+ <option>et-EE</option>
+ <option>eu-ES</option>
+ <option>fa-IR</option>
+ <option>fi-FI</option>
+ <option>fr-CA</option>
+ <option>fr-FR</option>
+ <option>gl-ES</option>
+ <option>he-IL</option>
+ <option>hi-IN</option>
+ <option>hr-HR</option>
+ <option>hu-HU</option>
+ <option>id-ID</option>
+ <option>it-IT</option>
+ <option>ja-JP</option>
+ <option>ka-GE</option>
+ <option>kn-IN</option>
+ <option>ko-KR</option>
+ <option>lt-LT</option>
+ <option>lv-LV</option>
+ <option>ml-IN</option>
+ <option>nb-NO</option>
+ <option>nl-NL</option>
+ <option>no-NO</option>
+ <option>pl-PL</option>
+ <option>pt-BR</option>
+ <option>pt-PT</option>
+ <option>ro-RO</option>
+ <option>ru-RU</option>
+ <option>sk-SK</option>
+ <option>sl-SI</option>
+ <option>sr-RS</option>
+ <option>sv-SE</option>
+ <option>ta-IN</option>
+ <option>te-IN</option>
+ <option>th-TH</option>
+ <option>tr-TR</option>
+ <option>uk-UA</option>
+ <option>vi-VN</option>
+ <option>zh-CN</option>
+ <option>zh-HK</option>
+ <option>zh-TW</option>
+ </options>
+ </constraints>
+ <control type="list" format="string">
+ <heading>30000</heading>
+ </control>
+ </setting>
+ <setting id="tmdbcertcountry" type="string" label="30001" help="">
+ <level>0</level>
+ <default>us</default>
+ <constraints>
+ <options>
+ <option>au</option>
+ <option>bg</option>
+ <option>br</option>
+ <option>by</option>
+ <option>ca</option>
+ <option>cz</option>
+ <option>de</option>
+ <option>dk</option>
+ <option>ee</option>
+ <option>es</option>
+ <option>fi</option>
+ <option>fr</option>
+ <option>gb</option>
+ <option>ge</option>
+ <option>gr</option>
+ <option>hr</option>
+ <option>hu</option>
+ <option>id</option>
+ <option>il</option>
+ <option>in</option>
+ <option>it</option>
+ <option>ir</option>
+ <option>jp</option>
+ <option>kr</option>
+ <option>lt</option>
+ <option>lv</option>
+ <option>mx</option>
+ <option>nl</option>
+ <option>no</option>
+ <option>pl</option>
+ <option>pt</option>
+ <option>ru</option>
+ <option>si</option>
+ <option>sv</option>
+ <option>th</option>
+ <option>tr</option>
+ <option>ua</option>
+ <option>us</option>
+ <option>vn</option>
+ <option>zh</option>
+ </options>
+ </constraints>
+ <control type="list" format="string">
+ <heading>30001</heading>
+ </control>
+ </setting>
+ <setting id="usecertprefix" type="boolean" label="30002" help="">
+ <level>0</level>
+ <default>true</default>
+ <control type="toggle"/>
+ </setting>
+ <setting id="certprefix" type="string" label="30003" help="">
+ <level>0</level>
+ <default>Rated </default>
+ <dependencies>
+ <dependency type="enable">
+ <condition operator="is" setting="usecertprefix">true</condition>
+ </dependency>
+ </dependencies>
+ <control type="edit" format="string">
+ <heading>30003</heading>
+ </control>
+ </setting>
+ <setting id="keeporiginaltitle" type="boolean" label="30004" help="">
+ <level>0</level>
+ <default>false</default>
+ <control type="toggle"/>
+ </setting>
+ <setting id="cat_landscape" type="boolean" label="30005" help="">
+ <level>0</level>
+ <default>true</default>
+ <control type="toggle"/>
+ </setting>
+ <setting id="studio_country" type="boolean" label="30006" help="">
+ <level>0</level>
+ <default>false</default>
+ <control type="toggle"/>
+ </setting>
+ <setting id="enab_trailer" type="boolean" label="30305" help="">
+ <level>0</level>
+ <default>true</default>
+ <control type="toggle"/>
+ </setting>
+ <setting id="players_opt" type="string" parent="enab_trailer" label="30306" help="">
+ <level>0</level>
+ <default>Tubed</default>
+ <constraints>
+ <options>
+ <option label="30307">YouTube</option>
+ <option label="30308">Tubed</option>
+ </options>
+ </constraints>
+ <dependencies>
+ <dependency type="enable" setting="enab_trailer" operator="is">true</dependency>
+ </dependencies>
+ <control type="spinner" format="string"/>
+ </setting>
+ </group>
+ </category>
+ <category id="ratings" label="30300" help="">
+ <group id="1">
+ <setting id="ratings" type="string" label="30301" help="">
+ <level>0</level>
+ <default>TMDb</default>
+ <constraints>
+ <options>
+ <option label="TMDb">TMDb</option>
+ <option label="IMDb">IMDb</option>
+ <option label="Trakt">Trakt</option>
+ </options>
+ </constraints>
+ <control type="spinner" format="string"/>
+ </setting>
+ <setting id="imdbanyway" type="boolean" label="30302" help="">
+ <level>0</level>
+ <default>false</default>
+ <dependencies>
+ <dependency type="enable">
+ <condition operator="!is" setting="ratings">IMDb</condition>
+ </dependency>
+ </dependencies>
+ <control type="toggle"/>
+ </setting>
+ <setting id="traktanyway" type="boolean" label="30303" help="">
+ <level>0</level>
+ <default>false</default>
+ <dependencies>
+ <dependency type="enable">
+ <condition operator="!is" setting="ratings">Trakt</condition>
+ </dependency>
+ </dependencies>
+ <control type="toggle"/>
+ </setting>
+ <setting id="tmdbanyway" type="boolean" label="30304" help="">
+ <level>0</level>
+ <default>true</default>
+ <dependencies>
+ <dependency type="enable">
+ <condition operator="!is" setting="ratings">TMDb</condition>
+ </dependency>
+ </dependencies>
+ <control type="toggle"/>
+ </setting>
+ </group>
+ </category>
+ <category id="fanart.tv" label="30100" help="">
+ <group id="1">
+ <setting id="enable_fanarttv" type="boolean" label="30109" help="">
+ <level>0</level>
+ <default>true</default>
+ <control type="toggle"/>
+ </setting>
+ <setting id="fanarttv_clientkey" type="string" label="30101" help="">
+ <level>0</level>
+ <default/>
+ <dependencies>
+ <dependency type="enable">
+ <condition operator="is" setting="enable_fanarttv">true</condition>
+ </dependency>
+ </dependencies>
+ <constraints>
+ <allowempty>true</allowempty>
+ </constraints>
+ <control type="edit" format="string">
+ <heading>30101</heading>
+ </control>
+ </setting>
+ </group>
+ </category>
+ <category id="advanced" label="30200" help="">
+ <group id="1">
+ <setting id="verboselog" type="boolean" label="30201" help="">
+ <level>0</level>
+ <default>false</default>
+ <control type="toggle"/>
+ </setting>
+ <setting id="lastUpdated" type="string" help="">
+ <level>0</level>
+ <default>0</default>
+ <dependencies>
+ <dependency type="visible">
+ <condition on="property" name="InfoBool">false</condition>
+ </dependency>
+ </dependencies>
+ <control type="edit" format="string">
+ <heading/>
+ </control>
+ </setting>
+ <setting id="originalUrl" type="string" help="">
+ <level>0</level>
+ <default/>
+ <constraints>
+ <allowempty>true</allowempty>
+ </constraints>
+ <dependencies>
+ <dependency type="visible">
+ <condition on="property" name="InfoBool">false</condition>
+ </dependency>
+ </dependencies>
+ <control type="edit" format="string">
+ <heading/>
+ </control>
+ </setting>
+ <setting id="previewUrl" type="string" help="">
+ <level>0</level>
+ <default/>
+ <constraints>
+ <allowempty>true</allowempty>
+ </constraints>
+ <dependencies>
+ <dependency type="visible">
+ <condition on="property" name="InfoBool">false</condition>
+ </dependency>
+ </dependencies>
+ <control type="edit" format="string">
+ <heading/>
+ </control>
+ </setting>
+ </group>
+ </category>
+ </section>
+</settings>