diff --git a/plugin.video.external.library/LICENSE.txt b/plugin.video.external.library/LICENSE.txt new file mode 100644 index 000000000..281d399f1 --- /dev/null +++ b/plugin.video.external.library/LICENSE.txt @@ -0,0 +1,619 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. diff --git a/plugin.video.external.library/addon.xml b/plugin.video.external.library/addon.xml new file mode 100644 index 000000000..bb2eb0c00 --- /dev/null +++ b/plugin.video.external.library/addon.xml @@ -0,0 +1,26 @@ + + + + + + + video + + + + + Kodi External Video Library + A plugin that allows to browse and play items from a video library on an external Kodi instance. + all + GPL-3.0-only + + icon.png + + https://github.com/romanvm/kodi.external.library + 1.0.0: Initial public release. + true + + diff --git a/plugin.video.external.library/commands.py b/plugin.video.external.library/commands.py new file mode 100644 index 000000000..8de89b6af --- /dev/null +++ b/plugin.video.external.library/commands.py @@ -0,0 +1,43 @@ +# Copyright (C) 2023, Roman Miroshnychenko aka Roman V.M. +# +# 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 . + +import logging +import sys + +import xbmc +import xbmcgui + +from libs.exception_logger import catch_exception +from libs.json_rpc_api import update_playcount +from libs.kodi_service import GettextEmulator, initialize_logging + +initialize_logging() +logger = logging.getLogger(__name__) +_ = GettextEmulator.gettext + + +def main(): + logger.debug('Executing command: %s', str(sys.argv)) + if len(sys.argv) == 1: + xbmcgui.Dialog().ok(_('Kodi External Video Library Client'), + _(r'Please run this addon from \"Video addons\" section.')) + elif sys.argv[1] == 'update_playcount': + update_playcount(sys.argv[2], int(sys.argv[3]), int(sys.argv[4])) + xbmc.executebuiltin('Container.Refresh') + + +if __name__ == '__main__': + with catch_exception(logger.error): + main() diff --git a/plugin.video.external.library/icon.png b/plugin.video.external.library/icon.png new file mode 100644 index 000000000..ff51a9ed3 Binary files /dev/null and b/plugin.video.external.library/icon.png differ diff --git a/plugin.video.external.library/libs/__init__.py b/plugin.video.external.library/libs/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/plugin.video.external.library/libs/actions.py b/plugin.video.external.library/libs/actions.py new file mode 100644 index 000000000..1362a94a0 --- /dev/null +++ b/plugin.video.external.library/libs/actions.py @@ -0,0 +1,160 @@ +# Copyright (C) 2023, Roman Miroshnychenko aka Roman V.M. +# +# 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 . + +import logging +import sys +from urllib.parse import parse_qsl + +import xbmcplugin +from xbmcgui import Dialog, ListItem + +from libs.content_type_handlers import ( + MoviesHandler, + RecentMoviesHandler, + TvShowsHandler, + SeasonsHandler, + EpisodesHandler, + RecentEpisodesHandler, + MusicVideosHandler, + RecentMusicVideosHandler, +) +from libs.exceptions import NoDataError, RemoteKodiError +from libs.kodi_service import ADDON, ADDON_ID, GettextEmulator, get_plugin_url +from libs.media_info_service import set_info, set_art +from libs.mem_storage import MemStorage + +logger = logging.getLogger(__name__) +_ = GettextEmulator.gettext + +HANDLE = int(sys.argv[1]) + +DIALOG = Dialog() + +MEM_STORAGE = MemStorage() + +CONTENT_TYPE_HANDLERS = { + 'movies': MoviesHandler, + 'recent_movies': RecentMoviesHandler, + 'tvshows': TvShowsHandler, + 'seasons': SeasonsHandler, + 'episodes': EpisodesHandler, + 'recent_episodes': RecentEpisodesHandler, + 'music_videos': MusicVideosHandler, + 'recent_music_videos': RecentMusicVideosHandler, +} + + +def root(): + """Root action""" + xbmcplugin.setPluginCategory(HANDLE, + _('Kodi Medialibrary on {kodi_host}').format( + kodi_host=ADDON.getSettingString('kodi_host'))) + if ADDON.getSettingBool('show_movies'): + list_item = ListItem(f'[{_("Movies")}]') + list_item.setArt({'icon': 'DefaultMovies.png', 'thumb': 'DefaultMovies.png'}) + url = get_plugin_url(content_type='movies') + xbmcplugin.addDirectoryItem(HANDLE, url, list_item, isFolder=True) + if ADDON.getSettingBool('show_recent_movies'): + list_item = ListItem(f'[{_("Recently added movies")}]') + list_item.setArt({'icon': 'DefaultRecentlyAddedMovies.png', + 'thumb': 'DefaultRecentlyAddedMovies.png'}) + url = get_plugin_url(content_type='recent_movies') + xbmcplugin.addDirectoryItem(HANDLE, url, list_item, isFolder=True) + if ADDON.getSettingBool('show_tvshows'): + list_item = ListItem(f'[{_("TV Shows")}]') + list_item.setArt({'icon': 'DefaultTVShows.png', 'thumb': 'DefaultTVShows.png'}) + url = get_plugin_url(content_type='tvshows') + xbmcplugin.addDirectoryItem(HANDLE, url, list_item, isFolder=True) + if ADDON.getSettingBool('show_recent_episodes'): + list_item = ListItem(f'[{_("Recently added episodes")}]') + list_item.setArt({'icon': 'DefaultRecentlyAddedEpisodes.png', + 'thumb': 'DefaultRecentlyAddedEpisodes.png'}) + url = get_plugin_url(content_type='recent_episodes') + xbmcplugin.addDirectoryItem(HANDLE, url, list_item, isFolder=True) + if ADDON.getSettingBool('show_music_videos'): + list_item = ListItem(f'[{_("Music videos")}]') + list_item.setArt({'icon': 'DefaultMusicVideos.png', 'thumb': 'DefaultMusicVideos.png'}) + url = get_plugin_url(content_type='music_videos') + xbmcplugin.addDirectoryItem(HANDLE, url, list_item, isFolder=True) + if ADDON.getSettingBool('show_recent_music_videos'): + list_item = ListItem(f'[{_("Recently added music videos")}]') + list_item.setArt({'icon': 'DefaultRecentlyAddedMusicVideos.png', + 'thumb': 'DefaultRecentlyAddedMusicVideos.png'}) + url = get_plugin_url(content_type='recent_music_videos') + xbmcplugin.addDirectoryItem(HANDLE, url, list_item, isFolder=True) + + +def show_media_items(content_type, tvshowid=None, season=None, parent_category=None): + content_type_handler_class = CONTENT_TYPE_HANDLERS.get(content_type) + if content_type_handler_class is None: + raise RuntimeError(f'Unknown content type: {content_type}') + content_type_handler = content_type_handler_class(tvshowid, season, parent_category) + xbmcplugin.setPluginCategory(HANDLE, content_type_handler.get_plugin_category()) + xbmcplugin.setContent(HANDLE, content_type_handler.content) + try: + media_items = content_type_handler.get_media_items() + except NoDataError: + logger.exception('Unable to retrieve %s from the remote Kodi library', + content_type) + DIALOG.notification(ADDON_ID, _('Unable to retrieve data from the remote Kodi library!'), + icon='error') + return + except RemoteKodiError as exc: + logger.exception('Unable to connect to %s', str(exc)) + DIALOG.notification(ADDON_ID, _('Unable to connect to the remote Kodi host!'), icon='error') + return + logger.debug('Creating a list of %s items...', content_type) + directory_items = [] + mem_storage_items = [] + for media_info in media_items: + list_item = ListItem(media_info.get('title') or media_info.get('label', '')) + if art := media_info.get('art'): + set_art(list_item, art) + info_tag = list_item.getVideoInfoTag() + set_info(info_tag, media_info, content_type_handler.mediatype) + list_item.addContextMenuItems(content_type_handler.get_item_context_menu(media_info)) + directory_items.append(( + content_type_handler.get_item_url(media_info), + list_item, + content_type_handler.item_is_folder, + )) + if content_type_handler.should_save_to_mem_storage: + item_id_param = f'{content_type_handler.mediatype}id' + mem_storage_items.append({ + 'item_id_param': item_id_param, + item_id_param: media_info[item_id_param], + 'file': media_info['file'], + 'playcount': media_info.get('playcount', 0), + }) + xbmcplugin.addDirectoryItems(HANDLE, directory_items, len(directory_items)) + MEM_STORAGE['__external_library_list__'] = mem_storage_items + for sort_method in content_type_handler.get_sort_methods(): + xbmcplugin.addSortMethod(HANDLE, sort_method) + logger.debug('Finished creating a list of %s items.', content_type) + + +def router(paramstring): + params = dict(parse_qsl(paramstring)) + logger.debug('Called addon with params: %s', str(sys.argv)) + if 'content_type' not in params: + root() + else: + if (tvshowid := params.get('tvshowid')) is not None: + tvshowid = int(tvshowid) + if (season := params.get('season')) is not None: + season = int(season) + parent_category = params.get('parent_category') + show_media_items(params['content_type'], tvshowid, season, parent_category) + xbmcplugin.endOfDirectory(HANDLE) diff --git a/plugin.video.external.library/libs/content_type_handlers.py b/plugin.video.external.library/libs/content_type_handlers.py new file mode 100644 index 000000000..56274c67b --- /dev/null +++ b/plugin.video.external.library/libs/content_type_handlers.py @@ -0,0 +1,231 @@ +# Copyright (C) 2023, Roman Miroshnychenko aka Roman V.M. +# +# 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 . +"""Classes that are responsible for processing supported content types: Movies, TV Shows etc.""" + +import enum +from typing import Type, List, Dict, Any, Optional, Tuple, Iterable +from urllib.parse import urljoin, quote + +import xbmcplugin + +from libs import json_rpc_api +from libs.kodi_service import GettextEmulator, get_remote_kodi_url, ADDON_ID, ADDON, get_plugin_url + +__all__ = [ + 'MoviesHandler', + 'RecentMoviesHandler', + 'TvShowsHandler', + 'SeasonsHandler', + 'EpisodesHandler', + 'RecentEpisodesHandler', +] + +_ = GettextEmulator.gettext + +REMOTE_KODI_URL = get_remote_kodi_url(with_credentials=True) +VIDEO_URL = urljoin(REMOTE_KODI_URL, 'vfs') + + +# pylint: disable=unused-argument +class BaseContentTypeHandler: + mediatype: str + item_is_folder: bool + should_save_to_mem_storage: bool + api_class: Type[json_rpc_api.BaseMediaItemsRetriever] + + def __init__(self, tvshowid: Optional[int] = None, + season: Optional[int] = None, + parent_category: Optional[str] = None): + self._tvshowid = tvshowid + self._season = season + self._parent_category = parent_category + self._api = self.api_class(self.content, self._tvshowid, self._season) + + @property + def content(self) -> str: + return f'{self.mediatype}s' + + def get_media_items(self) -> Iterable[Dict[str, Any]]: + yield from self._api.get_media_items() + + def get_plugin_category(self) -> str: + raise NotImplementedError + + def get_item_url(self, media_info: Dict[str, Any]) -> str: + raise NotImplementedError + + def get_item_context_menu(self, media_info: Dict[str, Any]) -> List[Tuple[str, str]]: + return [] + + def get_sort_methods(self) -> List[int]: + return [ + xbmcplugin.SORT_METHOD_TITLE_IGNORE_THE, + xbmcplugin.SORT_METHOD_TITLE, + xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE, + xbmcplugin.SORT_METHOD_LABEL, + xbmcplugin.SORT_METHOD_VIDEO_YEAR, + xbmcplugin.SORT_METHOD_COUNTRY, + xbmcplugin.SORT_METHOD_STUDIO, + xbmcplugin.SORT_METHOD_GENRE, + xbmcplugin.SORT_METHOD_MPAA_RATING, + xbmcplugin.SORT_METHOD_PLAYCOUNT, + ] + + +class PlayableContentMixin: + item_is_folder = False + should_save_to_mem_storage = True + + def get_item_context_menu(self, media_info: Dict[str, Any]) -> List[Tuple[str, str]]: + if media_info['playcount']: + caption = f'[COLOR=yellow][B]{_("Mark as unwatched")}[/B][/COLOR]' + playcount_to_set = 0 + else: + caption = f'[COLOR=green][B]{_("Mark as watched")}[/B][/COLOR]' + playcount_to_set = 1 + item_id_param = f'{self.mediatype}id' + item_id = media_info[item_id_param] + command = f'RunScript({ADDON_ID},' \ + f'update_playcount,{item_id_param},{item_id},{playcount_to_set})' + return [(caption, command)] + + def get_item_url(self, media_info: Dict[str, Any]) -> str: + if ADDON.getSettingBool('files_on_shares'): + return media_info['file'] + return f'{VIDEO_URL}/{quote(media_info["file"])}' + + +class MoviesHandler(PlayableContentMixin, BaseContentTypeHandler): + mediatype = 'movie' + api_class = json_rpc_api.GetMovies + + def get_plugin_category(self) -> str: + return _('Movies') + + +class RecentMoviesHandler(MoviesHandler): + api_class = json_rpc_api.GetRecentlyAddedMovies + + def get_plugin_category(self) -> str: + return _('Recently added movies') + + def get_sort_methods(self) -> List[int]: + return [] + + +class TvShowsHandler(BaseContentTypeHandler): + mediatype = 'tvshow' + item_is_folder = True + should_save_to_mem_storage = False + api_class = json_rpc_api.GetTVShows + + class FlattenSeasons(enum.IntEnum): + NEVER = 0 + IF_ONE_SEASON = 1 + ALWAYS = 2 + + def get_plugin_category(self) -> str: + return _('TV Shows') + + def get_media_items(self) -> Iterable[Dict[str, Any]]: + for media_item in super().get_media_items(): + if media_item['episode']: + yield media_item + + def get_item_url(self, media_info: Dict[str, Any]) -> str: + parent_category = media_info.get('title') or media_info['label'] + tvshowid = media_info['tvshowid'] + if ADDON.getSettingInt('flatten_seasons') == self.FlattenSeasons.ALWAYS: + return get_plugin_url(content_type='episodes', tvshowid=tvshowid, + parent_category=parent_category) + if ADDON.getSettingInt('flatten_seasons') == self.FlattenSeasons.IF_ONE_SEASON: + if media_info['season'] == 1: + return get_plugin_url(content_type='episodes', tvshowid=tvshowid, + parent_category=parent_category) + return get_plugin_url(content_type='seasons', tvshowid=tvshowid, + parent_category=parent_category) + + +class SeasonsHandler(BaseContentTypeHandler): + mediatype = 'season' + item_is_folder = True + should_save_to_mem_storage = False + api_class = json_rpc_api.GetSeasons + + def get_plugin_category(self) -> str: + return f'{self._parent_category} / {_("Seasons")}' + + def get_item_url(self, media_info: Dict[str, Any]) -> str: + season_title = media_info.get('title') or media_info['label'] + parent_category = f'{media_info["showtitle"]} / {season_title}' + return get_plugin_url(content_type='episodes', tvshowid=media_info['tvshowid'], + season=media_info['season'], parent_category=parent_category) + + def get_sort_methods(self) -> List[int]: + return [ + xbmcplugin.SORT_METHOD_TITLE, + xbmcplugin.SORT_METHOD_LABEL, + xbmcplugin.SORT_METHOD_PLAYCOUNT, + ] + + +class EpisodesHandler(PlayableContentMixin, BaseContentTypeHandler): + mediatype = 'episode' + api_class = json_rpc_api.GetEpisodes + + def get_plugin_category(self) -> str: + return self._parent_category + + def get_sort_methods(self) -> List[int]: + return [ + xbmcplugin.SORT_METHOD_EPISODE, + xbmcplugin.SORT_METHOD_DATE, + ] + super().get_sort_methods() + + +class RecentEpisodesHandler(EpisodesHandler): + api_class = json_rpc_api.GetRecentlyAddedEpisodes + + def get_plugin_category(self) -> str: + return _('Recently added episodes') + + def get_sort_methods(self) -> List[int]: + return [] + + +class MusicVideosHandler(PlayableContentMixin, BaseContentTypeHandler): + mediatype = 'musicvideo' + api_class = json_rpc_api.GetMusicVideos + + def get_plugin_category(self) -> str: + return _('Music videos') + + def get_sort_methods(self) -> List[int]: + return [ + xbmcplugin.SORT_METHOD_ALBUM, + xbmcplugin.SORT_METHOD_ARTIST, + xbmcplugin.SORT_METHOD_ARTIST_IGNORE_THE, + xbmcplugin.SORT_METHOD_TRACKNUM, + ] + super().get_sort_methods() + + +class RecentMusicVideosHandler(MusicVideosHandler): + api_class = json_rpc_api.GetRecentlyAddedMusicVideos + + def get_plugin_category(self) -> str: + return _('Recently added music videos') + + def get_sort_methods(self) -> List[int]: + return [] diff --git a/plugin.video.external.library/libs/exception_logger.py b/plugin.video.external.library/libs/exception_logger.py new file mode 100644 index 000000000..928dd8086 --- /dev/null +++ b/plugin.video.external.library/libs/exception_logger.py @@ -0,0 +1,194 @@ +# (c) Roman Miroshnychenko 2023 +# +# 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 . +"""Exception logger with extended diagnostic info""" + +import inspect +import sys +from contextlib import contextmanager +from platform import uname +from pprint import pformat +from typing import Any, Dict, Callable, Generator, Iterable, Optional + +import xbmc + + +def _log_error(message: str) -> None: + xbmc.log(message, level=xbmc.LOGERROR) + + +def _format_vars(variables: Dict[str, Any]) -> str: + """ + Format variables dictionary + + :param variables: variables dict + :return: formatted string with sorted ``var = val`` pairs + """ + 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(f'{var} = {pformat(val)}') + return '\n'.join(lines) + + +def _format_code_context(frame_info: inspect.FrameInfo) -> str: + context = '' + if frame_info.code_context is not None: + for i, line in enumerate(frame_info.code_context, frame_info.lineno - frame_info.index): + if i == frame_info.lineno: + context += f'{str(i).rjust(5)}:>{line}' + else: + context += f'{str(i).rjust(5)}: {line}' + return context + + +FRAME_INFO_TEMPLATE = """File: +{file_path}:{lineno} +---------------------------------------------------------------------------------------------------- +Code context: +{code_context} +---------------------------------------------------------------------------------------------------- +Local variables: +{local_vars} +==================================================================================================== +""" + + +def _format_frame_info(frame_info: inspect.FrameInfo) -> str: + return FRAME_INFO_TEMPLATE.format( + file_path=frame_info.filename, + lineno=frame_info.lineno, + code_context=_format_code_context(frame_info), + local_vars=_format_vars(frame_info.frame.f_locals) + ) + + +STACK_TRACE_TEMPLATE = """ +#################################################################################################### + Stack Trace +==================================================================================================== +{stack_trace} +************************************* End of diagnostic info *************************************** +""" + + +def _format_stack_trace(frames: Iterable[inspect.FrameInfo]) -> str: + stack_trace = '' + for frame_info in frames: + stack_trace += _format_frame_info(frame_info) + return STACK_TRACE_TEMPLATE.format(stack_trace=stack_trace) + + +EXCEPTION_TEMPLATE = """ +#################################################################################################### + Exception Diagnostic Info +---------------------------------------------------------------------------------------------------- +Exception type : {exc_type} +Exception message : {exc} +System info : {system_info} +Python version : {python_version} +Kodi version : {kodi_version} +sys.argv : {sys_argv} +---------------------------------------------------------------------------------------------------- +sys.path: +{sys_path} +{stack_trace_info} +""" + + +def format_trace(frames_to_exclude: int = 1) -> str: + """ + Returns a pretty stack trace with code context and local variables + + Stack trace info includes the following: + + * File path and line number + * Code fragment + * Local variables + + It allows to inspect execution state at the point of this function call + + :param frames_to_exclude: How many top frames are excluded from the trace + to skip unnecessary info. Since each function call creates a stack frame + you need to exclude at least this function frame. + """ + frames = inspect.stack(5)[frames_to_exclude:] + return _format_stack_trace(reversed(frames)) + + +def format_exception(exc_obj: Optional[Exception] = None) -> str: + """ + Returns a pretty exception stack trace with code context and local variables + + :param exc_obj: exception object (optional) + :raises ValueError: if no exception is being handled + """ + if exc_obj is None: + _, exc_obj, _ = sys.exc_info() + if exc_obj is None: + raise ValueError('No exception is currently being handled') + stack_trace = inspect.getinnerframes(exc_obj.__traceback__, context=5) + stack_trace_info = _format_stack_trace(stack_trace) + message = EXCEPTION_TEMPLATE.format( + exc_type=exc_obj.__class__.__name__, + exc=exc_obj, + system_info=uname(), + python_version=sys.version.replace('\n', ' '), + kodi_version=xbmc.getInfoLabel('System.BuildVersion'), + sys_argv=pformat(sys.argv), + sys_path=pformat(sys.path), + stack_trace_info=stack_trace_info + ) + return message + + +@contextmanager +def catch_exception(logger_func: Callable[[str], None] = _log_error) -> Generator[None, None, 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 + - Python version + - Kodi version + - Module path. + - Stack trace including: + * File path and line number where the exception happened + * Code fragment where the exception has happened. + * Local variables at the moment of the exception. + + After logging the diagnostic info the exception is re-raised. + + Example:: + + with catch_exception(): + # Some risky code + raise RuntimeError('Fatal error!') + + :param logger_func: logger function that accepts a single argument + that is a log message. + """ + try: + yield + except Exception as exc: + message = format_exception(exc) + # pylint: disable=line-too-long + logger_func('\n*********************************** Unhandled exception detected ***********************************\n' + + message) + raise diff --git a/plugin.video.external.library/libs/exceptions.py b/plugin.video.external.library/libs/exceptions.py new file mode 100644 index 000000000..39d11741b --- /dev/null +++ b/plugin.video.external.library/libs/exceptions.py @@ -0,0 +1,22 @@ +# (c) Roman Miroshnychenko 2020 +# +# 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 . + + +class NoDataError(Exception): + pass + + +class RemoteKodiError(ConnectionError): + pass diff --git a/plugin.video.external.library/libs/json_rpc_api.py b/plugin.video.external.library/libs/json_rpc_api.py new file mode 100644 index 000000000..4108ed727 --- /dev/null +++ b/plugin.video.external.library/libs/json_rpc_api.py @@ -0,0 +1,284 @@ +# Copyright (C) 2023, Roman Miroshnychenko aka Roman V.M. +# +# 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 . +"""Classes and functions responsible for interacting with the remote JSON-RPC API""" + +import logging +from pprint import pformat +from typing import List, Dict, Any + +from libs import simple_requests as requests +from libs.exceptions import NoDataError, RemoteKodiError +from libs.kodi_service import ADDON, get_remote_kodi_url + +logger = logging.getLogger(__name__) + + +class BaseJsonRpcApi: + kodi_url = get_remote_kodi_url(with_credentials=False) + method: str + + def send_json_rpc(self): + """ + Send JSON-RPC to remote Kodi + """ + request = { + 'jsonrpc': '2.0', + 'method': self.method, + 'params': self.get_params(), + 'id': '1', + } + logger.debug('JSON-RPC request: %s', pformat(request)) + auth = None + login = ADDON.getSetting('kodi_login') + password = ADDON.getSetting('kodi_password') + if login: + auth = (login, password) + try: + json_reply = requests.post(self.kodi_url + '/jsonrpc', json=request, + auth=auth, verify=False).json() + except requests.RequestException as exc: + raise RemoteKodiError(self.kodi_url) from exc + logger.debug('JSON-RPC reply: %s', pformat(json_reply)) + return json_reply + + def get_params(self) -> Dict[str, Any]: + """Get params to send to Kodi JSON-RPC API""" + raise NotImplementedError + + +class BaseMediaItemsRetriever(BaseJsonRpcApi): + properties: List[str] + sort = Dict[str, str] + + def __init__(self, content, tvshowid=None, season=None): + self._content = content + self._tvshowid = tvshowid + self._season = season + + def get_params(self) -> Dict[str, Any]: + params = { + 'properties': self.properties, + 'sort': self.sort, + } + if self._tvshowid is not None: + params['tvshowid'] = self._tvshowid + if self._season is not None: + params['season'] = self._season + return params + + def get_media_items(self) -> List[Dict[str, Any]]: + """ + Get the list of media items for Kodi database + + :raises: NoDataError when media items are not retrieved via JSON-RPC + """ + try: + return self.send_json_rpc()['result'][self._content] + except KeyError as exc: + raise NoDataError( + f'Unable to retrieve {self._content} from remote media library') from exc + + +class GetMovies(BaseMediaItemsRetriever): + method = 'VideoLibrary.GetMovies' + properties = [ + 'title', + 'genre', + 'year', + 'rating', + 'director', + 'trailer', + 'tagline', + 'plot', + 'plotoutline', + 'originaltitle', + 'playcount', + 'writer', + 'studio', + 'mpaa', + 'cast', + 'country', + 'streamdetails', + 'top250', + 'votes', + 'file', + 'sorttitle', + 'resume', + 'dateadded', + 'art', + 'premiered', + ] + sort = {'order': 'ascending', 'method': 'label'} + + +class GetRecentlyAddedMovies(GetMovies): + method = 'VideoLibrary.GetRecentlyAddedMovies' + sort = {'order': 'descending', 'method': 'dateadded'} + + +class GetTVShows(BaseMediaItemsRetriever): + method = 'VideoLibrary.GetTVShows' + properties = [ + 'title', + 'genre', + 'year', + 'rating', + 'plot', + 'studio', + 'mpaa', + 'cast', + 'episode', + 'playcount', + 'premiered', + 'votes', + 'file', + 'originaltitle', + 'sorttitle', + 'season', + 'watchedepisodes', + 'dateadded', + 'tag', + 'art', + 'userrating', + 'ratings', + 'runtime', + 'uniqueid', + ] + sort = {'order': 'ascending', 'method': 'label'} + + +class GetSeasons(BaseMediaItemsRetriever): + method = 'VideoLibrary.GetSeasons' + properties = [ + 'season', + 'showtitle', + 'playcount', + 'episode', + 'tvshowid', + 'watchedepisodes', + 'art', + 'title', + ] + sort = {'order': 'ascending', 'method': 'season'} + + +class GetEpisodes(BaseMediaItemsRetriever): + method = 'VideoLibrary.GetEpisodes' + properties = [ + 'title', + 'plot', + 'votes', + 'rating', + 'writer', + 'firstaired', + 'playcount', + 'runtime', + 'director', + 'productioncode', + 'season', + 'episode', + 'originaltitle', + 'showtitle', + 'cast', + 'streamdetails', + 'file', + 'resume', + 'tvshowid', + 'dateadded', + 'uniqueid', + 'art', + 'specialsortseason', + 'specialsortepisode', + 'seasonid', + ] + sort = {'order': 'ascending', 'method': 'label'} + + +class GetRecentlyAddedEpisodes(GetEpisodes): + method = 'VideoLibrary.GetRecentlyAddedEpisodes' + sort = {'order': 'descending', 'method': 'dateadded'} + + +class GetMusicVideos(BaseMediaItemsRetriever): + method = 'VideoLibrary.GetMusicVideos' + properties = [ + 'title', + 'playcount', + 'runtime', + 'director', + 'studio', + 'year', + 'plot', + 'album', + 'artist', + 'genre', + 'track', + 'streamdetails', + 'lastplayed', + 'file', + 'resume', + 'dateadded', + 'art', + 'rating', + 'premiered', + ] + sort = {'order': 'ascending', 'method': 'label'} + + +class GetRecentlyAddedMusicVideos(GetMusicVideos): + method = 'VideoLibrary.GetRecentlyAddedMusicVideos' + sort = {'order': 'descending', 'method': 'dateadded'} + + +class SetMovieDetails(BaseJsonRpcApi): + method = 'VideoLibrary.SetMovieDetails' + + def __init__(self): + super().__init__() + self._params = None + + def get_params(self) -> Dict[str, Any]: + return self._params + + def set_details(self, **kwargs): + self._params = kwargs + self.send_json_rpc() + + +class SetEpisodeDetails(SetMovieDetails): + method = 'VideoLibrary.SetEpisodeDetails' + + +SET_DETAILS_API_MAP = { + 'movieid': SetMovieDetails, + 'episodeid': SetEpisodeDetails, +} + + +def update_playcount(item_id_param, item_id, playcount): + api_class = SET_DETAILS_API_MAP[item_id_param] + api = api_class() + kwargs = { + item_id_param: item_id, + 'playcount': playcount, + 'resume': {'position': 0.0, 'total': 0.0}, + } + api.set_details(**kwargs) + + +def update_resume(item_id_param, item_id, position, total): + api_class = SET_DETAILS_API_MAP[item_id_param] + api = api_class() + api.set_details(**{item_id_param: item_id, 'resume': {'position': position, 'total': total}}) diff --git a/plugin.video.external.library/libs/kodi_service.py b/plugin.video.external.library/libs/kodi_service.py new file mode 100644 index 000000000..f0848614b --- /dev/null +++ b/plugin.video.external.library/libs/kodi_service.py @@ -0,0 +1,191 @@ +# (c) Roman Miroshnychenko 2020 +# +# 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 . + +"""Classes and functions to interact with Kodi API""" +import hashlib +import json +import logging +import re +from pathlib import Path +from urllib.parse import urlencode + +import xbmc +from xbmcaddon import Addon +from xbmcvfs import translatePath + +from libs.exception_logger import format_trace, format_exception + +ADDON = Addon() +ADDON_ID = ADDON.getAddonInfo('id') +ADDON_NAME = ADDON.getAddonInfo('name') +ADDON_VERSION = ADDON.getAddonInfo('version') + +ADDON_DIR = Path(translatePath(ADDON.getAddonInfo('path'))) +ADDON_ICON = Path(translatePath(ADDON.getAddonInfo('icon'))) +ADDON_PROFILE_DIR = Path(translatePath(ADDON.getAddonInfo('profile'))) + +PLUGIN_URL = f'plugin://{ADDON_ID}/' + +LOG_FORMAT = '[{addon_id} v.{addon_version}] {filename}:{lineno} - {message}' + + +class KodiLogHandler(logging.Handler): + """ + Logging handler that writes to the Kodi log with correct levels + + It also adds {addon_id} and {addon_version} variables available to log format. + """ + LEVEL_MAP = { + logging.NOTSET: xbmc.LOGNONE, + logging.DEBUG: xbmc.LOGDEBUG, + logging.INFO: xbmc.LOGINFO, + logging.WARN: xbmc.LOGWARNING, + logging.WARNING: xbmc.LOGWARNING, + logging.ERROR: xbmc.LOGERROR, + logging.CRITICAL: xbmc.LOGFATAL, + } + + def emit(self, record): + record.addon_id = ADDON_ID + record.addon_version = ADDON_VERSION + extended_trace_info = getattr(self, 'extended_trace_info', False) + if extended_trace_info: + if record.exc_info is not None: + record.exc_text = format_exception(record.exc_info[1]) + if record.stack_info is not None: + record.stack_info = format_trace(7) + message = self.format(record) + kodi_log_level = self.LEVEL_MAP.get(record.levelno, xbmc.LOGDEBUG) + xbmc.log(message, level=kodi_log_level) + + +class GettextEmulator: + """ + Emulate GNU Gettext by mapping resource.language.en_gb UI strings to their numeric string IDs + """ + _instance = None + + class LocalizationError(Exception): # pylint: disable=missing-docstring + pass + + def __new__(cls): + if cls._instance is None: + cls._instance = super().__new__(cls) + return cls._instance + + def __init__(self): + self._en_gb_string_po_path = (ADDON_DIR / 'resources' / 'language' / + 'resource.language.en_gb' / 'strings.po') + if not self._en_gb_string_po_path.exists(): + raise self.LocalizationError( + 'Missing resource.language.en_gb strings.po localization file') + if not ADDON_PROFILE_DIR.exists(): + ADDON_PROFILE_DIR.mkdir() + self._string_mapping_path = ADDON_PROFILE_DIR / 'strings-map.json' + self.strings_mapping = self._load_strings_mapping() + + def _load_strings_po(self): # pylint: disable=missing-docstring + with self._en_gb_string_po_path.open('r', encoding='utf-8') as fo: + return fo.read() + + def _load_strings_mapping(self): + """ + Load mapping of resource.language.en_gb UI strings to their IDs + + If a mapping file is missing or resource.language.en_gb strins.po file has been updated, + a new mapping file is created. + + :return: UI strings mapping + """ + strings_po = self._load_strings_po() + strings_po_md5 = hashlib.md5(strings_po.encode('utf-8')).hexdigest() + try: + with self._string_mapping_path.open('r', encoding='utf-8') as fo: + mapping = json.load(fo) + if mapping['md5'] != strings_po_md5: + raise IOError('resource.language.en_gb strings.po has been updated') + except (IOError, ValueError): + strings_mapping = self._parse_strings_po(strings_po) + mapping = { + 'strings': strings_mapping, + 'md5': strings_po_md5, + } + with self._string_mapping_path.open('w', encoding='utf-8') as fo: + json.dump(mapping, fo) + return mapping['strings'] + + @staticmethod + def _parse_strings_po(strings_po): + """ + Parse resource.language.en_gb strings.po file contents into a mapping of UI strings + to their numeric IDs. + + :param strings_po: the content of strings.po file as a text string + :return: UI strings mapping + """ + id_string_pairs = re.findall(r'^msgctxt "#(\d+?)"\r?\nmsgid "(.*)"\r?$', strings_po, re.M) + return {string: int(string_id) for string_id, string in id_string_pairs if string} + + @classmethod + def gettext(cls, en_string: str) -> str: + """ + Return a localized UI string by a resource.language.en_gb source string + + :param en_string: resource.language.en_gb UI string + :return: localized UI string + """ + emulator = cls() + try: + string_id = emulator.strings_mapping[en_string] + except KeyError as exc: + raise cls.LocalizationError( + f'Unable to find "{en_string}" string in resource.language.en_gb/strings.po' + ) from exc + return ADDON.getLocalizedString(string_id) + + +def initialize_logging(extended_trace_info=True): + """ + Initialize the root logger that writes to the Kodi log + + After initialization, you can use Python logging facilities as usual. + + :param extended_trace_info: write extended trace info when exc_info=True + or stack_info=True parameters are passed to logging methods. + """ + handler = KodiLogHandler() + # pylint: disable=attribute-defined-outside-init + handler.extended_trace_info = extended_trace_info + logging.basicConfig( + format=LOG_FORMAT, + style='{', + level=logging.DEBUG, + handlers=[handler], + force=True + ) + + +def get_plugin_url(**kwargs): + return f'{PLUGIN_URL}?{urlencode(kwargs)}' + + +def get_remote_kodi_url(with_credentials=False): + host = ADDON.getSetting('kodi_host') + port = ADDON.getSetting('kodi_port') + login = ADDON.getSetting('kodi_login') + password = ADDON.getSetting('kodi_password') + if not with_credentials or not login: + return f'http://{host}:{port}' + return f'http://{login}:{password}@{host}:{port}' diff --git a/plugin.video.external.library/libs/media_info_service.py b/plugin.video.external.library/libs/media_info_service.py new file mode 100644 index 000000000..7e6a1a21a --- /dev/null +++ b/plugin.video.external.library/libs/media_info_service.py @@ -0,0 +1,218 @@ +# Copyright (C) 2023, Roman Miroshnychenko aka Roman V.M. +# +# 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 . +""" +Classes and functions that process data from JSON-RPC API and assign them to ListItem instances +""" + +from typing import Dict, Any, List, Tuple, Type, Iterable, Union +from urllib.parse import urljoin, quote + +import xbmc +from xbmc import InfoTagVideo, Actor +from xbmcgui import ListItem + +from libs.kodi_service import get_remote_kodi_url + +__all__ = ['set_info', 'set_art'] + +REMOTE_KODI_URL = get_remote_kodi_url(with_credentials=True) +IMAGE_URL = urljoin(REMOTE_KODI_URL, 'image') + +StreamDetailsType = Union[xbmc.VideoStreamDetail, xbmc.AudioStreamDetail, xbmc.SubtitleStreamDetail] + + +class SimpleMediaPropertySetter: + """ + Sets a media property from a dictionary returned by JSON-RPC API to + xbmc.InfoTagVideo class instance + """ + + def __init__(self, media_property: str, media_info: Dict[str, Any], info_tag_method: str): + self._property_value = media_info.get(media_property) + self._info_tag_method = info_tag_method + + def should_set(self) -> bool: + return bool(self._property_value) + + def get_method_args(self) -> Iterable[Any]: + return (self._property_value,) + + def set_info_tag_property(self, info_tag: InfoTagVideo) -> None: + args = self.get_method_args() + method = getattr(info_tag, self._info_tag_method) + method(*args) + + +class NotNoneValueSetter(SimpleMediaPropertySetter): + + def should_set(self) -> bool: + return self._property_value is not None + + +class CastSetter(SimpleMediaPropertySetter): + + def get_method_args(self) -> Iterable[Any]: + actors = [] + for actor_info in self._property_value: + actor_thumbnail = actor_info.get('thumbnail', '') + if actor_thumbnail: + actor_thumbnail = f'{IMAGE_URL}/{quote(actor_thumbnail)}' + actors.append(Actor( + name=actor_info.get('name', ''), + role=actor_info.get('role', ''), + order=actor_info.get('order') or -1, + thumbnail=actor_thumbnail + )) + return (actors,) + + +class ResumePointSetter(SimpleMediaPropertySetter): + + def get_method_args(self) -> Iterable[Any]: + time = self._property_value.get('position', 0.0) + totaltime = self._property_value.get('total', 0.0) + return time, totaltime + + +class VideoStreamSetter(SimpleMediaPropertySetter): + stream_type = 'video' + stream_type_class = xbmc.VideoStreamDetail + + def should_set(self) -> bool: + return bool(self._property_value and self._property_value.get(self.stream_type)) + + @staticmethod + def get_stream_type_args(stream_dict: Dict[str, Any]) -> Iterable[Any,]: + return ( + stream_dict['width'], + stream_dict['height'], + stream_dict['aspect'], + stream_dict['duration'], + stream_dict['codec'], + stream_dict['stereomode'], + stream_dict['language'], + stream_dict['hdrtype'], + ) + + def _get_stream_type_object(self, stream_dict) -> StreamDetailsType: + args = self.get_stream_type_args(stream_dict) + return self.stream_type_class(*args) + + def get_method_args(self) -> Iterable[Any]: + args_list = [] + for stream_dict in self._property_value[self.stream_type]: + stream_type_obj = self._get_stream_type_object(stream_dict) + args_list.append(stream_type_obj) + return args_list + + def set_info_tag_property(self, info_tag: InfoTagVideo) -> None: + method = getattr(info_tag, self._info_tag_method) + args_list = self.get_method_args() + for arg in args_list: + method(arg) + + +class AudioStreamSetter(VideoStreamSetter): + stream_type = 'audio' + stream_type_class = xbmc.AudioStreamDetail + + @staticmethod + def get_stream_type_args(stream_dict: Dict[str, Any]) -> Iterable[Any]: + return ( + stream_dict['channels'], + stream_dict['codec'], + stream_dict['language'], + ) + + +class SubtitleStreamSetter(VideoStreamSetter): + stream_type = 'subtitle' + stream_type_class = xbmc.SubtitleStreamDetail + + @staticmethod + def get_stream_type_args(stream_dict: Dict[str, Any]) -> Iterable[Any]: + return (stream_dict['language'],) + + +class NonNegativeValueSetter(SimpleMediaPropertySetter): + + def should_set(self) -> bool: + return self._property_value is not None and self._property_value >= 0 + + +class IntAsStringValueSetter(SimpleMediaPropertySetter): + + def should_set(self) -> bool: + return bool(self._property_value + and self._property_value.isdigit() + and int(self._property_value)) + + def get_method_args(self) -> Iterable[Any]: + return (int(self._property_value),) + + +# The list of 3 element tuples: ( +# media property name as returned by JSON-RPC call, +# xbmc.InfoTagVideo method name, +# media property handler class, +# ) +MEDIA_PROPERTIES: List[Tuple[str, str, Type[SimpleMediaPropertySetter]]] = [ + ('title', 'setTitle', SimpleMediaPropertySetter), + ('genre', 'setGenres', SimpleMediaPropertySetter), + ('year', 'setYear', SimpleMediaPropertySetter), + ('rating', 'setRating', SimpleMediaPropertySetter), + ('director', 'setDirectors', SimpleMediaPropertySetter), + ('trailer', 'setTrailer', SimpleMediaPropertySetter), + ('tagline', 'setTagLine', SimpleMediaPropertySetter), + ('plot', 'setPlot', SimpleMediaPropertySetter), + ('plotoutline', 'setPlotOutline', SimpleMediaPropertySetter), + ('playcount', 'setPlaycount', NotNoneValueSetter), + ('writer', 'setWriters', SimpleMediaPropertySetter), + ('studio', 'setStudios', SimpleMediaPropertySetter), + ('mpaa', 'setMpaa', SimpleMediaPropertySetter), + ('cast', 'setCast', CastSetter), + ('country', 'setCountries', SimpleMediaPropertySetter), + ('streamdetails', 'addVideoStream', VideoStreamSetter), + ('streamdetails', 'addAudioStream', AudioStreamSetter), + ('streamdetails', 'addSubtitleStream', SubtitleStreamSetter), + ('top250', 'setTop250', SimpleMediaPropertySetter), + ('votes', 'setVotes', IntAsStringValueSetter), + ('sorttitle', 'setSortTitle', SimpleMediaPropertySetter), + ('resume', 'setResumePoint', ResumePointSetter), + ('dateadded', 'setDateAdded', SimpleMediaPropertySetter), + ('premiered', 'setPremiered', SimpleMediaPropertySetter), + ('season', 'setSeason', SimpleMediaPropertySetter), + ('episode', 'setEpisode', SimpleMediaPropertySetter), + ('showtitle', 'setTvShowTitle', SimpleMediaPropertySetter), + ('productioncode', 'setProductionCode', SimpleMediaPropertySetter), + ('specialsortseason', 'setSortSeason', NonNegativeValueSetter), + ('specialsortepisode', 'setSortEpisode', NonNegativeValueSetter), + ('album', 'setAlbum', SimpleMediaPropertySetter), + ('artist', 'setArtists', SimpleMediaPropertySetter), + ('track', 'setTrack', NonNegativeValueSetter), +] + + +def set_info(info_tag: InfoTagVideo, media_info: Dict[str, Any], mediatype: str) -> None: + info_tag.setMediaType(mediatype) + for media_property, info_tag_method, setter_class in MEDIA_PROPERTIES: + setter = setter_class(media_property, media_info, info_tag_method) + if setter.should_set(): + setter.set_info_tag_property(info_tag) + + +def set_art(list_item: ListItem, raw_art: Dict[str, str]) -> None: + art = {art_type: f'{IMAGE_URL}/{quote(raw_url)}' for art_type, raw_url in raw_art.items()} + list_item.setArt(art) diff --git a/plugin.video.external.library/libs/mem_storage.py b/plugin.video.external.library/libs/mem_storage.py new file mode 100644 index 000000000..577002120 --- /dev/null +++ b/plugin.video.external.library/libs/mem_storage.py @@ -0,0 +1,49 @@ +# Copyright (C) 2023, Roman Miroshnychenko aka Roman V.M. +# +# 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 . +"""In-memory storage""" + +import json + +import xbmcgui + + +class MemStorage: + """ + Stores a JSON-serializable Python object in a shared memory within Kodi + + It can be used to exchange data between different Python scripts running inside Kodi. + """ + def __init__(self, window_id=10000): + self._window = xbmcgui.Window(window_id) + + def __getitem__(self, key): + try: + json_string = self._window.getProperty(key) + return json.loads(json_string) + except ValueError as exc: + raise KeyError(f'Item "{key}" cannot be retrieved from MemStorage') from exc + + def __setitem__(self, key, value): + try: + json_string = json.dumps(value) + except (TypeError, ValueError) as exc: + raise ValueError(f'Item {key}:{value} cannot be stored in MemStorage') from exc + self._window.setProperty(key, json_string) + + def get(self, key, default=None): + try: + return self[key] + except KeyError: + return default diff --git a/plugin.video.external.library/libs/monitor.py b/plugin.video.external.library/libs/monitor.py new file mode 100644 index 000000000..dd65ccc1b --- /dev/null +++ b/plugin.video.external.library/libs/monitor.py @@ -0,0 +1,122 @@ +# Copyright (C) 2023, Roman Miroshnychenko aka Roman V.M. +# +# 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 . +# pylint: disable=broad-exception-caught,attribute-defined-outside-init +"""Playback progress monitor""" + +import logging +from urllib.parse import quote + +import xbmc + +from libs import json_rpc_api +from libs.kodi_service import ADDON +from libs.mem_storage import MemStorage + +logger = logging.getLogger(__name__) + + +class PlayMonitor(xbmc.Player): + """ + Monitors playback status and updates watches status + for an episode or a movie from an external library + """ + def __init__(self): + super().__init__() + self._mem_storage = MemStorage() + self._clear_state() + + def _clear_state(self): + self.is_monitoring = False + self._current_time = -1 + self._total_time = -1 + self._playing_file = None + self._item_info = None + + def onPlayBackStarted(self): + self._playing_file = self.getPlayingFile() + self._item_info = self._get_item_info() + if self._item_info is None: + self._clear_state() + return + self.is_monitoring = True + try: + self._total_time = self.getTotalTime() + except Exception: + self._total_time = -1 + logger.debug('Started monitoring %s', self._playing_file) + + def onPlayBackStopped(self): + self._send_played_file_state() + self._clear_state() + logger.debug('Stopped monitoring %s. Playback stopped.', self._playing_file) + + def onPlayBackEnded(self): + self._send_played_file_state() + self._clear_state() + logger.debug('Stopped monitoring %s. Playback ended.', self._playing_file) + + def onPlayBackPaused(self): + if self._should_send_resume(): + self._send_resume() + logger.debug('Paused monitoring %s', self._playing_file) + + def update_time(self): + try: + self._current_time = self.getTime() + except Exception: + self._current_time = -1 + if self._total_time <= 0: + try: + self._total_time = self.getTotalTime() + except Exception: + self._total_time = -1 + + def _get_item_info(self): + if listing := self._mem_storage.get('__external_library_list__'): + files_on_shares = ADDON.getSettingBool('files_on_shares') + for item in listing: + if files_on_shares and item['file'] == self._playing_file: + return item + if quote(item['file']) in self._playing_file: + return item + return None + + def _should_send_playcount(self): + watched_threshold = ADDON.getSettingInt('watched_threshold_percent') / 100 + return (self._current_time != -1 and self._total_time > 0 + and (self._current_time / self._total_time) >= watched_threshold) + + def _send_playcount(self): + logger.debug('Updating playcount for %s %s', self._item_info, self._playing_file) + item_id_param = self._item_info['item_id_param'] + new_playcount = self._item_info['playcount'] + 1 + json_rpc_api.update_playcount(item_id_param, self._item_info[item_id_param], new_playcount) + + def _should_send_resume(self): + return (self._current_time != -1 + and self._total_time != -1 + and self._current_time > ADDON.getSettingInt('playtime_to_skip')) + + def _send_resume(self): + logger.debug('Updating resume for %s %s', self._item_info, self._playing_file) + item_id_param = self._item_info['item_id_param'] + json_rpc_api.update_resume(item_id_param, self._item_info[item_id_param], + self._current_time, self._total_time) + + def _send_played_file_state(self): + if self._should_send_playcount(): + self._send_playcount() + elif self._should_send_resume(): + self._send_resume() diff --git a/plugin.video.external.library/libs/simple_requests.py b/plugin.video.external.library/libs/simple_requests.py new file mode 100644 index 000000000..9161b5038 --- /dev/null +++ b/plugin.video.external.library/libs/simple_requests.py @@ -0,0 +1,252 @@ +# Copyright (c) 2021, Roman Miroshnychenko +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +""" +A simple library for making HTTP requests with API similar to the popular "requests" library + +It depends only on the Python standard library. + +Supported: +* HTTP methods: GET, POST +* HTTP and HTTPS. +* Disabling SSL certificates validation. +* Request payload as form data and JSON. +* Custom headers. +* Basic authentication. +* Gzipped response content. + +Not supported: +* Cookies. +* File upload. +""" +import gzip +import io +import json as _json +import ssl +from base64 import b64encode +from email.message import Message +from typing import Optional, Dict, Any, Tuple, Union, List, BinaryIO +from urllib import request as url_request +from urllib.error import HTTPError as _HTTPError +from urllib.parse import urlparse, urlencode + +__all__ = [ + 'RequestException', + 'ConnectionError', + 'HTTPError', + 'get', + 'post', +] + + +class RequestException(IOError): + + def __repr__(self) -> str: + return self.__str__() + + +class ConnectionError(RequestException): + + def __init__(self, message: str, url: str): + super().__init__(message) + self.message = message + self.url = url + + def __str__(self) -> str: + return f'ConnectionError for url {self.url}: {self.message}' + + +class HTTPError(RequestException): + + def __init__(self, response: 'Response'): + self.response = response + + def __str__(self) -> str: + return f'HTTPError: {self.response.status_code} for url: {self.response.url}' + + +class HTTPMessage(Message): + + def update(self, dct: Dict[str, str]) -> None: + for key, value in dct.items(): + self[key] = value + + +class Response: + NULL = object() + + def __init__(self): + self.encoding: str = 'utf-8' + self.status_code: int = -1 + self.headers: Dict[str, str] = {} + self.url: str = '' + self.content: bytes = b'' + self._text = None + self._json = self.NULL + + def __str__(self) -> str: + return f'' + + def __repr__(self) -> str: + return self.__str__() + + @property + def ok(self) -> bool: + return self.status_code < 400 + + @property + def text(self) -> str: + """ + :return: Response payload as decoded text + """ + if self._text is None: + self._text = self.content.decode(self.encoding) + return self._text + + def json(self) -> Optional[Union[Dict[str, Any], List[Any]]]: + try: + if self._json is self.NULL: + self._json = _json.loads(self.content) + return self._json + except ValueError as exc: + raise ValueError('Response content is not a valid JSON') from exc + + def raise_for_status(self) -> None: + if not self.ok: + raise HTTPError(self) + + +def _create_request(url_structure, params=None, data=None, headers=None, auth=None, json=None): + query = url_structure.query + if params is not None: + separator = '&' if query else '' + query += separator + urlencode(params, doseq=True) + full_url = url_structure.scheme + '://' + url_structure.netloc + url_structure.path + if query: + full_url += '?' + query + prepared_headers = HTTPMessage() + if headers is not None: + prepared_headers.update(headers) + body = None + if json is not None: + body = _json.dumps(json).encode('utf-8') + prepared_headers['Content-Type'] = 'application/json' + if body is None and isinstance(data, dict): + body = urlencode(data, doseq=True).encode('ascii') + prepared_headers['Content-Type'] = 'application/x-www-form-urlencoded' + if body is None and isinstance(data, bytes): + body = data + if body is None and isinstance(data, str): + body = data.encode('utf-8') + if body is None and hasattr(data, 'read'): + body = data.read() + if hasattr(data, 'close'): + data.close() + if body is not None and 'Content-Type' not in prepared_headers: + prepared_headers['Content-Type'] = 'application/octet-stream' + if auth is not None: + encoded_credentials = b64encode((auth[0] + ':' + auth[1]).encode('utf-8')).decode('ascii') + prepared_headers['Authorization'] = f'Basic {encoded_credentials}' + if 'Accept-Encoding' not in prepared_headers: + prepared_headers['Accept-Encoding'] = 'gzip' + return url_request.Request(full_url, body, prepared_headers) + + +def post(url: str, + params: Optional[Dict[str, Any]] = None, + data: Optional[Union[Dict[str, Any], str, bytes, BinaryIO]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + verify: bool = True, + json: Optional[Dict[str, Any]] = None) -> Response: + """ + POST request + + This function assumes that a request body should be encoded with UTF-8 + and by default sends Accept-Encoding: gzip header to receive response content compressed. + + :param url: URL + :param params: URL query params + :param data: request payload as dict, str, bytes or a binary file object. + If "data" or "json" is passed then a POST request is sent. + For str, bytes or file object it's caller's responsibility to provide a proper + 'Content-Type' header. + :param headers: additional headers + :param auth: a tuple of (login, password) for Basic authentication + :param timeout: request timeout in seconds + :param verify: verify SSL certificates + :param json: request payload as JSON. This parameter has precedence over "data", that is, + if it's present then "data" is ignored. + :return: Response object + """ + url_structure = urlparse(url) + request = _create_request(url_structure, params, data, headers, auth, json) + context = None + if url_structure.scheme == 'https': + context = ssl.SSLContext() + if not verify: + context.verify_mode = ssl.CERT_NONE + context.check_hostname = False + fp = None + try: + r = fp = url_request.urlopen(request, timeout=timeout, context=context) + content = fp.read() + except _HTTPError as exc: + r = exc + fp = exc.fp + content = fp.read() + except Exception as exc: + raise ConnectionError(str(exc), request.full_url) from exc + finally: + if fp is not None: + fp.close() + response = Response() + response.status_code = r.status if hasattr(r, 'status') else r.getstatus() + response.headers = r.headers + response.url = r.url if hasattr(r, 'url') else r.geturl() + if r.headers.get('Content-Encoding') == 'gzip': + temp_fo = io.BytesIO(content) + gzip_file = gzip.GzipFile(fileobj=temp_fo) + content = gzip_file.read() + response.content = content + return response + + +def get(url: str, + params: Optional[Dict[str, Any]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + verify: bool = True) -> Response: + """ + GET request + + This function by default sends Accept-Encoding: gzip header + to receive response content compressed. + + :param url: URL + :param params: URL query params + :param headers: additional headers + :param auth: a tuple of (login, password) for Basic authentication + :param timeout: request timeout in seconds + :param verify: verify SSL certificates + :return: Response object + """ + return post(url=url, params=params, headers=headers, auth=auth, timeout=timeout, verify=verify) diff --git a/plugin.video.external.library/main.py b/plugin.video.external.library/main.py new file mode 100644 index 000000000..4ddcfc95e --- /dev/null +++ b/plugin.video.external.library/main.py @@ -0,0 +1,28 @@ +# Copyright (C) 2023, Roman Miroshnychenko aka Roman V.M. +# +# 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 . + +import sys +import logging + +from libs.actions import router +from libs.exception_logger import catch_exception +from libs.kodi_service import initialize_logging + +initialize_logging() +logger = logging.getLogger(__name__) + +if __name__ == '__main__': + with catch_exception(logger.error): + router(sys.argv[2][1:]) diff --git a/plugin.video.external.library/resources/language/resource.language.en_gb/strings.po b/plugin.video.external.library/resources/language/resource.language.en_gb/strings.po new file mode 100644 index 000000000..50e91402d --- /dev/null +++ b/plugin.video.external.library/resources/language/resource.language.en_gb/strings.po @@ -0,0 +1,124 @@ +# Kodi Media Center language file +msgid "" +msgstr "" + +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: en\n" + + +msgctxt "#32000" +msgid "Access" +msgstr "" + +msgctxt "#32001" +msgid "Remote Kodi host" +msgstr "" + +msgctxt "#32002" +msgid "Remote Kodi port" +msgstr "" + +msgctxt "#32003" +msgid "Movies" +msgstr "" + +msgctxt "#32004" +msgid "Recently added movies" +msgstr "" + +msgctxt "#32005" +msgid "TV Shows" +msgstr "" + +msgctxt "#32006" +msgid "Recently added episodes" +msgstr "" + +msgctxt "#32007" +msgid "Unable to connect to the remote Kodi host!" +msgstr "" + +msgctxt "#32008" +msgid "Unable to retrieve data from the remote Kodi library!" +msgstr "" + +msgctxt "#32009" +msgid "Flatten TV show seasons" +msgstr "" + +msgctxt "#32010" +msgid "Mark as watched" +msgstr "" + +msgctxt "#32011" +msgid "Mark as unwatched" +msgstr "" + +msgctxt "#32012" +msgid "Watched status threshold" +msgstr "" + +msgctxt "#32013" +msgid "Kodi login" +msgstr "" + +msgctxt "#32014" +msgid "Kodi password" +msgstr "" + +msgctxt "#32015" +msgid "Kodi hostname or IP address (without protocol)" +msgstr "" + +msgctxt "#32016" +msgid "Kodi Medialibrary on {kodi_host}" +msgstr "" + +msgctxt "#32017" +msgid "Kodi External Video Library Client" +msgstr "" + +msgctxt "#32018" +msgid "Please run this addon from \"Video addons\" section." +msgstr "" + +msgctxt "#32019" +msgid "Mediafiles on network shares" +msgstr "" + +msgctxt "#32020" +msgid "Enable if your mediafiles are stored on network shares accessible from this device." +msgstr "" + +msgctxt "#32021" +msgid "Videolibrary Sections" +msgstr "" + +msgctxt "#32022" +msgid "Playback" +msgstr "" + +msgctxt "#32023" +msgid "Seasons" +msgstr "" + +msgctxt "#32024" +msgid "Playtime to start tracking progress (seconds)" +msgstr "" + +msgctxt "#32025" +msgid "Playtime after which the plugin starts tracking playback progress." +msgstr "" + +msgctxt "#32026" +msgid "Playback percentage after which the plugin marks a played video as watched." +msgstr "" + +msgctxt "#32027" +msgid "Music videos" +msgstr "" + +msgctxt "#32028" +msgid "Recently added music videos" +msgstr "" diff --git a/plugin.video.external.library/resources/settings.xml b/plugin.video.external.library/resources/settings.xml new file mode 100644 index 000000000..a28bba39f --- /dev/null +++ b/plugin.video.external.library/resources/settings.xml @@ -0,0 +1,126 @@ + + +
+ + + + 0 + + + true + + + 32001 + + + + 0 + 8080 + + 32002 + + + + 0 + + + true + + + 32013 + + + + 0 + + + true + + + 32014 + true + + + + + + + + 0 + true + + + + 0 + true + + + + 0 + true + + + + 0 + true + + + + 0 + 1 + + + + + + + + + + + 0 + true + + + + 0 + true + + + + + + + + 0 + false + + + + 0 + 60 + + 30 + 30 + 120 + + + false + + + + 0 + 95 + + 90 + 1 + 100 + + + false + + + + +
+
diff --git a/plugin.video.external.library/service.py b/plugin.video.external.library/service.py new file mode 100644 index 000000000..044f209ec --- /dev/null +++ b/plugin.video.external.library/service.py @@ -0,0 +1,36 @@ +# Copyright (C) 2023, Roman Miroshnychenko aka Roman V.M. +# +# 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 . + +import logging + +import xbmc + +from libs.exception_logger import catch_exception +from libs.kodi_service import initialize_logging +from libs.monitor import PlayMonitor + +initialize_logging() +logger = logging.getLogger(__name__) + +with catch_exception(logger.error): + logger.debug('Starting playback monitoring service...') + kodi_monitor = xbmc.Monitor() + play_monitor = PlayMonitor() + while not kodi_monitor.waitForAbort(1.0): + if (play_monitor.isPlayingVideo() + and not xbmc.getCondVisibility('Player.Paused') + and play_monitor.is_monitoring): + play_monitor.update_time() +logger.debug('Stopped playback monitoring service.')