diff --git a/service.watchedlist/LICENSE.txt b/service.watchedlist/LICENSE.txt new file mode 100644 index 0000000000..94a9ed024d --- /dev/null +++ b/service.watchedlist/LICENSE.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/service.watchedlist/addon.xml b/service.watchedlist/addon.xml new file mode 100644 index 0000000000..1c65ac43de --- /dev/null +++ b/service.watchedlist/addon.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + executable + + + + + Save watched state of movies and TV-series episodes independent from filenames + Gesehen-Status von Filmen und Serien-Episoden unabhängig von Dateinamen speichern + + Export: Searches the Kodi-Database for watched files. Determine imdb-id and thetvdb-id to identify movies and TV-episodes. Then save the list to a new independent table. + Import: Set the watched state for each video file in Kodi. + Automatic background process without user interaction. + + Export: Durchsucht die Kodi-Datenbank nach gesehenen Filmen und ordnet den Dateien die eindeutigen Kennnummern von imdb und TheTVDB zu. Gesehene Filme und Episoden werden jeweils in einer eigenen Datenbank gespeichert. + Import: Der Gesehen-Status von Medien in Kodi wird aus der Gesehenen-Tabelle geholt. + Die Synchronisierung geschieht automatisch im Hintergrund ohne Benutzereingriff. + This script does not regard the file format. A Movie watched in DVD quality will also set the 1080p version as watched. + Dieses Script ignoriert das Dateiformat. Ein gesehener Film in DVD-Qualität wird auch in der BlueRay-Version als gesehen gekennzeichnet. + all + GPL-2.0-or-later + https://forum.kodi.tv/showthread.php?tid=164652 + https://kodi.wiki/view/Add-on:WatchedList + https://github.com/SchapplM/xbmc-addon-service-watchedlist + 1.3.6 - Dependency update for Kodi Nexus + + icon.png + fanart.jpg + + + diff --git a/service.watchedlist/changelog.txt b/service.watchedlist/changelog.txt new file mode 100644 index 0000000000..f97056bf08 --- /dev/null +++ b/service.watchedlist/changelog.txt @@ -0,0 +1,109 @@ +version 1.3.5 (28.11.2021) +* Fix for inconsistent imdb/tvdb numbers and new database format + +version 1.3.4 (23.10.2021) +* Fix for The Movie Database scraper + +version 1.3.3 (01.08.2021) +* Fix for new python interface in Kodi v20 + +version 1.3 (24.04.2020) +* Updated to work with Python 3 + +version 1.2.7 (03.05.2019) +* Minor fixes (mysql access protection, remove credentials from log file) + +version 1.2.6 (16.02.2019) +* Fixed waiting time for periodic update during playback + +version 1.2.5 (04.01.2018) +* Fix SMB access in Windows, minor code improvements + +version 1.2.4 (01.01.2018) +* Fix in background user watching + +version 1.2.3 (28.12.2017) +* Minor fixes (unicode support, less blocking on shutdown, backup file rotation on network shares, error handling and logging) + +version 1.2.2 (23.12.2017) +* Minor fixes, fixed buggalo emails + +version 1.2.1 (26.11.2017) +* Fixed Dropbox API: Change from v1 to v2 + +version 1.2 (21.05.2017) +* Added API and python module to use this addon in other addons +* minor fixes + +version 1.1.4 (28.04.2017) + * Fixed error in English language file + +version 1.1.3 (16.04.2017) + * Added verbosity option for graphical user notifications + * Added limitation of number of backup files + +version 1.1.2 (12.06.2016) + * Added fix to avoid infinite waiting if startup delay time is 0 + +version 1.1.1 (29.05.2016) + * Added fix for non-working python dropbox import + +version 1.1.0 (02.04.2016) + * Added dropbox synchronization for the database + +version 1.0.5 (24.12.2015) + * Enabled IPv6 adresses for hostnames + +version 1.0.4 (16.05.2015) + * Fixed mysql timestamp bug + +version 1.0.3 (11.01.2015) + * Fixed wrong implementation of startup delay + * Fixed missing startup execution if autostart mode is set to periodic + +version 1.0.2 (10.01.2015) + * Fixed support for Database file got lost in version 1.0.0 + +version 1.0.1 (13.12.2014) + * Fixed unwanted waiting time in autostart + +version 1.0.0 (01.09.2014) + * Added mySQL Database support for the WatchedList Database + +version 0.9.8 (31.08.2014) + * Fix for Unicode Path problems + * Fix for SQLite Error handling + +version 0.9.7 (14.06.2014) + * Added custom sleep function to handle requested shutdown in Gotham + +version 0.9.6 (23.09.2013) + * Fixed tvshow id with imdb-scraper + +version 0.9.5 (18.09.2013) + * Fixed bug in watching user actions + +version 0.9.4 (09.09.2013) + * Fixed bug in watching user actions + +version 0.9.3 (04.09.2013) + * Fixed minor bugs + +version 0.9.2 (01.08.2013) + * Fixed minor bugs + +version 0.9.1 (24.06.2013) + * Fixed: Network share problems in Linux + +version 0.9.0 (09.06.2013) + * Added: Check watched-states permanently and enable to set media as unwatched + +version 0.8.1 (22.05.2013) + * Fixed: Duplicate movies and tv episodes get marked as watched + +version 0.8.0 (16.05.2013) + * Fixed: lastplayed-information is now also stored in the database (although it is sometimes missing in XBMC) + * Added: Exceptions are catched with buggalo and bug reports are sent + +version 0.7.0 (11.05.2013) + * Initial release diff --git a/service.watchedlist/default.py b/service.watchedlist/default.py new file mode 100644 index 0000000000..b7c768b541 --- /dev/null +++ b/service.watchedlist/default.py @@ -0,0 +1,31 @@ +""" +This file is entry point for automatic start via Kodi +""" + +import sys + +import xbmc + +import lib.watchedlist.utils as utils +from lib.watchedlist.watchedlist import WatchedList + +__remotedebug__ = False +# Append pydev remote debugger +if __remotedebug__: + utils.log("Initialize remote debugging.") + # Make pydev debugger works for auto reload. + try: + import pydevd + pydevd.settrace('localhost', port=60678, stdoutToServer=True, stderrToServer=True) + except ImportError: + sys.stderr.write("Error: " + + "You must add org.python.pydev.debug.pysrc to your PYTHONPATH.") + utils.showNotification('WatchedList Error', 'remote debug could not be imported.', xbmc.LOGERROR) + sys.exit(1) + except BaseException: + utils.showNotification('WatchedList Error', 'remote debug in pydev is activated, but remote server not responding.', xbmc.LOGERROR) + sys.exit(1) + +# Run the program +utils.log("WatchedList Database Service starting...") +WatchedList().runProgram() diff --git a/service.watchedlist/fanart.jpg b/service.watchedlist/fanart.jpg new file mode 100644 index 0000000000..55fbe53801 Binary files /dev/null and b/service.watchedlist/fanart.jpg differ diff --git a/service.watchedlist/icon.png b/service.watchedlist/icon.png new file mode 100644 index 0000000000..56846ad343 Binary files /dev/null and b/service.watchedlist/icon.png differ diff --git a/service.watchedlist/lib/watchedlist/api.py b/service.watchedlist/lib/watchedlist/api.py new file mode 100644 index 0000000000..4685edef63 --- /dev/null +++ b/service.watchedlist/lib/watchedlist/api.py @@ -0,0 +1,110 @@ +""" +This file contains API functions for the usage of WatchedList with other Kodi addons +""" + +import time + +import xbmc + +from lib.watchedlist.watchedlist import WatchedList +import lib.watchedlist.utils as utils + + +def change_watched_movie(imdb_id, playCount=1, name=''): + """ + Change the watched state of one movie in the WL database + + Args: + imdb_id: ID of the movie in the imdb. Format: Integer, numbers after 'tt0012345' + playCount: Unsigned Integer + name: Title of the movie (optional) + + Returns: + Error Code (0=No error) + """ + + if not name: + name = 'tt%d' % imdb_id + if playCount == 0: + lastPlayed = 0 + else: + lastPlayed = int(time.time()) + row_xbmc = [imdb_id, 0, 0, lastPlayed, playCount, name, 0] # 0imdbnumber, 1empty, 2empty, 3lastPlayed, 4playCount, 5title, 6empty, 7movieid + saveanyway = True + commit = True + lastChange = lastPlayed + with WatchedList(True) as WL: + if WL.get_watched_wl(1): # Read the WL database + utils.showNotification(utils.getString(32102), utils.getString(32602), xbmc.LOGERROR) + return 1 + WL.wl_update_media('movie', row_xbmc, saveanyway, commit, lastChange) + return 0 + + +def change_watched_episode(tvdb_id, season, episode, playCount=1, name=''): + """ + Change the watched state of one episode in the WL database + + Args: + tvdb_id: ID of the tv show in tvdb. Format: Integer + season: Number of the season (Integer) within the show + episode: Number of the episode within the season (Integer) + playCount: Unsigned Integer + name: Name of the Episode (optional) + + Returns: + Error Code (0=No error) + """ + + if not name: + name = 'tvdb%d S%02dE%02d' % (tvdb_id, season, episode) + if playCount == 0: + lastPlayed = 0 + else: + lastPlayed = int(time.time()) + row_xbmc = [tvdb_id, season, episode, lastPlayed, playCount, name, 0] # 0imdbnumber, 1empty, 2empty, 3lastPlayed, 4playCount, 5title, 6empty, 7movieid + saveanyway = True + commit = True + lastChange = lastPlayed + with WatchedList(True) as WL: + if WL.get_watched_wl(1): # Read the WL database + utils.showNotification(utils.getString(32102), utils.getString(32602), xbmc.LOGERROR) + return 1 + WL.wl_update_media('episode', row_xbmc, saveanyway, commit, lastChange) + return 0 + + +def change_watched_episodes(tvdb_id, seasons, episodes, playCount, names): + """ + Change the watched state of multiple episodes of one tv show in the WL database + + Args: + tvdb_id: ID of the tv show in tvdb. Format: Integer + seasons: Number of the seasons for the affected episodes (list of Integers) + episodes: Number of the episodes within the seasons (list of Integers, same length as seasons list). + playCount: Unsigned Integer + names: Names of the Episodes (list of strings, same length as lists above) + + Returns: + Error Code (0=No error) + """ + + if playCount == 0: + lastPlayed = 0 + else: + lastPlayed = int(time.time()) + with WatchedList(True) as WL: + if WL.get_watched_wl(1): # Read the WL database + utils.showNotification(utils.getString(32102), utils.getString(32602), xbmc.LOGERROR) + return 1 + for i in range(len(seasons)): + row_xbmc_i = [tvdb_id, seasons[i], episodes[i], lastPlayed, playCount, names[i], 0] # 0imdbnumber, 1empty, 2empty, 3lastPlayed, 4playCount, 5title, 6empty, 7movieid + saveanyway = True + if i == len(seasons) - 1: + commit = True # Only commit the last row to reduce file access to the database + else: + commit = False + lastChange = lastPlayed + + WL.wl_update_media('episode', row_xbmc_i, saveanyway, commit, lastChange) + return 0 diff --git a/service.watchedlist/lib/watchedlist/utils.py b/service.watchedlist/lib/watchedlist/utils.py new file mode 100644 index 0000000000..c49f889269 --- /dev/null +++ b/service.watchedlist/lib/watchedlist/utils.py @@ -0,0 +1,209 @@ +""" +This file contains additional utility functions +""" +import os +import time +import re +import random +import json + +import xbmc +import xbmcgui +import xbmcvfs +import xbmcaddon +import buggalo + +_addon_id = u'service.watchedlist' +_Addon = xbmcaddon.Addon(_addon_id) + + +def data_dir(): + """"get user data directory of this addon. + according to http://wiki.xbmc.org/index.php?title=Add-on_Rules#Requirements_for_scripts_and_plugins + """ + _datapath = xbmcvfs.translatePath(_Addon.getAddonInfo('profile')) + if not xbmcvfs.exists(_datapath): + xbmcvfs.mkdir(_datapath) + return _datapath + + +def addon_dir(): + """"get source directory of this addon. + according to http://wiki.xbmc.org/index.php?title=Add-on_Rules#Requirements_for_scripts_and_plugins + """ + return _Addon.getAddonInfo('path') + + +def log(message, loglevel=xbmc.LOGINFO): + """"save message to xbmc.log. + + Args: + message: has to be unicode, http://wiki.xbmc.org/index.php?title=Add-on_unicode_paths#Logging + loglevel: xbmc.LOGDEBUG, xbmc.LOGINFO, xbmc.LOGWARNING, xbmc.LOGERROR, xbmc.LOGFATAL + """ + xbmc.log(_addon_id + u": " + message, level=loglevel) + + +def showNotification(title, message, loglevel, showtime=4000): + """Show Notification + + Args: + title: has to be unicode + message: has to be unicode + loglevel: Log-level of the message (equivalent to xbmc.LOGDEBUG ... xbmc.LOGFATAL) + showtime: Time that the message is beeing displayed + """ + # Check log level + if getSetting('verbosity') == '1' and loglevel < xbmc.LOGINFO: + return # setting "only infos" + elif getSetting('verbosity') == '2' and loglevel < xbmc.LOGWARNING: + return # setting "only warnings" + elif getSetting('verbosity') == '3' and loglevel < xbmc.LOGERROR: + return # setting "only errors" + elif getSetting('verbosity') == '4': + return # setting "None" + _addoniconpath = _Addon.getAddonInfo('icon') + log(u'Notification. %s: %s' % (title, message)) + if not xbmc.Player().isPlaying(): # do not show the notification, if a video is being played. + xbmcgui.Dialog().notification(title, message, _addoniconpath, showtime) + + +def setSetting(name, value): + _Addon.setSetting(name, value) + + +def getSetting(name): + # The returned value from getSetting is not unicode, only string + # This function returns unicode + return _Addon.getSetting(name) + + +def getString(string_id): + # return a localized string from resources/language/*.po + # The returned string is unicode + return _Addon.getLocalizedString(string_id) + +def footprint(): + """Print settings to log file""" + log(u'data_dir() = %s' % data_dir(), xbmc.LOGDEBUG) + log(u'addon_dir() = %s' % addon_dir(), xbmc.LOGDEBUG) + log(u'verbosity = %s' % getSetting('verbosity'), xbmc.LOGDEBUG) + log(u'w_movies = %s' % getSetting('w_movies'), xbmc.LOGDEBUG) + log(u'w_episodes = %s' % getSetting('w_episodes'), xbmc.LOGDEBUG) + log(u'autostart = %s' % getSetting('autostart'), xbmc.LOGDEBUG) + log(u'delay = %s' % getSetting('delay'), xbmc.LOGDEBUG) + log(u'starttype = %s' % getSetting('starttype'), xbmc.LOGDEBUG) + log(u'interval = %s' % getSetting('interval'), xbmc.LOGDEBUG) + log(u'watch_user = %s' % getSetting('watch_user'), xbmc.LOGDEBUG) + log(u'progressdialog = %s' % getSetting('progressdialog'), xbmc.LOGDEBUG) + log(u'db_format = %s' % getSetting('db_format'), xbmc.LOGDEBUG) + log(u'extdb = %s' % getSetting('extdb'), xbmc.LOGDEBUG) + log(u'dbpath = %s' % getSetting('dbpath'), xbmc.LOGDEBUG) + log(u'dbfilename = %s' % getSetting('dbfilename'), xbmc.LOGDEBUG) + log(u'dbbackup = %s' % getSetting('dbbackup'), xbmc.LOGDEBUG) + log(u'dropbox_enabled = %s' % getSetting('dropbox_enabled'), xbmc.LOGDEBUG) + log(u'dropbox_apikey = %s' % getSetting('dropbox_apikey'), xbmc.LOGDEBUG) + log(u'mysql_server = %s' % getSetting('mysql_server'), xbmc.LOGDEBUG) + log(u'mysql_port = %s' % getSetting('mysql_port'), xbmc.LOGDEBUG) + log(u'mysql_user = *******', xbmc.LOGDEBUG) + log(u'mysql_pass = *******', xbmc.LOGDEBUG) + + +def sqlDateTimeToTimeStamp(sqlDateTime): + """Convert SQLite DateTime to Unix Timestamp + + Args: + sqlDateTime: E.g. "2013-05-10 21:23:24" + Returns: + timestamp: E.g. 1368213804 + """ + # sqlDateTime is a string (only from SQLite db. Mysql returns object) + if sqlDateTime == '': + return 0 # NULL timestamp + else: + # the usage of strptime produces the error "Failed to import _strptime because the import lock is held by another thread." + # to solve this, in case of error try again after random time + try: + for i in range(5): + try: + return int(time.mktime(time.strptime(sqlDateTime, "%Y-%m-%d %H:%M:%S"))) + except BaseException: + xbmc.wait(random.randint(200, 500)) + except BaseException: + return 0 # error, but timestamp=0 works in the addon + + +def TimeStamptosqlDateTime(TimeStamp): + """Convert Unix Timestamp to SQLite DateTime + + Args: + timestamp: E.g. 1368213804 + + Returns: + sqlDateTime: E.g. "2013-05-10 21:23:24" + """ + if TimeStamp == 0: + return "" + return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(TimeStamp)) + + +def executeJSON(request): + """Execute JSON-RPC Command + + Args: + request: Dictionary with JSON-RPC Commands + """ + rpccmd = json.dumps(request) # create string from dict + json_query = xbmc.executeJSONRPC(rpccmd) + json_response = json.loads(json_query) + # in case of exception this will be sent + buggalo.addExtraData('len(json_query)', len(json_query)) + buggalo.addExtraData('len(json_response)', len(json_response)) + return json_response + + +def buggalo_extradata_settings(): + """"add extradata to buggalo""" + + buggalo.addExtraData('data_dir', data_dir()) + buggalo.addExtraData('addon_dir', addon_dir()) + buggalo.addExtraData('setting_verbosity', getSetting("verbosity")) + buggalo.addExtraData('setting_w_movies', getSetting("w_movies")) + buggalo.addExtraData('setting_w_episodes', getSetting("w_episodes")) + buggalo.addExtraData('setting_autostart', getSetting("autostart")) + buggalo.addExtraData('setting_delay', getSetting("delay")) + buggalo.addExtraData('setting_starttype', getSetting("starttype")) + buggalo.addExtraData('setting_interval', getSetting("interval")) + buggalo.addExtraData('setting_progressdialog', getSetting("progressdialog")) + buggalo.addExtraData('setting_watch_user', getSetting("watch_user")) + buggalo.addExtraData('setting_extdb', getSetting("extdb")) + buggalo.addExtraData('setting_dbpath', getSetting("dbpath")) + buggalo.addExtraData('setting_dbfilename', getSetting("dbfilename")) + buggalo.addExtraData('setting_dbbackup', getSetting("dbbackup")) + buggalo.addExtraData('setting_db_format', getSetting("db_format")) + buggalo.addExtraData('setting_mysql_server', getSetting("mysql_server")) + buggalo.addExtraData('setting_mysql_port', getSetting("mysql_port")) + buggalo.addExtraData('setting_mysql_db', getSetting("mysql_db")) + + +def fileaccessmode(path): + """"determine file access mode for the given path + in case of network shares no direct access is possible + on windows, smb paths can be accessed directly in certain conditions, + which are ignored for the sake of simplicity + + Args: + path: Path to File + + Returns: + copy_mode: Mode of file access: 'copy' or 'normal' + """ + + res_nw = re.compile(r'(.*?)://(.*?)').findall(path) + if res_nw: + # Path with smb://, nfs:// or ftp:// is correct, but can not be accessed with normal python file access. + # Copy the file with the virtual file system + return 'copy' + else: + # "normal" path on local filesystem + return 'normal' diff --git a/service.watchedlist/lib/watchedlist/watchedlist.py b/service.watchedlist/lib/watchedlist/watchedlist.py new file mode 100644 index 0000000000..a165ba97ad --- /dev/null +++ b/service.watchedlist/lib/watchedlist/watchedlist.py @@ -0,0 +1,1846 @@ +""" +This file contains the class of the addon + +Settings for this addon: +w_movies + 'true', 'false': save watched state of movies +w_episodes + 'true', 'false': save watched state of movies +autostart +delay + delay after startup in minutes: '0', '5', '10', ... +starttype + '0' = No autostart + '1' = One Execution after Kodi start + '2' = Periodic start of the addon +interval +watch_user +progressdialog +verbosity + '0' = All messages (debug) + '1' = Only info / notification + '2' = Only warnings + '3' = Only errors + '4' = No Messages +db_format + '0' = SQLite File + '1' = MYSQL Server +drobox_enabled +extdb + 'true', 'false': Use external database file +dbpath + String: Specify path to external database file +dbfilename +dbbackupcount +mysql_server +mysql_port +mysql_db +mysql_user +mysql_pass +""" + +import sys +import os +import re +import time +import sqlite3 +import base64 + +import xbmc +import xbmcgui +import xbmcvfs +import mysql.connector +import buggalo + +import lib.watchedlist.utils as utils + +try: + import dropbox + from dropbox.exceptions import ApiError as DropboxApiError + DROPBOX_APP_KEY = base64.b64decode("YmhkMnY4aGdzbXF3Y2d0").decode('ascii') + DROPBOX_APP_SECRET = base64.b64decode("dDJjZXBvZXZqcXl1Ym5k").decode('ascii') + DROPBOX_ENABLED = True +except BaseException: + DROPBOX_ENABLED = False + if utils.getSetting("dropbox_enabled") == 'true': + utils.showNotification(utils.getString(32708), utils.getString(32720), xbmc.LOGWARNING) + +if utils.getSetting('dbbackupcount') != '0': + import zipfile + import datetime + +buggalo.EMAIL_CONFIG = {"recipient": base64.b64decode("bXNhaGFkbDYwQGdtYWlsLmNvbQ==").decode('ascii'), + "sender": base64.b64decode("QnVnZ2FsbyA8a29kaXdhdGNoZWRsaXN0QGdtYWlsLmNvbT4=").decode('ascii'), + "server": base64.b64decode("c210cC5nb29nbGVtYWlsLmNvbQ==").decode('ascii'), + "method": "ssl", + "user": base64.b64decode("a29kaXdhdGNoZWRsaXN0QGdtYWlsLmNvbQ==").decode('ascii'), + "pass": base64.b64decode("bWNneHd1and6c3ducW1iaA==").decode('ascii')} + +QUERY_MV_INSERT_SQLITE = 'INSERT OR IGNORE INTO movie_watched (idMovieImdb,playCount,lastChange,lastPlayed,title) VALUES (?, ?, ?, ?, ?)' +QUERY_MV_INSERT_MYSQL = 'INSERT IGNORE INTO movie_watched (idMovieImdb,playCount,lastChange,lastPlayed,title) VALUES (%s, %s, FROM_UNIXTIME(%s), FROM_UNIXTIME(%s), %s)' +QUERY_EP_INSERT_SQLITE = 'INSERT OR IGNORE INTO episode_watched (idShow,season,episode,playCount,lastChange,lastPlayed) VALUES (?, ?, ?, ?, ?, ?)' +QUERY_EP_INSERT_MYSQL = 'INSERT IGNORE INTO episode_watched (idShow,season,episode,playCount,lastChange,lastPlayed) VALUES (%s, %s, %s, %s, FROM_UNIXTIME(%s), FROM_UNIXTIME(%s))' + +QUERY_MV_UPDATE_SQLITE = 'UPDATE movie_watched SET playCount = ?, lastplayed = ?, lastChange = ? WHERE idMovieImdb LIKE ?' +QUERY_MV_UPDATE_MYSQL = 'UPDATE movie_watched SET playCount = %s, lastplayed = FROM_UNIXTIME(%s), lastChange = FROM_UNIXTIME(%s) WHERE idMovieImdb LIKE %s' +QUERY_EP_UPDATE_SQLITE = 'UPDATE episode_watched SET playCount = ?, lastPlayed = ?, lastChange = ? WHERE idShow LIKE ? AND season LIKE ? AND episode LIKE ?' +QUERY_EP_UPDATE_MYSQL = 'UPDATE episode_watched SET playCount = %s, lastPlayed = FROM_UNIXTIME(%s), lastChange = FROM_UNIXTIME(%s) WHERE idShow LIKE %s AND season LIKE %s AND episode LIKE %s' + +# Queries to create tables for movies ("mv"), episodes ("ep") and series ("ss") for sqlite and mysql +QUERY_CREATE_MV_SQLITE = "CREATE TABLE IF NOT EXISTS movie_watched (idMovieImdb INTEGER PRIMARY KEY,playCount INTEGER,lastChange INTEGER,lastPlayed INTEGER,title TEXT)" +QUERY_CREATE_EP_SQLITE = "CREATE TABLE IF NOT EXISTS episode_watched (idShow INTEGER, season INTEGER, episode INTEGER, playCount INTEGER,lastChange INTEGER,lastPlayed INTEGER, PRIMARY KEY (idShow, season, episode))" +QUERY_CREATE_SS_SQLITE = "CREATE TABLE IF NOT EXISTS tvshows (idShow INTEGER, title TEXT, PRIMARY KEY (idShow))" + +QUERY_CREATE_MV_MYSQL = ("CREATE TABLE IF NOT EXISTS `movie_watched` (" + "`idMovieImdb` int unsigned NOT NULL," + "`playCount` tinyint unsigned DEFAULT NULL," + "`lastChange` timestamp NULL DEFAULT NULL," + "`lastPlayed` timestamp NULL DEFAULT NULL," + "`title` text," + "PRIMARY KEY (`idMovieImdb`)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8;") +QUERY_CREATE_EP_MYSQL = ("CREATE TABLE IF NOT EXISTS `episode_watched` (" + "`idShow` int unsigned NOT NULL DEFAULT '0'," + "`season` smallint unsigned NOT NULL DEFAULT '0'," + "`episode` smallint unsigned NOT NULL DEFAULT '0'," + "`playCount` tinyint unsigned DEFAULT NULL," + "`lastChange` timestamp NULL DEFAULT NULL," + "`lastPlayed` timestamp NULL DEFAULT NULL," + "PRIMARY KEY (`idShow`,`season`,`episode`)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8;") +QUERY_CREATE_SS_MYSQL = ("CREATE TABLE IF NOT EXISTS `tvshows` (" + "`idShow` int unsigned NOT NULL," + "`title` text," + "PRIMARY KEY (`idShow`)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8;") + +# Queries for clearing data from the tables +QUERY_CLEAR_MV_SQLITE = "DELETE FROM movie_watched;" +QUERY_CLEAR_EP_SQLITE = "DELETE FROM episode_watched;" + +# Queries for selecting all table entries +QUERY_SELECT_MV_SQLITE = "SELECT idMovieImdb, lastPlayed, playCount, title, lastChange FROM movie_watched ORDER BY title" +QUERY_SELECT_MV_MYSQL = "SELECT `idMovieImdb`, UNIX_TIMESTAMP(`lastPlayed`), `playCount`, `title`, UNIX_TIMESTAMP(`lastChange`) FROM `movie_watched` ORDER BY `title`" +QUERY_SELECT_EP_SQLITE = "SELECT idShow, season, episode, lastPlayed, playCount, lastChange FROM episode_watched ORDER BY idShow, season, episode" +QUERY_SELECT_EP_MYSQL = "SELECT `idShow`, `season`, `episode`, UNIX_TIMESTAMP(`lastPlayed`), `playCount`, UNIX_TIMESTAMP(`lastChange`) FROM `episode_watched` ORDER BY `idShow`, `season`, `episode`" + +# Queries for inserting tv series +QUERY_INSERT_SS_SQLITE = "INSERT OR IGNORE INTO tvshows (idShow,title) VALUES (?, ?)" +QUERY_INSERT_SS_MYSQL = "INSERT IGNORE INTO tvshows (idShow,title) VALUES (%s, %s)" + + +class WatchedList: + """ + Main class of the add-on + """ + + def __init__(self, externalcall=False): + """ + Initialize Class, default values for all class variables + + Args: + externalcall: Flag if the class was created for use with another Addon (via the API). + In this case some features will be deactivated for speed purpose + """ + self.watchedmovielist_wl = list([]) # 0imdbnumber, 1empty, 2empty, 3lastPlayed, 4playCount, 5title, 6lastChange + self.watchedepisodelist_wl = list([]) # 0tvdbnumber, 1season, 2episode, 3lastplayed, 4playcount, 5empty, 6lastChange + + self.watchedmovielist_xbmc = list([]) # 0imdbnumber, 1empty, 2empty, 3lastPlayed, 4playCount, 5title, 6empty, 7movieid + self.watchedepisodelist_xbmc = list([]) # 0tvdbnumber, 1season, 2episode, 3lastplayed, 4playcount, 5name, 6empty, 7episodeid + + self.tvshows = {} # dict: key=xbmcid, value=[tvdbnumber, showname] + self.tvshownames = {} # dict: key=tvdbnumber, value=showname + + self.sqlcon_wl = 0 + self.sqlcursor_wl = 0 + self.sqlcon_db = 0 + self.sqlcursor_db = 0 + + self.db_method = 'file' # either 'file' or 'mysql' + + # flag to remember copying the databasefile if requested + self.dbbackupdone = False + + self.watch_user_changes_count = 0 + + # normal access of files or access over the Kodi virtual file system (on unix) + self.dbfileaccess = 'normal' + + self.dbpath = '' + self.dbdirectory = '' + self.dropbox_path = None + self.downloaded_dropbox_timestamp = 0 + self.dbdirectory_copy = '' + self.dbpath_copy = '' + + # monitor for shutdown detection + self.monitor = xbmc.Monitor() + + if externalcall: + # No Dropbox for external API calls + self.downloaded_dropbox_timestamp = float('inf') + # No database backup + self.dbbackupdone = True + + def __del__(self): + ''' Cleanup db when object destroyed ''' + self.close_db(3) # changes have to be committed before + + def __enter__(self): # for using the class in a with-statement + return self + + def __exit__(self, exc_type, exc_value, traceback): # for using the class in a with-statement + self.close_db(3) # changes have to be committed before + + def runProgram(self): + """ + entry point for automatic start. + Main function to call other functions + infinite loop for periodic database update + + Returns: + return codes: + 0 success + 2 undefined + 3 error/exit + 4 planned exit (no error) + """ + try: + # workaround to disable autostart, if requested + if utils.getSetting("autostart") == 'false': + return 0 + + utils.buggalo_extradata_settings() + utils.footprint() + + # wait the delay time after startup + delaytime = int(utils.getSetting("delay")) * 60 # in seconds + utils.log(u'Delay time before execution: %d seconds' % delaytime, xbmc.LOGDEBUG) + utils.showNotification(utils.getString(32101), utils.getString(32004) % int(utils.getSetting("delay")), xbmc.LOGINFO) + if self.monitor.waitForAbort(1 + delaytime): # wait at least one second (zero waiting time waits infinitely) + return 0 + + # load all databases + if self.sqlcursor_wl == 0 or self.sqlcon_wl == 0: + if self.load_db(): + utils.showNotification(utils.getString(32102), utils.getString(32601), xbmc.LOGERROR) + return 3 + if not self.tvshownames: + if self.sync_tvshows(): + return 2 + if not self.watchedmovielist_wl: + if self.get_watched_wl(1): + return 2 + if not self.watchedmovielist_xbmc: + if self.get_watched_xbmc(1): + return 2 + executioncount = 0 + idletime = 0 + + if utils.getSetting("watch_user") == 'true': + utils.showNotification(utils.getString(32101), utils.getString(32005), xbmc.LOGINFO) + + # handle the periodic execution + while int(utils.getSetting("starttype")) > 0 or utils.getSetting("watch_user") == 'true': + starttime = time.time() + # determine sleeptime before next full watched-database update + if utils.getSetting("starttype") == '1' and executioncount == 0: # one execution after startup + sleeptime = 0 + elif utils.getSetting("starttype") == '2': # periodic execution + if executioncount == 0: # with periodic execution, one update after startup and then periodic + sleeptime = 0 + else: + sleeptime = int(utils.getSetting("interval")) * 3600 # wait interval until next startup in [seconds] + # wait and then update again + utils.log(u'wait %d seconds until next update' % sleeptime) + utils.showNotification(utils.getString(32101), utils.getString(32003) % (sleeptime / 3600), xbmc.LOGINFO) + else: # no autostart, only watch user + sleeptime = 3600 # arbitrary time for infinite loop + + # sleep the requested time and watch user changes + while True: + if self.monitor.abortRequested(): + return 4 + # check if user changes arrived + if utils.getSetting("watch_user") == 'true': + idletime_old = idletime + idletime = xbmc.getGlobalIdleTime() # Kodi idletime in seconds + # check if user could have made changes and process these changes to the wl database + self.watch_user_changes(idletime_old, idletime) + # check if time for update arrived + if time.time() > starttime + sleeptime: + break + if self.monitor.waitForAbort(1): + return 4 # wait 1 second until next check if Kodi terminates and user made changes + # perform full update + if utils.getSetting("starttype") == '1' and executioncount == 0 or utils.getSetting("starttype") == '2': + self.runUpdate(False) + executioncount += 1 + + # check for exiting program + if int(utils.getSetting("starttype")) < 2 and utils.getSetting("watch_user") == 'false': + return 0 # the program may exit. No purpose for background process + + return 0 + except SystemExit: + return 4 + except BaseException: + buggalo.onExceptionRaised() + + def runUpdate(self, manualstart): + """ + entry point for manual start. + this function is called for periodic update for automatic start + perform the update step by step + + Args: + manualstart: True if called manually + + Returns: + return code: + 0 success + 2 SystemExit + 3 Error opening database + 4 Error getting watched state from addon database + 5 Error getting watched state from Kodi database + 6 Error writing WL Database + 7 Error writing Kodi database + 8 Error merging dropbox database into local watched list + 9 Error merging local database into dropbox + 10 Error performing database backup + """ + + try: + utils.buggalo_extradata_settings() + # check if player is running before doing the update. Only do this check for automatic start + while xbmc.Player().isPlaying() and not manualstart: + if self.monitor.waitForAbort(60): + return 1 # wait one minute until next check for active playback + if not xbmc.Player().isPlaying(): + if self.monitor.waitForAbort(180): + return 1 # wait 3 minutes so the dialogue does not pop up directly after the playback ends + + # load the addon-database + if self.sqlcursor_wl == 0 or self.sqlcon_wl == 0: + if self.load_db(True): # True: Manual start + utils.showNotification(utils.getString(32102), utils.getString(32601), xbmc.LOGERROR) + return 3 + + if self.sync_tvshows(): + utils.showNotification(utils.getString(32102), utils.getString(32604), xbmc.LOGERROR) + return 5 + + # get the watched state from the addon + if self.get_watched_wl(0): + utils.showNotification(utils.getString(32102), utils.getString(32602), xbmc.LOGERROR) + return 4 + + # get watched state from xbmc + if self.get_watched_xbmc(0): + utils.showNotification(utils.getString(32102), utils.getString(32603), xbmc.LOGERROR) + return 5 + + if self.sync_tvshows(): + utils.showNotification(utils.getString(32102), utils.getString(32604), xbmc.LOGERROR) + return 5 + + # attempt to merge the database from dropbox + if DROPBOX_ENABLED and utils.getSetting("dropbox_enabled") == 'true' and self.merge_dropbox_local(): + utils.showNotification(utils.getString(32102), utils.getString(32607), xbmc.LOGERROR) + # do not abort execution of the whole addon if dropbox fails (e.g. due to network issues) + # return 8 + + # import from Kodi into addon database + res = self.write_wl_wdata() + if res == 2: # user exit + return 0 + elif res == 1: # error + utils.showNotification(utils.getString(32102), utils.getString(32604), xbmc.LOGERROR) + return 6 + + # export from addon database into Kodi database + res = self.write_xbmc_wdata((utils.getSetting("progressdialog") == 'true'), 2) + if res == 2: # user exit + return 0 + elif res == 1: # error + utils.showNotification(utils.getString(32102), utils.getString(32605), xbmc.LOGERROR) + return 7 + + utils.showNotification(utils.getString(32101), utils.getString(32107), xbmc.LOGINFO) + utils.log(u'runUpdate exited with success', xbmc.LOGDEBUG) + + # sync with dropbox + if DROPBOX_ENABLED and utils.getSetting("dropbox_enabled") == 'true': + if self.merge_local_dropbox() == 0: + self.close_db(2) # save the database to file. + self.pushToDropbox() + else: + return 9 + + # close the watchedlist database. Is only closed locally in case of error + self.close_db(1) + + # delete old backup files of the database + # do this at the end for not destroying valuable backup in case something went wrong before + if self.database_backup_delete(): + return 10 + return 0 + except SystemExit: + return 2 + except BaseException: + buggalo.onExceptionRaised() + + def load_db(self, manualstart=False): + """Load WL database + + Args: + manualstart: True if called manually; only retry opening db once + + Returns: + return code: + 0 successfully opened database + 1 error + 2 shutdown (serious error in subfunction) + """ + + try: + if int(utils.getSetting("db_format")) != 1: + # SQlite3 database in a file + # load the db path + if utils.getSetting("extdb") == 'false': + # use the default file + self.dbdirectory = xbmcvfs.translatePath(utils.data_dir()) + buggalo.addExtraData('dbdirectory', self.dbdirectory) + self.dbpath = os.path.join(self.dbdirectory, "watchedlist.db") + else: + wait_minutes = 1 # retry waittime if db path does not exist/ is offline + + while not self.monitor.abortRequested(): + # use a user specified file, for example to synchronize multiple clients + self.dbdirectory = xbmcvfs.translatePath(utils.getSetting("dbpath")) + self.dbfileaccess = utils.fileaccessmode(self.dbdirectory) + self.dbpath = os.path.join(self.dbdirectory, utils.getSetting("dbfilename")) + + if not xbmcvfs.exists(self.dbdirectory): # do not use os.path.exists to access smb:// paths + if manualstart: + utils.log(u'db path does not exist: %s' % self.dbdirectory, xbmc.LOGWARNING) + return 1 # raise error on manual start if directory not accessible (we do not want to wait in that case) + else: + utils.log(u'db path does not exist, wait %d minutes: %s' % (wait_minutes, self.dbdirectory), xbmc.LOGWARNING) + + utils.showNotification(utils.getString(32102), utils.getString(32002) % self.dbdirectory, xbmc.LOGWARNING) + # Wait "wait_minutes" minutes until next check for file path (necessary on network shares, that are offline) + wait_minutes += wait_minutes # increase waittime until next check + if self.monitor.waitForAbort(wait_minutes * 60): + return 2 + else: + break # directory exists, continue below + + # on unix, smb-shares can not be accessed with sqlite3 --> copy the db with Kodi file system operations and work in mirror directory + buggalo.addExtraData('dbfileaccess', self.dbfileaccess) + buggalo.addExtraData('dbdirectory', self.dbdirectory) + buggalo.addExtraData('dbpath', self.dbpath) + if self.dbfileaccess == 'copy': + self.dbdirectory_copy = self.dbdirectory + self.dbpath_copy = self.dbpath # path to db file as in the settings (but not accessable) + buggalo.addExtraData('dbdirectory_copy', self.dbdirectory_copy) + buggalo.addExtraData('dbpath_copy', self.dbpath_copy) + # work in copy directory in the Kodi profile folder + self.dbdirectory = os.path.join(xbmcvfs.translatePath(utils.data_dir()), 'dbcopy' + os.sep) + if not xbmcvfs.exists(self.dbdirectory): # directory has to end with '/' (os.sep) + xbmcvfs.mkdir(self.dbdirectory) + utils.log(u'created directory %s' % str(self.dbdirectory)) + self.dbpath = os.path.join(self.dbdirectory, "watchedlist.db") + if xbmcvfs.exists(self.dbpath_copy): + success = xbmcvfs.copy(self.dbpath_copy, self.dbpath) # copy the external db file to local mirror directory + utils.log(u'copied db file from share: %s -> %s. Success: %d' % (self.dbpath_copy, self.dbpath, success), xbmc.LOGDEBUG) + + buggalo.addExtraData('dbdirectory', self.dbdirectory) + buggalo.addExtraData('dbpath', self.dbpath) + + # connect to the local wl database. create database if it does not exist + self.sqlcon_wl = sqlite3.connect(self.dbpath) + self.sqlcursor_wl = self.sqlcon_wl.cursor() + else: + # MySQL Database on a server + self.sqlcon_wl = mysql.connector.connect(user=utils.getSetting("mysql_user"), password=utils.getSetting("mysql_pass"), database=utils.getSetting("mysql_db"), host=utils.getSetting("mysql_server"), port=utils.getSetting("mysql_port")) + self.sqlcursor_wl = self.sqlcon_wl.cursor() + + # create tables if they don't exist + if int(utils.getSetting("db_format")) != 1: # sqlite file + self.sqlcursor_wl.execute(QUERY_CREATE_MV_SQLITE) + self.sqlcursor_wl.execute(QUERY_CREATE_EP_SQLITE) + self.sqlcursor_wl.execute(QUERY_CREATE_SS_SQLITE) + else: # mysql network database + self.sqlcursor_wl.execute(QUERY_CREATE_MV_MYSQL) + self.sqlcursor_wl.execute(QUERY_CREATE_EP_MYSQL) + self.sqlcursor_wl.execute(QUERY_CREATE_SS_MYSQL) + + # check for dropbox + if DROPBOX_ENABLED and utils.getSetting("dropbox_enabled") == 'true': + # Download Dropbox database only once a day to reduce traffic. + if time.time() > self.downloaded_dropbox_timestamp + 3600.0 * 24.0: + if self.pullFromDropbox(): + return 1 + self.downloaded_dropbox_timestamp = time.time() + # connect to the dropbox wl database. + if self.dropbox_path is not None: + self.sqlcon_db = sqlite3.connect(self.dropbox_path) + self.sqlcursor_db = self.sqlcon_db.cursor() + # create tables in dropbox file, if they don't exist + self.sqlcursor_db.execute(QUERY_CREATE_MV_SQLITE) + self.sqlcursor_db.execute(QUERY_CREATE_EP_SQLITE) + self.sqlcursor_db.execute(QUERY_CREATE_SS_SQLITE) + + buggalo.addExtraData('db_connstatus', 'connected') + except sqlite3.Error as err: + try: + errstring = err.args[0] # TODO: Find out, why this does not work some times + except BaseException: + errstring = '' + utils.log(u"Database error while opening %s. '%s'" % (self.dbpath, errstring), xbmc.LOGERROR) + utils.showNotification(utils.getString(32109), errstring, xbmc.LOGERROR) + self.close_db(3) + buggalo.addExtraData('db_connstatus', 'sqlite3 error, closed') + return 1 + except mysql.connector.Error as err: + # Catch common mysql errors and show them to guide the user + utils.log(u"Database error while opening mySQL DB %s [%s:%s@%s]. %s" % (utils.getSetting("mysql_db"), utils.getSetting("mysql_user"), utils.getSetting("mysql_pass"), utils.getSetting("mysql_db"), err.msg), xbmc.LOGERROR) + if err.errno == mysql.connector.errorcode.ER_DBACCESS_DENIED_ERROR: + utils.showNotification(utils.getString(32108), utils.getString(32210) % (utils.getSetting("mysql_user"), utils.getSetting("mysql_db")), xbmc.LOGERROR) + elif err.errno == mysql.connector.errorcode.ER_ACCESS_DENIED_ERROR: + utils.showNotification(utils.getString(32108), utils.getString(32208), xbmc.LOGERROR) + elif err.errno == mysql.connector.errorcode.ER_BAD_DB_ERROR: + utils.showNotification(utils.getString(32108), utils.getString(32209) % utils.getSetting("mysql_db"), xbmc.LOGERROR) + else: + utils.showNotification(utils.getString(32108), err.msg, xbmc.LOGERROR) + buggalo.addExtraData('db_connstatus', 'mysql error, closed') + self.close_db(3) + return 1 + except SystemExit: + return 1 + except BaseException: + utils.log(u"Error while opening %s: %s" % (self.dbpath, sys.exc_info()[2]), xbmc.LOGERROR) + self.close_db(3) + buggalo.addExtraData('dbpath', self.dbpath) + buggalo.addExtraData('db_connstatus', 'error, closed') + buggalo.onExceptionRaised() + return 1 + # only commit the changes if no error occured to ensure database persistence + self.sqlcon_wl.commit() + return 0 + + def close_db(self, flag): + """Close WL database + Argument: + flag + 1 for closing the WatchedList database + 2 for closing the DropBox database + 3 for closing both + + Returns: + return code: + 0 successfully closed database + 1 error + """ + # close watchedlist db (if it is open) + if self.sqlcon_wl and (flag == 1 or flag == 3): + if self.sqlcon_wl: + self.sqlcon_wl.close() + self.sqlcon_wl = 0 + # copy the db file back to the shared directory, if needed + if utils.getSetting("db_format") == '0' and self.dbfileaccess == 'copy': + if xbmcvfs.exists(self.dbpath): + success = xbmcvfs.copy(self.dbpath, self.dbpath_copy) + utils.log(u'copied db file to share: %s -> %s. Success: %d' % (self.dbpath, self.dbpath_copy, success), xbmc.LOGDEBUG) + if not success: + utils.showNotification(utils.getString(32102), utils.getString(32606) % self.dbpath, xbmc.LOGERROR) + return 1 + buggalo.addExtraData('db_connstatus', 'closed') + # close dropbox db + if flag == 2 or flag == 3: + if self.sqlcon_db: + self.sqlcon_db.close() + self.sqlcon_db = 0 + return 0 + + def get_watched_xbmc(self, silent): + """Get Watched States of Kodi Database + + Args: + silent: Do not show notifications if True + + Returns: + return code: + 0 success + 1 error + 4 planned exit (no error) + """ + try: + + ############################################ + # first tv shows with TheTVDB-ID, then tv episodes + if utils.getSetting("w_episodes") == 'true': + ############################################ + # get imdb tv-show id from Kodi database + utils.log(u'get_watched_xbmc: Get all TV shows from Kodi database', xbmc.LOGDEBUG) + json_response = utils.executeJSON({ + "jsonrpc": "2.0", + "method": "VideoLibrary.GetTVShows", + "params": { + "properties": ["title", "uniqueid"], + "sort": {"order": "ascending", "method": "title"} + }, + "id": 1}) + if 'result' in json_response and json_response['result'] is not None and 'tvshows' in json_response['result']: + for item in json_response['result']['tvshows']: + if self.monitor.abortRequested(): + self.close_db(3) + return 4 + tvshowId_xbmc = int(item['tvshowid']) + if not 'uniqueid' in item: + utils.log(u'get_watched_xbmc: tv show "%s" has no field uniqueid in database. tvshowid=%d. Try rescraping.' % (item['title'], tvshowId_xbmc), xbmc.LOGINFO) + continue + try: + tvshowId_tvdb = int(item['uniqueid']['tvdb']) + except BaseException: + utils.log(u'get_watched_xbmc: tv show "%s" has no tvdb-number in database. tvshowid=%d. Unique IDs: %s. Try rescraping.' % (item['title'], tvshowId_xbmc, str(list(item['uniqueid'].keys()))), xbmc.LOGINFO) + if not silent: + utils.showNotification(utils.getString(32101), utils.getString(32297) % (item['title'], tvshowId_xbmc), xbmc.LOGINFO) + tvshowId_tvdb = int(0) + self.tvshows[tvshowId_xbmc] = list([tvshowId_tvdb, item['title']]) + if tvshowId_tvdb > 0: + self.tvshownames[tvshowId_tvdb] = item['title'] + + # Get all watched movies and episodes by unique id from xbmc-database via JSONRPC + self.watchedmovielist_xbmc = list([]) + self.watchedepisodelist_xbmc = list([]) + for modus in ['movie', 'episode']: + if self.monitor.abortRequested(): + self.close_db(3) + return 4 + buggalo.addExtraData('modus', modus) + if modus == 'movie' and utils.getSetting("w_movies") != 'true': + continue + if modus == 'episode' and utils.getSetting("w_episodes") != 'true': + continue + utils.log(u'get_watched_xbmc: Get all %ss from Kodi database' % modus, xbmc.LOGDEBUG) + if modus == 'movie': + # use the JSON-RPC to access the xbmc-database. + json_response = utils.executeJSON({ + "jsonrpc": "2.0", + "method": "VideoLibrary.GetMovies", + "params": { + "properties": ["title", "year", "lastplayed", "playcount", "uniqueid"], + "sort": {"order": "ascending", "method": "title"} + }, + "id": 1 + }) + else: + json_response = utils.executeJSON({ + "jsonrpc": "2.0", + "method": "VideoLibrary.GetEpisodes", + "params": { + "properties": ["tvshowid", "season", "episode", "playcount", "showtitle", "lastplayed", "uniqueid"] + }, + "id": 1 + }) + if modus == 'movie': + searchkey = 'movies' + else: + searchkey = 'episodes' + if 'result' in json_response and json_response['result'] is not None and searchkey in json_response['result']: + # go through all watched movies and save them in the class-variable self.watchedmovielist_xbmc + for item in json_response['result'][searchkey]: + if self.monitor.abortRequested(): + break + if not 'uniqueid' in item: + if modus == 'movie': + utils.log(u'get_watched_xbmc: Movie %s has no field uniqueid in database. Try rescraping.' % (item['title']), xbmc.LOGINFO) + else: # episode + utils.log(u'get_watched_xbmc: Episode id %d (show %d, S%02dE%02d) has no field uniqueid in database. Try rescraping.' % (item['episodeid'], item['tvshowid'], item['season'], item['episode']), xbmc.LOGINFO) + continue + if modus == 'movie': + name = item['title'] + ' (' + str(item['year']) + ')' + try: + # check if movie number is in imdb-format (scraper=imdb) + res = re.compile(r'tt(\d+)').findall(item['uniqueid']['imdb']) + imdbId = int(res[0]) + except BaseException: + # no imdb-number for this movie in database. Skip + utils.log(u'get_watched_xbmc: Movie %s has no imdb-number in database. movieid=%d. IDs are %s. Try rescraping' % (name, int(item['movieid']), str(list(item['uniqueid'].keys()))), xbmc.LOGINFO) + imdbId = 0 + continue + else: # episodes + tvshowId_xbmc = item['tvshowid'] + try: + tvshowName_xbmc = item['showtitle'] + except BaseException: + # TODO: Something is wrong with the database or the json output since the field tvshowid is missing although requested. Check if this error still occurs and remove try-except + utils.log(u'get_watched_xbmc: TV episode id %d (show %d, S%02dE%02d) has no associated showtitle. Skipping.' % (item['episodeid'], item['tvshowid'], item['season'], item['episode']), xbmc.LOGWARNING) + continue + name = '%s S%02dE%02d' % (tvshowName_xbmc, item['season'], item['episode']) + try: + tvshowId_tvdb = self.tvshows[tvshowId_xbmc][0] + except BaseException: + utils.log(u'get_watched_xbmc: Kodi tv showid %d is not in Kodi-table tvshows. Skipping episode id %d (%s)' % (item['tvshowid'], item['episodeid'], name), xbmc.LOGINFO) + continue + if tvshowId_tvdb == 0: + utils.log(u'get_watched_xbmc: tvshow %d has no tvdb-number. Skipping episode id %d (%s)' % (item['tvshowid'], item['episodeid'], name), xbmc.LOGDEBUG) + continue + lastplayed = utils.sqlDateTimeToTimeStamp(item['lastplayed']) # convert to integer-timestamp + playcount = int(item['playcount']) + # add data to the class-variables + if modus == 'movie': + self.watchedmovielist_xbmc.append(list([imdbId, 0, 0, lastplayed, playcount, name, 0, int(item['movieid'])])) # 0imdbnumber, 1empty, 2empty, 3lastPlayed, 4playCount, 5title, 6empty, 7movieid + else: + self.watchedepisodelist_xbmc.append(list([tvshowId_tvdb, int(item['season']), int(item['episode']), lastplayed, playcount, name, 0, int(item['episodeid'])])) # 0tvdbnumber, 1season, 2episode, 3lastplayed, 4playcount, 5name, 6empty, 7episodeid + if not silent: + utils.showNotification(utils.getString(32101), utils.getString(32299) % (len(self.watchedmovielist_xbmc), len(self.watchedepisodelist_xbmc)), xbmc.LOGINFO) + if self.monitor.abortRequested(): + self.close_db(3) + return 4 + return 0 + except SystemExit: + return 4 + except BaseException: + utils.log(u'get_watched_xbmc: error getting the Kodi database : %s' % sys.exc_info()[2], xbmc.LOGERROR) + self.close_db(3) + buggalo.onExceptionRaised() + return 1 + + def get_watched_wl(self, silent): + """Get Watched States of WL Database + + Args: + silent: Do not show notifications if True + + Returns: + return code: + 0 successfully got watched states from WL-database + 1 unknown error (programming related) + 2 shutdown (error in subfunction) + 3 error related to opening the database + 4 exit requested (no error) + """ + + try: + buggalo.addExtraData('self_sqlcursor', self.sqlcursor_wl) + buggalo.addExtraData('self_sqlcon', self.sqlcon_wl) + if self.sqlcursor_wl == 0 or self.sqlcon_wl == 0: + if self.load_db(): + return 2 + + # get watched movies from addon database + self.watchedmovielist_wl = list([]) + if utils.getSetting("w_movies") == 'true': + utils.log(u'get_watched_wl: Get watched movies from WL database', xbmc.LOGDEBUG) + if int(utils.getSetting("db_format")) != 1: # SQLite3 File. Timestamp stored as integer + self.sqlcursor_wl.execute(QUERY_SELECT_MV_SQLITE) + else: # mySQL: Create integer timestamp with the request + self.sqlcursor_wl.execute(QUERY_SELECT_MV_MYSQL) + rows = self.sqlcursor_wl.fetchall() + for row in rows: + if self.monitor.abortRequested(): + self.close_db(1) + return 4 + self.watchedmovielist_wl.append(list([int(row[0]), 0, 0, int(row[1]), int(row[2]), row[3], int(row[4])])) # 0tvdbnumber, 1empty, 2empty, 3lastPlayed, 4playCount, 5title, 6lastChange + + # get watched episodes from addon database + self.watchedepisodelist_wl = list([]) + if utils.getSetting("w_episodes") == 'true': + utils.log(u'get_watched_wl: Get watched episodes from WL database', xbmc.LOGDEBUG) + if int(utils.getSetting("db_format")) != 1: # SQLite3 File. Timestamp stored as integer + self.sqlcursor_wl.execute(QUERY_SELECT_EP_SQLITE) + else: # mySQL: Create integer timestamp with the request + self.sqlcursor_wl.execute(QUERY_SELECT_EP_MYSQL) + + rows = self.sqlcursor_wl.fetchall() + for row in rows: + if self.monitor.abortRequested(): + self.close_db(1) + return 4 + try: + name = '%s S%02dE%02d' % (self.tvshownames[int(row[0])], int(row[1]), int(row[2])) + except BaseException: + name = 'tvdb-id %d S%02dE%02d' % (int(row[0]), int(row[1]), int(row[2])) + self.watchedepisodelist_wl.append(list([int(row[0]), int(row[1]), int(row[2]), int(row[3]), int(row[4]), name, int(row[5])])) # 0tvdbnumber, 1season, 2episode, 3lastplayed, 4playcount, 5name, 6lastChange + + if not silent: + utils.showNotification(utils.getString(32101), utils.getString(32298) % (len(self.watchedmovielist_wl), len(self.watchedepisodelist_wl)), xbmc.LOGINFO) + return 0 + except sqlite3.Error as err: + try: + errstring = err.args[0] # TODO: Find out, why this does not work some times + except BaseException: + errstring = '' + utils.log(u'get_watched_wl: SQLite Database error getting the wl database. %s' % errstring, xbmc.LOGERROR) + self.close_db(1) + # error could be that the database is locked (for tv show strings). This is not an error to disturb the other functions + return 3 + except mysql.connector.Error as err: + utils.log(u'get_watched_wl: MySQL Database error getting the wl database. %s' % err, xbmc.LOGERROR) + return 3 + except SystemExit: + return 4 + except BaseException: + utils.log(u'get_watched_wl: Error getting the wl database : %s' % sys.exc_info()[2], xbmc.LOGERROR) + self.close_db(1) + buggalo.onExceptionRaised() + return 1 + + def sync_tvshows(self): + """Sync List of TV Shows from Kodi to WL Database + + Returns: + return code: + 0 successfully synched tv shows + 1 database access error + 2 database loading error + 4 exit requested (no error) + """ + + try: + utils.log(u'sync_tvshows: sync tvshows with wl database : %s' % sys.exc_info()[2], xbmc.LOGDEBUG) + if self.sqlcursor_wl == 0 or self.sqlcon_wl == 0: + if self.load_db(): + return 2 + # write eventually new tv shows to wl database + for xbmcid in self.tvshows: + if self.monitor.abortRequested(): + break # all queries will be commited + values = self.tvshows[xbmcid] + if values[0] == 0: + # no imdb-id saved for this tv show. Nothing to process. + continue + if int(utils.getSetting("db_format")) != 1: # sqlite3 + self.sqlcursor_wl.execute(QUERY_INSERT_SS_SQLITE, values) + else: # mysql + self.sqlcursor_wl.execute(QUERY_INSERT_SS_MYSQL, values) + self.database_backup() + self.sqlcon_wl.commit() + if self.monitor.abortRequested(): + self.close_db(1) + return 4 + # get all known tv shows from wl database + self.sqlcursor_wl.execute("SELECT idShow, title FROM tvshows") + rows = self.sqlcursor_wl.fetchall() + for row_i in rows: + if self.monitor.abortRequested(): + break + self.tvshownames[int(row_i[0])] = row_i[1] + except sqlite3.Error as err: + try: + errstring = err.args[0] # TODO: Find out, why this does not work some times + except BaseException: + errstring = '' + utils.log(u'sync_tvshows: SQLite Database error accessing the wl database: ''%s''' % errstring, xbmc.LOGERROR) + self.close_db(1) + # error could be that the database is locked (for tv show strings). + return 1 + except mysql.connector.Error as err: + utils.log(u"sync_tvshows: MySQL Database error accessing the wl database: ''%s''" % (err), xbmc.LOGERROR) + self.close_db(1) + return 1 + except SystemExit: + return 4 + except BaseException: + utils.log(u'sync_tvshows: Error getting the wl database: ''%s''' % sys.exc_info()[2], xbmc.LOGERROR) + self.close_db(1) + buggalo.onExceptionRaised() + return 1 + if self.monitor.abortRequested(): + return 4 + return 0 + + def write_wl_wdata(self): + """Go through all watched movies from Kodi and check whether they are up to date in the addon database + + Returns: + return code: + 0 successfully written WL + 1 program exception + 2 database loading error + 4 SystemExit + """ + + buggalo.addExtraData('self_sqlcursor', self.sqlcursor_wl) + buggalo.addExtraData('self_sqlcon', self.sqlcon_wl) + if self.sqlcursor_wl == 0 or self.sqlcon_wl == 0: + if self.load_db(): + return 2 + for modus in ['movie', 'episode']: + buggalo.addExtraData('modus', modus) + if modus == 'movie' and utils.getSetting("w_movies") != 'true': + continue + if modus == 'episode' and utils.getSetting("w_episodes") != 'true': + continue + utils.log(u'write_wl_wdata: Write watched %ss to WL database' % modus, xbmc.LOGDEBUG) + count_insert = 0 + count_update = 0 + if utils.getSetting("progressdialog") == 'true': + DIALOG_PROGRESS = xbmcgui.DialogProgress() + DIALOG_PROGRESS.create(utils.getString(32101), utils.getString(32105)) + if modus == 'movie': + list_length = len(self.watchedmovielist_xbmc) + else: + list_length = len(self.watchedepisodelist_xbmc) + + for i in range(list_length): + if self.monitor.abortRequested(): + break # this loop can take some time in debug mode and prevents Kodi to exit + if utils.getSetting("progressdialog") == 'true' and DIALOG_PROGRESS.iscanceled(): + if modus == 'movie': + strno = 32202 + else: + strno = 32203 + utils.showNotification(utils.getString(strno), utils.getString(32301) % (count_insert, count_update), xbmc.LOGINFO) + return 2 + if modus == 'movie': + row_xbmc = self.watchedmovielist_xbmc[i] + else: + row_xbmc = self.watchedepisodelist_xbmc[i] + + if utils.getSetting("progressdialog") == 'true': + DIALOG_PROGRESS.update(int(100 * (i + 1) / list_length), (utils.getString(32105)+"\n"+utils.getString(32610) % (i + 1, list_length, row_xbmc[5]))) + + try: + res = self._wl_update_media(modus, row_xbmc, 0, 0, 0) + count_insert += res['num_new'] + count_update += res['num_update'] + + except sqlite3.Error as err: + try: + errstring = err.args[0] # TODO: Find out, why this does not work some times + except BaseException: + errstring = '' + utils.log(u'write_wl_wdata: SQLite Database error ''%s'' while updating %s %s' % (errstring, modus, row_xbmc[5]), xbmc.LOGERROR) + # error at this place is the result of duplicate movies, which produces a DUPLICATE PRIMARY KEY ERROR + return 1 + except mysql.connector.Error as err: + utils.log(u'write_wl_wdata: MySQL Database error ''%s'' while updating %s %s' % (err, modus, row_xbmc[5]), xbmc.LOGERROR) + self.close_db(1) + return 1 # error while writing. Do not continue with episodes, if movies raised an exception + except SystemExit: + return 4 + except BaseException: + utils.log(u'write_wl_wdata: Error while updating %s %s: %s' % (modus, row_xbmc[5], sys.exc_info()[2]), xbmc.LOGERROR) + self.close_db(1) + if utils.getSetting("progressdialog") == 'true': + DIALOG_PROGRESS.close() + buggalo.addExtraData('count_update', count_update) + buggalo.addExtraData('count_insert', count_insert) + buggalo.onExceptionRaised() + return 1 + if utils.getSetting("progressdialog") == 'true': + DIALOG_PROGRESS.close() + if self.monitor.abortRequested(): + break # break outer loop if exit requested. Do not do any database operations below + # only commit the changes if no error occured to ensure database persistence + if count_insert > 0 or count_update > 0: + self.database_backup() + self.sqlcon_wl.commit() + if modus == 'movie': + strno = [32202, 32301] + else: + strno = [32203, 32301] + utils.showNotification(utils.getString(strno[0]), utils.getString(strno[1]) % (count_insert, count_update), xbmc.LOGINFO) + return 0 + + def write_xbmc_wdata(self, progressdialogue, notifications): + """Go through all watched movies/episodes from the wl-database and check, + if the xbmc-database is up to date + + Args: + progressdialogue: Show Progress Bar if True + notifications: 0= no, 1=only changed info, 2=all + + Returns: + return code: + 0 successfully written Kodi database + 1 program exception + 2 cancel by user interaction + 4 SystemExit + """ + + for modus in ['movie', 'episode']: + buggalo.addExtraData('modus', modus) + if modus == 'movie' and utils.getSetting("w_movies") != 'true': + continue + if modus == 'episode' and utils.getSetting("w_episodes") != 'true': + continue + + utils.log(u'write_xbmc_wdata: Write watched %ss to Kodi database (pd=%d, noti=%d)' % (modus, progressdialogue, notifications), xbmc.LOGDEBUG) + count_update = 0 + if progressdialogue: + DIALOG_PROGRESS = xbmcgui.DialogProgress() + DIALOG_PROGRESS.create(utils.getString(32101), utils.getString(32106)) + + # list to iterate over + if modus == 'movie': + list_length = len(self.watchedmovielist_wl) + else: + list_length = len(self.watchedepisodelist_wl) + # iterate over wl-list + for j in range(list_length): + if self.monitor.abortRequested(): + break # this loop can take some time in debug mode and prevents Kodi to exit + if progressdialogue and DIALOG_PROGRESS.iscanceled(): + if notifications > 0: + utils.showNotification(utils.getString(32204), utils.getString(32302) % (count_update), xbmc.LOGINFO) + return 2 + # get media-specific list items + if modus == 'movie': + row_wl = self.watchedmovielist_wl[j] + else: + row_wl = self.watchedepisodelist_wl[j] + season = row_wl[1] + episode = row_wl[2] + imdbId = row_wl[0] + name = row_wl[5] + + if progressdialogue: + DIALOG_PROGRESS.update(int(100 * (j + 1) / list_length), (utils.getString(32106)+"\n"+utils.getString(32610) % (j + 1, list_length, name))) + try: + # search the unique movie/episode id in the xbmc-list + if modus == 'movie': + indices = [i for i, x in enumerate(self.watchedmovielist_xbmc) if x[0] == imdbId] # the movie can have multiple entries in xbmc + else: + indices = [i for i, x in enumerate(self.watchedepisodelist_xbmc) if x[0] == imdbId and x[1] == season and x[2] == episode] + lastplayed_wl = row_wl[3] + playcount_wl = row_wl[4] + lastchange_wl = row_wl[6] + if indices: + # the movie/episode is already in the xbmc-list + for i in indices: + if modus == 'movie': + row_xbmc = self.watchedmovielist_xbmc[i] + else: + row_xbmc = self.watchedepisodelist_xbmc[i] + + lastplayed_xbmc = row_xbmc[3] + playcount_xbmc = row_xbmc[4] + + change_xbmc_db = False + # check if movie/episode is set as unwatched in the wl database + if playcount_wl != playcount_xbmc and lastchange_wl > lastplayed_xbmc: + change_xbmc_db = True + # compare playcount and lastplayed (update if Kodi data is older) + if playcount_xbmc < playcount_wl or (lastplayed_xbmc < lastplayed_wl and playcount_wl > 0): + change_xbmc_db = True + if not change_xbmc_db: + # utils.log(u'write_xbmc_wdata: Kodi database up-to-date for tt%d, %s' % (imdbId, row_xbmc[2]), xbmc.LOGDEBUG) + continue + # check if the lastplayed-timestamp in wl is useful + if playcount_wl == 0: + lastplayed_new = 0 + else: + if lastplayed_wl == 0: + lastplayed_new = lastplayed_xbmc + else: + lastplayed_new = lastplayed_wl + # update database + mediaid = row_xbmc[7] + if modus == 'movie': + jsonmethod = "VideoLibrary.SetMovieDetails" + idfieldname = "movieid" + else: + jsonmethod = "VideoLibrary.SetEpisodeDetails" + idfieldname = "episodeid" + jsondict = { + "jsonrpc": "2.0", + "method": jsonmethod, + "params": {idfieldname: mediaid, "playcount": playcount_wl, "lastplayed": utils.TimeStamptosqlDateTime(lastplayed_new)}, + "id": 1 + } + json_response = utils.executeJSON(jsondict) + if 'result' in json_response and json_response['result'] == 'OK': + utils.log(u'write_xbmc_wdata: Kodi database updated for %s. playcount: {%d -> %d}, lastplayed: {"%s" -> "%s"} (%sid=%d)' % (name, playcount_xbmc, playcount_wl, utils.TimeStamptosqlDateTime(lastplayed_xbmc), utils.TimeStamptosqlDateTime(lastplayed_new), modus, mediaid), xbmc.LOGINFO) + if playcount_wl == 0: + if notifications > 0: + utils.showNotification(utils.getString(32404), name, xbmc.LOGDEBUG) + else: + if notifications > 0: + utils.showNotification(utils.getString(32401), name, xbmc.LOGDEBUG) + count_update += 1 + # update the xbmc-db-mirror-variable + if modus == 'movie': + self.watchedmovielist_xbmc[i][3] = lastplayed_new + self.watchedmovielist_xbmc[i][4] = playcount_wl + else: + self.watchedepisodelist_xbmc[i][3] = lastplayed_new + self.watchedepisodelist_xbmc[i][4] = playcount_wl + else: + utils.log(u'write_xbmc_wdata: error updating Kodi database. %s. json_response=%s' % (name, str(json_response)), xbmc.LOGERROR) + + else: + # the movie is in the watched-list but not in the xbmc-list -> no action + # utils.log(u'write_xbmc_wdata: movie not in Kodi database: tt%d, %s' % (imdbId, row_xbmc[2]), xbmc.LOGDEBUG) + continue + except SystemExit: + return 4 + except BaseException: + utils.log(u"write_xbmc_wdata: Error while updating %s %s: %s" % (modus, name, sys.exc_info()[2]), xbmc.LOGERROR) + if progressdialogue: + DIALOG_PROGRESS.close() + buggalo.addExtraData('count_update', count_update) + buggalo.onExceptionRaised() + return 1 + + if progressdialogue: + DIALOG_PROGRESS.close() + if self.monitor.abortRequested(): + break # break the outer loop (movie/episode if exit requested) + if notifications > 1: + if modus == 'movie': + strno = [32204, 32302] + else: + strno = [32205, 32303] + utils.showNotification(utils.getString(strno[0]), utils.getString(strno[1]) % (count_update), xbmc.LOGINFO) + return 0 + + def database_backup(self): + """create a copy of the database, in case something goes wrong (only if database file is used) + + Returns: + return code: + 0 successfully copied database + 1 file writing error + 2 program exception + 4 SystemExit + """ + + if utils.getSetting("db_format") != '0': + return 0 # no backup needed since we are using mysql database + + if utils.getSetting('dbbackupcount') == '0': + return 0 # no backup requested in the addon settings + + if not self.dbbackupdone: + if not xbmcvfs.exists(self.dbpath): + utils.log(u'database_backup: directory %s does not exist. No backup possible.' % self.dbpath, xbmc.LOGERROR) + return 1 + now = datetime.datetime.now() + timestr = u'%04d%02d%02d_%02d%02d%02d' % (now.year, now.month, now.day, now.hour, now.minute, now.second) + zipfilename = os.path.join(self.dbdirectory, timestr + u'-watchedlist.db.zip') + try: + with zipfile.ZipFile(zipfilename, 'w') as zf: + zf.write(self.dbpath, arcname='watchedlist.db', compress_type=zipfile.ZIP_DEFLATED) + self.dbbackupdone = True + utils.log(u'database_backup: database backup copy created to %s' % zipfilename, xbmc.LOGINFO) + # copy the zip file with Kodi file system, if needed + if self.dbfileaccess == 'copy': + xbmcvfs.copy(zipfilename, os.path.join(self.dbdirectory_copy, timestr + u'-watchedlist.db.zip')) + xbmcvfs.delete(zipfilename) + except ValueError as err: # e.g. "timestamps before 1980" + utils.showNotification(utils.getString(32102), utils.getString(32608) % str(err), xbmc.LOGERROR) + utils.log(u'database_backup: Error creating database backup %s: %s' % (zipfilename, str(err)), xbmc.LOGERROR) + self.dbbackupdone = True # pretend this was done to avoid log spamming + return 2 + except IOError as err: # e.g. "permission denied" + utils.showNotification(utils.getString(32102), utils.getString(32608) % err.strerror, xbmc.LOGERROR) + utils.log(u'database_backup: Error creating database backup %s: (%s) %s' % (zipfilename, err.errno, err.strerror), xbmc.LOGERROR) + self.dbbackupdone = True # pretend this was done to avoid log spamming + return 2 + except SystemExit: + return 4 + except BaseException: + buggalo.addExtraData('zipfilename', zipfilename) + buggalo.onExceptionRaised() + return 2 + return 0 + + def database_backup_delete(self): + """delete old backup files + + Returns: + return code: + 0 no operation done or operation successful + 1 error deleting the backups + """ + + if not self.dbbackupdone: + return 0 + # Limit number of backup files to the specified value + backupsize = int(utils.getSetting('dbbackupcount')) + if backupsize == -1: + return 0 # do not delete old backup files + if self.dbfileaccess == 'copy': + # Database is on a network share. The backup is also copied to that location. Delete old backups there. + backupdir = self.dbdirectory_copy + else: + # Database and backups are in the default folders + backupdir = self.dbdirectory + + files = xbmcvfs.listdir(backupdir)[1] + # find database copy files among all files in that directory + files_match = [] + for i, f in enumerate(files): + if self.monitor.abortRequested(): + break + if re.match(r'\d+_\d+-watchedlist\.db\.zip', f) is not None: # match the filename string from database_backup() + files_match.append(f) + files_match = sorted(files_match, reverse=True) + # Iterate over backup files starting with newest. Delete oldest + for i, f in enumerate(files_match): + if self.monitor.abortRequested(): + break + if i >= int(utils.getSetting('dbbackupcount')): + # delete file + utils.log(u'database_backup_delete: Delete old backup file %d/%d (%s)' % (i + 1, len(files_match), f), xbmc.LOGINFO) + try: + xbmcvfs.delete(os.path.join(backupdir, f)) + except BaseException: + utils.log(u'database_backup_delete: Error deleting old backup file %d (%s)' % (i, os.path.join(backupdir, f)), xbmc.LOGERROR) + return 1 + return 0 + + def watch_user_changes(self, idletime_old, idletime): + """check if the user made changes in the watched states. Especially setting movies as "not watched". + This can not be recognized by the other functions + + Args: + idletime_old: Old Idle Time + idletime: New Idle Time + + Returns: + return code: + 0 no operation done + 1 operation successful + 2 database error + 4 system exit (no error) + """ + + if xbmc.Player().isPlaying(): + return 0 + if idletime > idletime_old: + # the idle time increased. No user interaction probably happened + return 0 + self.watch_user_changes_count = self.watch_user_changes_count + 1 + utils.log(u'watch_user_changes: Check for user changes (no. %d)' % self.watch_user_changes_count, xbmc.LOGDEBUG) + + # save previous state + old_watchedmovielist_xbmc = self.watchedmovielist_xbmc + old_watchedepisodelist_xbmc = self.watchedepisodelist_xbmc + # get new state + self.get_watched_xbmc(1) + # save exception information + buggalo.addExtraData('len_old_watchedmovielist_xbmc', len(old_watchedmovielist_xbmc)) + buggalo.addExtraData('len_old_watchedepisodelist_xbmc', len(old_watchedepisodelist_xbmc)) + buggalo.addExtraData('len_self_watchedmovielist_xbmc', len(self.watchedmovielist_xbmc)) + buggalo.addExtraData('len_self_watchedepisodelist_xbmc', len(self.watchedepisodelist_xbmc)) + # Separate the change detection and the change in the database to + # prevent circle reference: Two steps for watching user changes + # First step: Compare states of movies/episodes + for modus in ['movie', 'episode']: + if self.monitor.abortRequested(): + return 4 + buggalo.addExtraData('modus', modus) + if modus == 'movie' and utils.getSetting("w_movies") != 'true': + continue + if modus == 'episode' and utils.getSetting("w_episodes") != 'true': + continue + if modus == 'movie': + list_new = self.watchedmovielist_xbmc + list_old = old_watchedmovielist_xbmc + else: + list_new = self.watchedepisodelist_xbmc + list_old = old_watchedepisodelist_xbmc + if not list_old or not list_new: + # one of the lists is empty: nothing to compare. No user changes noticable + continue + indices_changed = list([]) # list for corresponding new/old indices + for i_n, row_xbmc in enumerate(list_new): + if self.monitor.abortRequested(): + return 4 + mediaid = row_xbmc[7] + lastplayed_new = row_xbmc[3] + playcount_new = row_xbmc[4] + # index of this movie/episode in the old database (before the change by the user) + if (len(list_old) > i_n) and (list_old[i_n][7] == mediaid): + i_o = i_n # db did not change + else: # search the movieid + i_o = [i for i, x in enumerate(list_old) if x[7] == mediaid] + if not i_o: + continue # movie is not in old array + i_o = i_o[0] # convert list to int + lastplayed_old = list_old[i_o][3] + playcount_old = list_old[i_o][4] + + if playcount_new != playcount_old or lastplayed_new != lastplayed_old: + if playcount_new == playcount_old and playcount_new == 0: + continue # do not add lastplayed to database, when playcount = 0 + # The user changed the playcount or lastplayed. + # update wl with new watched state + indices_changed.append([i_n, i_o]) + + # Second step: Go through all movies changed by the user + for icx in indices_changed: + if self.monitor.abortRequested(): + return 4 + i_o = icx[1] + i_n = icx[0] + row_xbmc = list_new[i_n] + row_xbmc_old = list_old[i_o] + lastplayed_old = row_xbmc_old[3] + playcount_old = row_xbmc_old[4] + lastplayed_new = row_xbmc[3] + playcount_new = row_xbmc[4] + mediaid = row_xbmc[7] + utils.log(u'watch_user_changes: %s "%s" changed playcount {%d -> %d} lastplayed {"%s" -> "%s"}. %sid=%d' % (modus, row_xbmc[5], playcount_old, playcount_new, utils.TimeStamptosqlDateTime(lastplayed_old), utils.TimeStamptosqlDateTime(lastplayed_new), modus, mediaid)) + try: + self._wl_update_media(modus, row_xbmc, 1, 1, 0) + except sqlite3.Error as err: + try: + errstring = err.args[0] # TODO: Find out, why this does not work some times + except BaseException: + errstring = '' + utils.log(u'watch_user_changes: SQLite Database error (%s) while updating %s %s' % (errstring, modus, row_xbmc[5])) + utils.showNotification(utils.getString(32102), utils.getString(32606) % ('(%s)' % errstring), xbmc.LOGERROR) + # error because of db locked or similar error + self.close_db(1) + return 2 + except mysql.connector.Error as err: + # Catch common mysql errors and show them to guide the user + utils.log(u'watch_user_changes: MySQL Database error (%s) while updating %s %s' % (err, modus, row_xbmc[5])) + utils.showNotification(utils.getString(32102), utils.getString(32606) % ('(%s)' % err), xbmc.LOGERROR) + self.close_db(1) + return 2 + + # update Kodi watched status, e.g. to set duplicate movies also as watched + if indices_changed: + self.write_xbmc_wdata(0, 1) # this changes self.watchedmovielist_xbmc + return 1 + + def _wl_update_media(self, mediatype, row_xbmc, saveanyway, commit, lastChange): + """update the wl database for one movie/episode with the information in row_xbmc. + + This function is intended to be private and should not be called externally + + Args: + mediatype: 'episode' or 'movie' + row_xbmc: One row of the Kodi media table self.watchedmovielist_xbmc. + saveanyway: Skip checks whether not to save the changes + commit: The db change is committed directly (slow with many movies, but safe) + lastChange: Last change timestamp of the given data. + If 0: Data from kodi. + If >0: Data from other watchedlist database for merging + + Returns: Dict with fields + errcode: + 0 No errors + 2 error loading the database + num_new, num_update: + Number of new and updated entries + """ + retval = {'errcode': 0, 'num_new': 0, 'num_update': 0} + buggalo.addExtraData('self_sqlcursor', self.sqlcursor_wl) + buggalo.addExtraData('self_sqlcon', self.sqlcon_wl) + buggalo.addExtraData('len_self_watchedmovielist_wl', len(self.watchedmovielist_wl)) + buggalo.addExtraData('len_self_watchedepisodelist_wl', len(self.watchedepisodelist_wl)) + buggalo.addExtraData('len_self_tvshownames', len(self.tvshownames)) + buggalo.addExtraData('row_xbmc', row_xbmc) + buggalo.addExtraData('saveanyway', saveanyway) + if self.sqlcursor_wl == 0 or self.sqlcon_wl == 0: + if self.load_db(): + retval['errcode'] = 2 + return retval + + buggalo.addExtraData('modus', mediatype) + # row_xbmc: 0imdbnumber, 1empty, 2empty, 3lastPlayed, 4playCount, 5title, 6empty, 7movieid + imdbId = row_xbmc[0] + lastplayed_xbmc = row_xbmc[3] + playcount_xbmc = row_xbmc[4] + name = row_xbmc[5] + if mediatype == 'episode': + season = row_xbmc[1] + episode = row_xbmc[2] + + self.database_backup() + if self.sqlcursor_wl == 0 or self.sqlcon_wl == 0: + if self.load_db(): + retval['errcode'] = 2 + return retval + if not saveanyway and playcount_xbmc == 0 and lastChange == 0: + # playcount in xbmc-list is empty. Nothing to save + # utils.log(u'wl_update_%s: not watched in xbmc: tt%d, %s' % (modus, imdbId, name), xbmc.LOGDEBUG) + return retval + if lastChange == 0: + lastchange_new = int(time.time()) + else: # data from WL database with given last change timestamp + lastchange_new = lastChange + if lastplayed_xbmc == -1: # used for external calls + lastplayed_xbmc = int(time.time()) + if mediatype == 'movie': + j = [ii for ii, x in enumerate(self.watchedmovielist_wl) if x[0] == imdbId] + else: # if mediatype == 'episode': + j = [ii for ii, x in enumerate(self.watchedepisodelist_wl) if x[0] == imdbId and x[1] == season and x[2] == episode] + if j: # j is the list of indexes of the occurences of the given row + j = j[0] # there can only be one valid index j, since only one entry in wl per imdbId + # the movie is already in the watched-list + if mediatype == 'movie': + row_wl = self.watchedmovielist_wl[j] + else: + row_wl = self.watchedepisodelist_wl[j] + lastplayed_wl = row_wl[3] + playcount_wl = row_wl[4] + lastchange_wl = row_wl[6] + + if not saveanyway: + # check if an update of the wl database is necessary (xbmc watched status newer) + if lastChange == 0: # information from xbmc: Criterion Playcount and lastplayed-timestamp + if lastchange_wl > lastplayed_xbmc: + return retval # no update of WL-db. Return + if playcount_wl >= playcount_xbmc and lastplayed_wl >= lastplayed_xbmc: + return retval # everything up-to-date + elif lastChange <= lastchange_wl: # information from watchedlist. Only criterion: lastChange-timestamp + return retval + + # check if the lastplayed-timestamp in Kodi is useful + if lastplayed_xbmc == 0 and lastChange == 0: + lastplayed_new = lastplayed_wl + else: + lastplayed_new = lastplayed_xbmc + else: + lastplayed_new = lastplayed_xbmc + + if mediatype == 'movie': + if int(utils.getSetting("db_format")) != 1: # sqlite3 + sql = QUERY_MV_UPDATE_SQLITE + else: # mysql + sql = QUERY_MV_UPDATE_MYSQL + values = list([playcount_xbmc, lastplayed_new, lastchange_new, imdbId]) + else: + if int(utils.getSetting("db_format")) != 1: # sqlite3 + sql = QUERY_EP_UPDATE_SQLITE + else: # mysql + sql = QUERY_EP_UPDATE_MYSQL + values = list([playcount_xbmc, lastplayed_new, lastchange_new, imdbId, season, episode]) + self.sqlcursor_wl.execute(sql, values) + retval['num_update'] = self.sqlcursor_wl.rowcount + # update the local mirror variable of the wl database: # 0imdbnumber, season, episode, 3lastPlayed, 4playCount, 5title, 6lastChange + if mediatype == 'movie': + self.watchedmovielist_wl[j] = list([imdbId, 0, 0, lastplayed_new, playcount_xbmc, name, lastchange_new]) + else: + self.watchedepisodelist_wl[j] = list([imdbId, season, episode, lastplayed_new, playcount_xbmc, name, lastchange_new]) + utils.log(u'wl_update_%s: updated wl db for "%s" (id %d). playcount: {%d -> %d}. lastplayed: {"%s" -> "%s"}. lastchange: "%s. Affected %d row."' % (mediatype, name, imdbId, playcount_wl, playcount_xbmc, utils.TimeStamptosqlDateTime(lastplayed_wl), utils.TimeStamptosqlDateTime(lastplayed_new), utils.TimeStamptosqlDateTime(lastchange_new), self.sqlcursor_wl.rowcount), xbmc.LOGDEBUG) + if playcount_xbmc > 0: + utils.showNotification(utils.getString(32403), name, xbmc.LOGDEBUG) + else: + utils.showNotification(utils.getString(32405), name, xbmc.LOGDEBUG) + else: + # the movie is not in the watched-list -> insert the movie + # order: idMovieImdb,playCount,lastChange,lastPlayed,title + if mediatype == 'movie': + if int(utils.getSetting("db_format")) != 1: # sqlite3 + sql = QUERY_MV_INSERT_SQLITE + else: # mysql + sql = QUERY_MV_INSERT_MYSQL + values = list([imdbId, playcount_xbmc, lastchange_new, lastplayed_xbmc, name]) + else: # episode + if int(utils.getSetting("db_format")) != 1: # sqlite3 + sql = QUERY_EP_INSERT_SQLITE + else: # mysql + sql = QUERY_EP_INSERT_MYSQL + values = list([imdbId, season, episode, playcount_xbmc, lastchange_new, lastplayed_xbmc]) + self.sqlcursor_wl.execute(sql, values) + utils.log(u'wl_update_%s: new entry for wl database: "%s", lastChange="%s", lastPlayed="%s", playCount=%d. Affected %d row.' % (mediatype, name, utils.TimeStamptosqlDateTime(lastchange_new), utils.TimeStamptosqlDateTime(lastplayed_xbmc), playcount_xbmc, self.sqlcursor_wl.rowcount)) + retval['num_new'] = self.sqlcursor_wl.rowcount + # update the local mirror variable of the wl database + if mediatype == 'movie': + self.watchedmovielist_wl.append(list([imdbId, 0, 0, lastplayed_xbmc, playcount_xbmc, name, lastchange_new])) + else: + self.watchedepisodelist_wl.append(list([imdbId, season, episode, lastplayed_xbmc, playcount_xbmc, name, lastchange_new])) + if playcount_xbmc > 0: + utils.showNotification(utils.getString(32402), name, xbmc.LOGDEBUG) + else: + utils.showNotification(utils.getString(32405), name, xbmc.LOGDEBUG) + if commit: + self.sqlcon_wl.commit() + return retval + + def wl_update_media(self, mediatype, row_xbmc, saveanyway, commit, lastChange): + """update the wl database for one movie/episode with the information in row_xbmc. + + Function for external access with basic error handling + + Args: + mediatype: 'episode' or 'movie' + row_xbmc: One row of the Kodi media table self.watchedmovielist_xbmc or self.watchedepisodelist_xbmc. + List with [0imdbnumber, 1empty, 2empty, 3lastPlayed, 4playCount, 5title, 6empty, 7movieid] + or [0tvdbnumber, 1season, 2episode, 3lastplayed, 4playcount, 5name, 6empty, 7episodeid] + saveanyway: Skip checks whether not to save the changes + commit: The db change is committed directly (slow with many movies, but safe) + lastChange: Last change timestamp of the given data. + If 0: Data from kodi. + If >0: Data from other watchedlist database for merging + + Returns: Dict with fields + errcode: + 0 No errors + 1 error with the database + 2 error loading the database + num_new, num_update: + Number of new and updated entries + """ + retval = {'errcode': 0, 'num_new': 0, 'num_update': 0} + try: + return self._wl_update_media(mediatype, row_xbmc, saveanyway, commit, lastChange) + except sqlite3.Error as err: + try: + errstring = err.args[0] # TODO: Find out, why this does not work some times + except BaseException: + errstring = '' + utils.log(u'wl_update_media: SQLite Database error accessing the wl database: ''%s''' % errstring, xbmc.LOGERROR) + utils.showNotification(utils.getString(32109), errstring, xbmc.LOGERROR) + self.close_db(1) + retval['errcode'] = 1 + except mysql.connector.Error as err: + utils.log(u"wl_update_media: MySQL Database error accessing the wl database: ''%s''" % (err.msg), xbmc.LOGERROR) + utils.showNotification(utils.getString(32108), err.msg, xbmc.LOGERROR) + self.close_db(1) + retval['errcode'] = 1 + return retval + + def merge_dropbox_local(self): + """ + Merge the remote (eg: Dropbox) database into the local one + The resulting merged database contains all watched movies and episodes of both databases + + Returns: + return code: + 0 successfully synched databases + 1 database access error + 2 database loading error + 4 exit requested (no error) + """ + + if not self.dropbox_path: + utils.log(u'merge_dropbox_local: no dropbox path -- assuming download failed. not merging remote database.') + return 1 + + try: + if self.sqlcursor_wl == 0 or self.sqlcon_wl == 0: + if self.load_db(): + return 2 + + # do not merge tvshows between dropbox and local wl database. + # Only movies and episodes + count_insert = 0 + count_update = 0 + for mediatype in ['movie', 'episode']: + # strno: number of string for heading of notifications + # sql_select_dropbox: Definitions of SQL queries to get data from the dropbox database + if mediatype == 'movie': + strno = 32711 + sql_select_dropbox = QUERY_SELECT_MV_SQLITE + else: + strno = 32712 + sql_select_dropbox = QUERY_SELECT_EP_SQLITE + utils.log(u'wl_merge_dropbox_local (%s): Start merging the remote into the local database' % mediatype) + self.sqlcursor_db.execute(sql_select_dropbox) + # loop through all rows of the remote (dropbox) database and merge it into the local database with + # with the function for merging the Kodi database + if utils.getSetting("progressdialog") == 'true': + DIALOG_PROGRESS = xbmcgui.DialogProgress() + DIALOG_PROGRESS.create(utils.getString(strno), utils.getString(32105)) + rows = self.sqlcursor_db.fetchall() + list_length = len(rows) + for i in range(list_length): + if self.monitor.abortRequested(): + break + row = rows[i] # see definition of sql_select_dropbox for contents of `row` + if mediatype == 'movie': # idMovieImdb, 1lastPlayed, 2playCount, 3title, 4lastChange + name = "%s" % row[3] + playCount = row[2] + lastChange = row[4] + lastPlayed = row[1] + else: # 0idShow, 1season, 2episode, 3lastPlayed, 4playCount, 5lastChange + try: + name = '%s S%02dE%02d' % (self.tvshownames[int(row[0])], int(row[1]), int(row[2])) + except BaseException: + name = 'tvdb-id %d S%02dE%02d' % (int(row[0]), int(row[1]), int(row[2])) + playCount = row[4] + lastChange = row[5] + lastPlayed = row[3] + + # handle the row from the dropbox database as if it came from the Kodi database and + # store it in the local WL database (same function call) + # row_xbmc_sim: 0imdbnumber, 1seasonnumber, 2episodenumber, 3lastPlayed, 4playCount, 5title, 6empty, 7movieid + row_xbmc_sim = [0, 0, 0, lastPlayed, playCount, name, 0] + if mediatype == 'movie': + row_xbmc_sim[0] = row[0] + else: + row_xbmc_sim[0:3] = row[0:3] + res = self._wl_update_media(mediatype, row_xbmc_sim, 0, 0, lastChange) + count_insert += res['num_new'] + count_update += res['num_update'] + + # check if update is canceled + if utils.getSetting("progressdialog") == 'true' and DIALOG_PROGRESS.iscanceled(): + return 2 + if utils.getSetting("progressdialog") == 'true': + DIALOG_PROGRESS.update(int(100 * (i + 1) / list_length), (utils.getString(32105)+"\n"+utils.getString(32610) % (i + 1, list_length, row_xbmc_sim[5]))) + + utils.showNotification(utils.getString(strno), utils.getString(32301) % (count_insert, count_update), xbmc.LOGINFO) + if utils.getSetting("progressdialog") == 'true': + DIALOG_PROGRESS.close() + if self.monitor.abortRequested(): + return 4 + except sqlite3.Error as err: + try: + errstring = err.args[0] # TODO: Find out, why this does not work some times + except BaseException: + errstring = '' + utils.log(u'merge_dropbox_local: SQLite Database error accessing the wl database: ''%s''' % errstring, xbmc.LOGERROR) + self.close_db(3) + # error could be that the database is locked (for tv show strings). + if utils.getSetting("progressdialog") == 'true': + DIALOG_PROGRESS.close() + return 1 + except SystemExit: + return 4 + except BaseException: + utils.log(u'merge_dropbox_local: Error getting the wl database: ''%s''' % sys.exc_info()[2], xbmc.LOGERROR) + self.close_db(3) + buggalo.onExceptionRaised() + if utils.getSetting("progressdialog") == 'true': + DIALOG_PROGRESS.close() + return 1 + # commit all changes: This saves the database file physically + self.sqlcon_wl.commit() + return 0 + + def merge_local_dropbox(self): + """ + Merge the local database into the remote one (e.g. dropbox) by copying all tables directly + the content is already merged after loading the remote database (merge_dropbox_local) + + Returns: + return code: + 0 successfully synched databases + 1 database access error + 2 database loading error + 4 exit requested (no error) + """ + + if not self.dropbox_path: + utils.log(u'merge_dropbox: no dropbox path -- assuming download failed. not merging remote database.') + return 1 + + try: + if self.sqlcursor_wl == 0 or self.sqlcon_wl == 0: + if self.load_db(): + return 2 + + # do not merge tvshows between dropbox and local wl database + + # clear dropbox database and just insert all rows from the local db + self.sqlcursor_db.execute(QUERY_CLEAR_MV_SQLITE) + self.sqlcursor_db.execute(QUERY_CLEAR_EP_SQLITE) + + for mediatype in ['movie', 'episode']: + # strno: number of string for heading of notifications + # sql_select_wl: Definitions of SQL queries to get data from the local database + utils.log(u'merge_local_dropbox (%s): Start merging the local into the remote database' % mediatype) + if mediatype == 'movie': + strno = 32718 + rows = self.watchedmovielist_wl # 0imdbnumber, 1empty, 2empty, 3lastPlayed, 4playCount, 5title, 6lastChange + else: + strno = 32719 + rows = self.watchedepisodelist_wl # 0tvdbnumber, 1season, 2episode, 3lastplayed, 4playcount, 5empty, 6lastChange + + # loop through all rows of the local database and merge it into the remote (dropbox) database + if utils.getSetting("progressdialog") == 'true': + DIALOG_PROGRESS = xbmcgui.DialogProgress() + DIALOG_PROGRESS.create(utils.getString(strno), utils.getString(32716)) + list_length = len(rows) + for i in range(list_length): + if self.monitor.abortRequested(): + break + row = rows[i] # see definition of queries for contents of `row` + if mediatype == 'movie': + name = row[5] + sql = QUERY_MV_INSERT_SQLITE # idMovieImdb,playCount,lastChange,lastPlayed,title + values = list([row[0], row[4], row[6], row[3], row[5]]) + else: + try: + name = '%s S%02dE%02d' % (self.tvshownames[int(row[0])], int(row[1]), int(row[2])) + except BaseException: + name = 'tvdb-id %d S%02dE%02d' % (int(row[0]), int(row[1]), int(row[2])) + sql = QUERY_EP_INSERT_SQLITE # idShow,season,episode,playCount,lastChange,lastPlayed + values = list([row[0], row[1], row[2], row[4], row[6], row[3]]) + self.sqlcursor_db.execute(sql, values) + + # check if update is canceled DIALOG_PROGRESS.close() + if utils.getSetting("progressdialog") == 'true' and DIALOG_PROGRESS.iscanceled(): + return 2 + if utils.getSetting("progressdialog") == 'true': + DIALOG_PROGRESS.update(int(100 * (i + 1) / list_length), (utils.getString(32716)+"\n"+utils.getString(32610) % (i + 1, list_length, name))) + utils.showNotification(utils.getString(strno), (utils.getString(32717)) % list_length, xbmc.LOGINFO) + if utils.getSetting("progressdialog") == 'true': + DIALOG_PROGRESS.close() + if self.monitor.abortRequested(): + return 4 # no further database operations + except sqlite3.Error as err: + try: + errstring = err.args[0] # TODO: Find out, why this does not work some times + except BaseException: + errstring = '' + utils.log(u'merge_local_dropbox: SQLite Database error accessing the wl database: ''%s''' % errstring, xbmc.LOGERROR) + self.close_db(3) + # error could be that the database is locked (for tv show strings). + if utils.getSetting("progressdialog") == 'true': + DIALOG_PROGRESS.close() + return 1 + except SystemExit: + return 4 + except BaseException: + utils.log(u'merge_local_dropbox: Error getting the wl database: ''%s''' % sys.exc_info()[2], xbmc.LOGERROR) + self.close_db(3) + buggalo.onExceptionRaised() + if utils.getSetting("progressdialog") == 'true': + DIALOG_PROGRESS.close() + return 1 + # only commit the changes if no error occured above (to ensure database persistence) + self.sqlcon_db.commit() + self.close_db(2) # close dropbox database + return 0 + + def pushToDropbox(self): + dropbox_key = utils.getSetting('dropbox_apikey') + + #utils.showNotification(utils.getString(32204), utils.getString(32302)%(count_update)) + # feign success if there is no local dropbox database file + if not (self.dropbox_path and dropbox_key): + return + + dest_file = '/' + 'watchedlist.db' + old_file = '/old' + 'watchedlist.db' + + client = dropbox.Dropbox(dropbox_key) + + # delete the old watched list. Failure here doesn't really matter + try: + client.files_delete(old_file) + except BaseException: + utils.log(u'Dropbox error: Unable to delete previous old watched list (%s)' % old_file) + + # rename the previously uploaded watchlist to "oldWHATEVER" + try: + client.files_move_v2(dest_file, old_file) + except BaseException: + utils.log(u'Dropbox error: Unable rename previous watched list') + + f = open(self.dropbox_path, 'rb') + try: + client.files_upload(f.read(), dest_file) + except DropboxApiError as err: + utils.log(u'Dropbox upload error: ' + str(err)) + utils.showNotification(utils.getString(32708), utils.getString(32709), xbmc.LOGERROR) + return + finally: + f.close() + utils.showNotification(utils.getString(32713), utils.getString(32714), xbmc.LOGINFO) + utils.log(u'Dropbox upload complete: %s -> %s' % (self.dropbox_path, dest_file)) + + def pullFromDropbox(self): + """ + Downloads the dropbox database + + Returns: + return code: + 0 successfully downloaded databases + 1 database download error + """ + dropbox_key = utils.getSetting('dropbox_apikey') + + if not dropbox_key: + # no dropbox authorization key entered. Feature does not work. + utils.showNotification(utils.getString(32708), utils.getString(32715), xbmc.LOGWARNING) + return 0 + + utils.log(u'Downloading WatchedList from dropbox') + + client = dropbox.Dropbox(dropbox_key) + + # save the dropbox database file in the user data directory (this is only a temporary file for upload and download) + self.dropbox_path = os.path.join(utils.data_dir(), "dropbox.db") + dropbox_file_exists = False + + remote_file = '/' + 'watchedlist.db' + old_file = '/old' + 'watchedlist.db' + # first: Try downloading the database file (if existent). + # if that fails, try restoring the backup file (if existent). + # if that also fails, the database will be rewritten (in other function) + try: + trycount = 0 + while trycount <= 4: # two tries for db file (trycount 1, 2), then try copying backup and download that (trycount 3,4) + if self.monitor.abortRequested(): + break + trycount = trycount + 1 + try: + client.files_download_to_file(self.dropbox_path, remote_file) + dropbox_file_exists = True + break + except DropboxApiError as err: + # file not available, e.g. deleted or first execution. + utils.log(u'Dropbox database download failed. %s.' % str(err)) + time.sleep(0.5) # wait to avoid immediate re-try + if err[1].is_path() and isinstance(err[1].get_path(), dropbox.files.LookupError): + # Error reason: file does not exist + trycount = trycount + 1 # do not try second time on downloading non-existing file + if trycount == 2 and not dropbox_file_exists: + try: + # No file was downloaded after second try. That means the dropbox file does not exist + # Try restoring the backup file, if existent + client.files_copy(old_file, remote_file) + except DropboxApiError as err: # files_copy raises RelocationError + # file not available, e.g. deleted or not existing + utils.log(u'Dropbox restore database backup failed. %s.' % str(err)) + break + except BaseException: # catch this error, the dropbox mode will be disabled + utils.log(u'Dropbox download error: ' + str(sys.exc_info())) + utils.showNotification(utils.getString(32708), utils.getString(32710), xbmc.LOGERROR) + self.dropbox_path = '' + return 1 + # check if file was written + if dropbox_file_exists: + utils.log(u'Dropbox database downloaded: %s -> %s' % (remote_file, self.dropbox_path)) + else: + utils.log(u'Dropbox database download failed. No remote file available.') + return 0 + + def get_movie_status(self, imdbId): + """ + Return the watched state of one movie from the internal WL database copy + requires this class to have a loaded database + + Args: + imdbId (Integer) + + Returns: + List with [Playcount, lastPlayed (integer timestamp), lastChange (integer timestamp)] + if no entry is available, playcount is -1 + """ + j = [ii for ii, x in enumerate(self.watchedmovielist_wl) if x[0] == imdbId] + if not j: + return [-1, 0, 0] + return [self.watchedmovielist_wl[j[0]][x] for x in [4, 3, 6]] # return 4playCount, 3lastPlayed, 6lastChange + + def get_episode_status(self, tvdbId, season, episode): + """ + Return the watched state of one tv series episode from the internal WL database copy + requires this class to have a loaded database + + Args: + tvdbId, season, episode (Integer) + + Returns: + List with [Playcount, lastPlayed (integer timestamp), lastChange (integer timestamp)] + if no entry is available, playcount is -1 + """ + j = [ii for ii, x in enumerate(self.watchedepisodelist_wl) if x[0] == tvdbId and x[1] == season and x[2] == episode] + if not j: + return [-1, 0, 0] + return [self.watchedepisodelist_wl[j[0]][x] for x in [4, 3, 6]] # return 4playCount, 3lastPlayed, 6lastChange diff --git a/service.watchedlist/manual.py b/service.watchedlist/manual.py new file mode 100644 index 0000000000..1a18e3a64f --- /dev/null +++ b/service.watchedlist/manual.py @@ -0,0 +1,34 @@ +""" +This file is entry point for manual start via the programs menu +""" +import sys + +import xbmc +import xbmcgui + +import lib.watchedlist.utils as utils +from lib.watchedlist.watchedlist import WatchedList + + +__remotedebug__ = False +# append pydev remote debugger +if __remotedebug__: + utils.log("Initialize remote debugging.") + # Make pydev debugger works for auto reload. + try: + import pydevd + pydevd.settrace('localhost', port=60678, stdoutToServer=True, stderrToServer=True) + except ImportError: + sys.stderr.write("Error: " + + "You must add org.python.pydev.debug.pysrc to your PYTHONPATH.") + utils.showNotification('WatchedList Error', 'remote debug could not be imported.', xbmc.LOGFATAL) + sys.exit(1) + except BaseException: + utils.showNotification('WatchedList Error', 'remote debug in pydev is activated, but remote server not responding.', xbmc.LOGERROR) + sys.exit(1) + +if (not utils.getSetting("autostart") == 'true') or xbmcgui.Dialog().yesno(utils.getString(32101), utils.getString(32001)): + # Check if we should run updates (only ask if autostart is on) + # run the program + utils.log("Update Library Manual Run.") + WatchedList().runUpdate(True) # one time update diff --git a/service.watchedlist/resources/language/resource.language.de_de/strings.po b/service.watchedlist/resources/language/resource.language.de_de/strings.po new file mode 100644 index 0000000000..3eeb7c43b4 --- /dev/null +++ b/service.watchedlist/resources/language/resource.language.de_de/strings.po @@ -0,0 +1,389 @@ +# Kodi Media Center language file +# Addon Name: WatchedList +# Addon id: service.watchedlist +# Addon Provider: schapplm +msgid "" +msgstr "" +"Project-Id-Version: XBMC-Addons\n" +"Report-Msgid-Bugs-To: alanwww1@xbmc.org\n" +"POT-Creation-Date: 2016-03-28 16:47+0000\n" +"PO-Revision-Date: 2017-12-30 10:56+0100\n" +"Last-Translator: schapplm\n" +"Language-Team: schapplm\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: de_DE\n" +"Plural-Forms: nplurals=2; plural=(n != 1)\n" + +msgctxt "Addon Summary" +msgid "Save watched Movies and TV Episodes independent from filenames" +msgstr "Gesehen-Status von Filmen und Serien-Episoden unabhängig von Dateinamen speichern" + +msgctxt "Addon Description" +msgid "Export: Searches the Kodi-Database for watched files. Determine imdb-id and thetvdb-id to identify movies and TV-episodes. Then save the list to a new independent table.\nImport: Set the watched state for each video file in Kodi.\nAutomatic background process without user interaction." +msgstr "Export: Durchsucht die Kodi-Datenbank nach gesehenen Filmen und ordnet den Dateien die eindeutigen Kennnummern von imdb und TheTVDB zu. Gesehene Filme und Episoden werden jeweils in einer eigenen Datenbank gespeichert.\nImport: Der Gesehen-Status von Medien in Kodi wird aus der Gesehenen-Tabelle geholt.\nDie Synchronisierung geschieht automatisch im Hintergrund ohne Benutzereingriff." + +msgctxt "Addon Disclaimer" +msgid "This script does not regard the file format. A Movie watched in DVD quality will also set the 1080p version as watched." +msgstr "Dieses Script ignoriert das Dateiformat. Ein gesehener Film in DVD-Qualität wird auch in der BlueRay-Version als gesehen gekennzeichnet." + +msgctxt "#30001" +msgid "Basic Settings" +msgstr "Grundeinstellungen" + +msgctxt "#30002" +msgid "Database" +msgstr "Datenbank" + +msgctxt "#30011" +msgid "Update movies watched state" +msgstr "Aktualisiere Gesehen-Status von Filmen" + +msgctxt "#30012" +msgid "Update episodes watched state" +msgstr "Aktualisiere Gesehen-Status von Episoden" + +msgctxt "#30013" +msgid "autostart mode" +msgstr "Starttyp" + +msgctxt "#30014" +msgid "Update interval [hours]" +msgstr "Aktualisierungs-Intervall [Stunden]" + +msgctxt "#30015" +msgid "Startup delay before action [minutes]" +msgstr "Start-Verzögerung [Minuten]" + +msgctxt "#30016" +msgid "Progress Dialog" +msgstr "Fortschrittsanzeige" + +msgctxt "#30017" +msgid "Use non-default database file" +msgstr "Eigene Datenbank-Datei" + +msgctxt "#30018" +msgid "Path to database file" +msgstr "Pfad zur Datenbank-Datei" + +msgctxt "#30019" +msgid "Database filename (SQLite Database, *.db)" +msgstr "Dateiname (*.db)" + +msgctxt "#30020" +msgid "Number of backup copies (-1=infinite)" +msgstr "Anzahl an Sicherungskopien (-1=unendlich)" + +msgctxt "#30021" +msgid "Start with Kodi (autorun)" +msgstr "Automatisch mit Kodi starten" + +msgctxt "#30022" +msgid "follow user setting watched/unwatched" +msgstr "Gesehen-Änderungen laufend überwachen" + +msgctxt "#30023" +msgid "Dropbox Auth Code" +msgstr "Dropbox Autorisierungs-Code" + +msgctxt "#30024" +msgid "Amount of User Information" +msgstr "Grad der Benutzerinformation" + +msgctxt "#30025" +msgid "All" +msgstr "Alle" + +msgctxt "#30026" +msgid "Only Info" +msgstr "Nur Infos" + +msgctxt "#30027" +msgid "Only Warning" +msgstr "Nur Warnungen" + +msgctxt "#30028" +msgid "Only Error" +msgstr "Nur Fehler" + +msgctxt "#30029" +msgid "None" +msgstr "Keine" + +msgctxt "#30030" +msgid "no update" +msgstr "Keine Aktualisierung" + +msgctxt "#30031" +msgid "one update" +msgstr "Einmalig" + +msgctxt "#30032" +msgid "periodic" +msgstr "Periodisch" + +msgctxt "#30040" +msgid "DB Method" +msgstr "DB-Art" + +msgctxt "#30041" +msgid "File" +msgstr "Datei" + +msgctxt "#30042" +msgid "MySQL" +msgstr "MySQL" + +msgctxt "#30043" +msgid "Options for accessing SQLite-DB-File" +msgstr "Optionen für SQLite-Datei-Zugriff" + +msgctxt "#30044" +msgid "Options for accessing MySQL-Server" +msgstr "Optionen für MySQL-Server-Zugriff" + +msgctxt "#30045" +msgid "Dropbox synchronization" +msgstr "Dropbox-Synchronisierung" + +msgctxt "#30051" +msgid "MySQL Server" +msgstr "MySQL Server" + +msgctxt "#30052" +msgid "MySQL Database" +msgstr "MySQL Datenbank" + +msgctxt "#30053" +msgid "MySQL Username" +msgstr "MySQL Benutzername" + +msgctxt "#30054" +msgid "MySQL Password" +msgstr "MySQL Kennwort" + +msgctxt "#30055" +msgid "MySQL Port" +msgstr "MySQL Port" + +msgctxt "#32001" +msgid "manually run the database update again?" +msgstr "Datenbank-Aktualisierung nochmal starten?" + +msgctxt "#32002" +msgid "DB path does not exist: %s" +msgstr "DB-Pfad existiert nicht: %s" + +msgctxt "#32003" +msgid "next update in %d hours" +msgstr "Nächste Aktualisierung in %d Stunden" + +msgctxt "#32004" +msgid "begin update in %d minutes" +msgstr "Starte Aktualisierung in %d Minuten" + +msgctxt "#32005" +msgid "running observation of changes of watched states" +msgstr "laufende Überwachung von Änderungen des Gesehen-Status" + +msgctxt "#32101" +msgid "WatchedList" +msgstr "WatchedList" + +msgctxt "#32102" +msgid "Watchedlist: Error" +msgstr "WatchedList: Fehler" + +msgctxt "#32103" +msgid "Load watched states from addon-database..." +msgstr "Lade Gesehen-Status aus Gesehen-Datenbank..." + +msgctxt "#32104" +msgid "load watched states Kodi-database ..." +msgstr "Lade Gesehene-Status aus Kodi-Datenbank ..." + +msgctxt "#32105" +msgid "update the addon watched-database ..." +msgstr "Aktualisiere die Gesehen-Datenbank: ..." + +msgctxt "#32106" +msgid "update the Kodi-database ..." +msgstr "Aktualisiere die Kodi-Datenbank ..." + +msgctxt "#32107" +msgid "update complete." +msgstr "Aktualisierung abgeschlossen." + +msgctxt "#32108" +msgid "Watchedlist: MySQL Error (WL DB)" +msgstr "Watchedlist: MySQL Fehler (WL DB)" + +msgctxt "#32109" +msgid "Watchedlist: SQLite Error (WL DB)" +msgstr "Watchedlist: SQLite Fehler (WL DB)" + +msgctxt "#32202" +msgid "Addon movie database" +msgstr "Gesehen-Datenbank (Filme)" + +msgctxt "#32203" +msgid "Addon episode database" +msgstr "Gesehen-Datenbank (Episoden)" + +msgctxt "#32204" +msgid "Kodi-movie database" +msgstr "Kodi-Filmdatenbank" + +msgctxt "#32205" +msgid "Kodi-episode database" +msgstr "Kodi-Episodendatenbank" + +msgctxt "#32208" +msgid "Access Denied (username/password/rights)" +msgstr "Zugriff verweigert (Benutzername/Kennwort/Rechte)" + +msgctxt "#32209" +msgid "Database '%s' does not exist" +msgstr "Datenbank '%s' existiert nicht" + +msgctxt "#32210" +msgid "Access denied (user '%s', DB '%s')" +msgstr "Zugriff verweigert (Benutzer '%s', DB '%s')" + +msgctxt "#32297" +msgid "TV-Show \"%s\" (ID %d) has no tvdb-number. No processing with WL possible. Try rescraping." +msgstr "TV-Serie \"%s\" (ID %d) hat keine tvdb-Nummer. Keine Verarbeitung mit WL möglich." + +msgctxt "#32298" +msgid "%d movies and %d episodes read from WL." +msgstr "%d Filme, %d Episoden in WL." + +msgctxt "#32299" +msgid "%d movies and %d episodes read from Kodi-DB." +msgstr "%d Filme, %d Episoden in Kodi-DB." + +msgctxt "#32301" +msgid "%d watched new. %d updated" +msgstr "%d neu gesehen. %d aktualisiert." + +msgctxt "#32302" +msgid "%d movies marked as watched" +msgstr "%d Filme als gesehen markiert." + +msgctxt "#32303" +msgid "%d episodes marked as watched" +msgstr "%d Episoden als gesehen markiert." + +msgctxt "#32401" +msgid "Set as watched (Kodi-DB)" +msgstr "Als gesehen markiert (Kodi-DB)" + +msgctxt "#32402" +msgid "Remember as newly watched (WL-DB)" +msgstr "Merke als neu gesehen (WL-DB)" + +msgctxt "#32403" +msgid "Remember as watched (updated) (WL-DB)" +msgstr "Merke als gesehen (aktualisiert) (WL-DB)" + +msgctxt "#32404" +msgid "Set as not watched (Kodi-DB)" +msgstr "Als ungesehen markiert (Kodi-DB)" + +msgctxt "#32405" +msgid "Remember as not watched (WL-DB)" +msgstr "Merke als ungesehen (WL-DB)" + +msgctxt "#32601" +msgid "Error opening WL-database" +msgstr "Öffnen der Gesehen-Datenbank" + +msgctxt "#32602" +msgid "Error loading WL-database" +msgstr "Laden der Gesehen-Datenbank" + +msgctxt "#32603" +msgid "Error loading Kodi-database" +msgstr "Laden der Kodi-Datenbank" + +msgctxt "#32604" +msgid "Error updating WL database" +msgstr "Aktualisieren der Gesehen-Datenbank" + +msgctxt "#32605" +msgid "Error updating Kodi-database" +msgstr "Aktualisieren der Kodi-Datenbank" + +msgctxt "#32606" +msgid "Writing the WL-database file %s" +msgstr "Beim Schreiben der Gesehen-Datenbank %s" + +msgctxt "#32607" +msgid "Unable to merge dropbox data" +msgstr "Zusammenführung mit Dropbox" + +msgctxt "#32608" +msgid "Doing a database backup (%s)" +msgstr "Beim Sichern der Datenbank (%s)" + +msgctxt "#32610" +msgid "%d/%d: %s" +msgstr "%d/%d: %s" + +msgctxt "#32611" +msgid "%d/%d: %s S%02dE%02d" +msgstr "%d/%d: %s S%02dE%02d" + +msgctxt "#32708" +msgid "Dropbox Error" +msgstr "Dropbox Fehler" + +msgctxt "#32709" +msgid "Unable to upload" +msgstr "Hochladen nicht möglich" + +msgctxt "#32710" +msgid "Unable to download" +msgstr "Herunterladen nicht möglich" + +msgctxt "#32711" +msgid "WatchedList: Dropbox-Import (Movies)" +msgstr "WatchedList: Dropbox-Import (Filme)" + +msgctxt "#32712" +msgid "WatchedList: Dropbox-Import (Episodes)" +msgstr "WatchedList: Dropbox-Import (Episoden)" + +msgctxt "#32713" +msgid "Dropbox synchronization" +msgstr "Dropbox-Synchronisierung" + +msgctxt "#32714" +msgid "Upload successfull" +msgstr "Hochladen erfolgreich" + +msgctxt "#32715" +msgid "Empty authorization code in settings" +msgstr "Leerer Autorisierungscode in Einstellungen" + +msgctxt "#32716" +msgid "Update the Dropbox database: ..." +msgstr "Aktualisiere die Dropbox-Datenbank: ..." + +msgctxt "#32717" +msgid "Dropbox database updated: %d entries." +msgstr "Dropbox-Datenbank aktualisiert. %d Einträge." + +msgctxt "#32718" +msgid "WatchedList: Dropbox-Export (Movies)" +msgstr "WatchedList: Dropbox-Export (Filme)" + +msgctxt "#32719" +msgid "WatchedList: Dropbox-Export (Episodes)" +msgstr "WatchedList: Dropbox-Export (Episoden)" + +msgctxt "#32720" +msgid "Error importing python Dropbox API. Disable function." +msgstr "Fehler beim Laden der Dropbox API. Deaktiviere Funktion." diff --git a/service.watchedlist/resources/language/resource.language.en_gb/strings.po b/service.watchedlist/resources/language/resource.language.en_gb/strings.po new file mode 100644 index 0000000000..e64d9df329 --- /dev/null +++ b/service.watchedlist/resources/language/resource.language.en_gb/strings.po @@ -0,0 +1,419 @@ +# Kodi Media Center language file +# Addon Name: WatchedList +# Addon id: service.watchedlist +# Addon Provider: schapplm +msgid "" +msgstr "" +"Project-Id-Version: XBMC-Addons\n" +"Report-Msgid-Bugs-To: alanwww1@xbmc.org\n" +"POT-Creation-Date: 2016-03-28 16:47+0000\n" +"PO-Revision-Date: 2017-12-30 10:56+0100\n" +"Last-Translator: schapplm\n" +"Language-Team: schapplm\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: en_GB\n" +"Plural-Forms: nplurals=2; plural=(n != 1)\n" + +msgctxt "Addon Summary" +msgid "Save watched Movies and TV Episodes independent from filenames" +msgstr "" + +msgctxt "Addon Description" +msgid "Export: Searches the Kodi-Database for watched files. Determine imdb-id and thetvdb-id to identify movies and TV-episodes. Then save the list to a new independent table.\nImport: Set the watched state for each video file in Kodi.\nAutomatic background process without user interaction." +msgstr "" + +msgctxt "Addon Disclaimer" +msgid "This script does not regard the file format. A Movie watched in DVD quality will also set the 1080p version as watched." +msgstr "" + +# Notification headers + +msgctxt "#30001" +msgid "Basic Settings" +msgstr "" + +msgctxt "#30002" +msgid "Database" +msgstr "" + +msgctxt "#30011" +msgid "Update movies watched state" +msgstr "" + +msgctxt "#30012" +msgid "Update episodes watched state" +msgstr "" + +msgctxt "#30013" +msgid "autostart mode" +msgstr "" + +msgctxt "#30014" +msgid "Update interval [hours]" +msgstr "" + +msgctxt "#30015" +msgid "Startup delay before action [minutes]" +msgstr "" + +msgctxt "#30016" +msgid "Progress Dialog" +msgstr "" + +msgctxt "#30017" +msgid "Use non-default database file" +msgstr "" + +msgctxt "#30018" +msgid "Path to database file" +msgstr "" + +msgctxt "#30019" +msgid "Database filename (SQLite Database, *.db)" +msgstr "" + +msgctxt "#30020" +msgid "Number of backup copies (-1=infinite)" +msgstr "" + +msgctxt "#30021" +msgid "Start with Kodi (autorun)" +msgstr "" + +msgctxt "#30022" +msgid "follow user setting watched/unwatched" +msgstr "" + +msgctxt "#30023" +msgid "Dropbox Auth Code" +msgstr "" + +msgctxt "#30024" +msgid "Amount of User Information" +msgstr "" + +msgctxt "#30025" +msgid "All" +msgstr "" + +msgctxt "#30026" +msgid "Only Info" +msgstr "" + +msgctxt "#30027" +msgid "Only Warning" +msgstr "" + +msgctxt "#30028" +msgid "Only Error" +msgstr "" + +msgctxt "#30029" +msgid "None" +msgstr "" + +msgctxt "#30030" +msgid "no update" +msgstr "" + +msgctxt "#30031" +msgid "one update" +msgstr "" + +msgctxt "#30032" +msgid "periodic" +msgstr "" + +# empty strings from id 30033 to 30039 + +msgctxt "#30040" +msgid "DB Method" +msgstr "" + +msgctxt "#30041" +msgid "File" +msgstr "" + +msgctxt "#30042" +msgid "MySQL" +msgstr "" + +msgctxt "#30043" +msgid "Options for accessing SQLite-DB-File" +msgstr "" + +msgctxt "#30044" +msgid "Options for accessing MySQL-Server" +msgstr "" + +msgctxt "#30045" +msgid "Dropbox synchronization" +msgstr "" + +# empty strings from id 30046 to 30050 + +msgctxt "#30051" +msgid "MySQL Server" +msgstr "" + +msgctxt "#30052" +msgid "MySQL Database" +msgstr "" + +msgctxt "#30053" +msgid "MySQL Username" +msgstr "" + +msgctxt "#30054" +msgid "MySQL Password" +msgstr "" + +msgctxt "#30055" +msgid "MySQL Port" +msgstr "" + +# empty strings from id 30056 to 32000 + +msgctxt "#32001" +msgid "manually run the database update again?" +msgstr "" + +msgctxt "#32002" +msgid "DB path does not exist: %s" +msgstr "" + +msgctxt "#32003" +msgid "next update in %d hours" +msgstr "" + +msgctxt "#32004" +msgid "begin update in %d minutes" +msgstr "" + +msgctxt "#32005" +msgid "running observation of changes of watched states" +msgstr "" + +# empty strings from id 32006 to 32100 + +msgctxt "#32101" +msgid "WatchedList" +msgstr "" + +msgctxt "#32102" +msgid "Watchedlist: Error" +msgstr "" + +msgctxt "#32103" +msgid "Load watched states from addon-database..." +msgstr "" + +msgctxt "#32104" +msgid "load watched states Kodi-database ..." +msgstr "" + +msgctxt "#32105" +msgid "update the addon watched-database ..." +msgstr "" + +msgctxt "#32106" +msgid "update the Kodi-database ..." +msgstr "" + +msgctxt "#32107" +msgid "update complete." +msgstr "" + +msgctxt "#32108" +msgid "Watchedlist: MySQL Error (WL DB)" +msgstr "" + +msgctxt "#32109" +msgid "Watchedlist: SQLite Error (WL DB)" +msgstr "" + +# empty strings from id 32110 to 32201 + +msgctxt "#32202" +msgid "Addon movie database" +msgstr "" + +msgctxt "#32203" +msgid "Addon episode database" +msgstr "" + +msgctxt "#32204" +msgid "Kodi-movie database" +msgstr "" + +msgctxt "#32205" +msgid "Kodi-episode database" +msgstr "" + +# empty strings from id 32206 to 32207 + +msgctxt "#32208" +msgid "Access Denied (username/password/rights)" +msgstr "" + +msgctxt "#32209" +msgid "Database '%s' does not exist" +msgstr "" + +msgctxt "#32210" +msgid "Access denied (user '%s', DB '%s')" +msgstr "" + +# empty strings from id 32211 to 32296 + +msgctxt "#32297" +msgid "TV-Show \"%s\" (ID %d) has no tvdb-number. No processing with WL possible. Try rescraping." +msgstr "" + +msgctxt "#32298" +msgid "%d movies and %d episodes read from WL." +msgstr "" + +msgctxt "#32299" +msgid "%d movies and %d episodes read from Kodi-DB." +msgstr "" + +# empty string with id 32300 + +msgctxt "#32301" +msgid "%d watched new. %d updated" +msgstr "" + +msgctxt "#32302" +msgid "%d movies marked as watched" +msgstr "" + +msgctxt "#32303" +msgid "%d episodes marked as watched" +msgstr "" + +# Error Messages +# empty strings from id 32304 to 32400 + +msgctxt "#32401" +msgid "Set as watched (Kodi-DB)" +msgstr "" + +msgctxt "#32402" +msgid "Remember as newly watched (WL-DB)" +msgstr "" + +msgctxt "#32403" +msgid "Remember as watched (updated) (WL-DB)" +msgstr "" + +msgctxt "#32404" +msgid "Set as not watched (Kodi-DB)" +msgstr "" + +msgctxt "#32405" +msgid "Remember as not watched (WL-DB)" +msgstr "" + +# Notification text +# empty strings from id 32406 to 32600 + +msgctxt "#32601" +msgid "Error opening WL-database" +msgstr "" + +msgctxt "#32602" +msgid "Error loading WL-database" +msgstr "" + +msgctxt "#32603" +msgid "Error loading Kodi-database" +msgstr "" + +msgctxt "#32604" +msgid "Error updating WL database" +msgstr "" + +msgctxt "#32605" +msgid "Error updating Kodi-database" +msgstr "" + +msgctxt "#32606" +msgid "Writing the WL-database file %s" +msgstr "" + +msgctxt "#32607" +msgid "Unable to merge dropbox data" +msgstr "" + +msgctxt "#32608" +msgid "Doing a database backup (%s)" +msgstr "" + +# Progress Dialog +# empty string with id 32609 + +msgctxt "#32610" +msgid "%d/%d: %s" +msgstr "" + +msgctxt "#32611" +msgid "%d/%d: %s S%02dE%02d" +msgstr "" + +# Dropbox related messages +# empty strings from id 32612 to 32707 + +msgctxt "#32708" +msgid "Dropbox Error" +msgstr "" + +msgctxt "#32709" +msgid "Unable to upload" +msgstr "" + +msgctxt "#32710" +msgid "Unable to download" +msgstr "" + +msgctxt "#32711" +msgid "WatchedList: Dropbox-Import (Movies)" +msgstr "" + +msgctxt "#32712" +msgid "WatchedList: Dropbox-Import (Episodes)" +msgstr "" + +msgctxt "#32713" +msgid "Dropbox synchronization" +msgstr "" + +msgctxt "#32714" +msgid "Upload successfull" +msgstr "" + +msgctxt "#32715" +msgid "Empty authorization code in settings" +msgstr "" + +msgctxt "#32716" +msgid "Update the Dropbox database: ..." +msgstr "" + +msgctxt "#32717" +msgid "Dropbox database updated: %d entries." +msgstr "" + +msgctxt "#32718" +msgid "WatchedList: Dropbox-Export (Movies)" +msgstr "" + +msgctxt "#32719" +msgid "WatchedList: Dropbox-Export (Episodes)" +msgstr "" + +msgctxt "#32720" +msgid "Error importing python Dropbox API. Disable function." +msgstr "" diff --git a/service.watchedlist/resources/language/resource.language.he_il/strings.po b/service.watchedlist/resources/language/resource.language.he_il/strings.po new file mode 100644 index 0000000000..610f7762d5 --- /dev/null +++ b/service.watchedlist/resources/language/resource.language.he_il/strings.po @@ -0,0 +1,409 @@ +# Kodi Media Center language file +# Addon Name: WatchedList +# Addon id: service.watchedlist +# Addon Provider: schapplm +msgid "" +msgstr "" +"Project-Id-Version: XBMC-Addons\n" +"Report-Msgid-Bugs-To: alanwww1@xbmc.org\n" +"POT-Creation-Date: 2016-03-28 16:47+0000\n" +"PO-Revision-Date: 2017-10-09 11:16+0300\n" +"Last-Translator: A. Dambledore\n" +"Language-Team: Eng2Heb\n" +"Language: he_IL\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + + +msgctxt "Addon Summary" +msgid "Save watched Movies and TV Episodes independent from filenames" +msgstr "שומר מצב נצפה לסרטים ופרקים טלוויזיה עצמאית משמות קבצים" + +msgctxt "Addon Description" +msgid "" +"Export: Searches the Kodi-Database for watched files. Determine imdb-id and thetvdb-id to identify movies and TV-episodes. Then save the list to a new independent table.\n" +"Import: Set the watched state for each video file in Kodi.\n" +"Automatic background process without user interaction." +msgstr "" +"ייצוא: מחפש את מסד הנתונים של קודי עבור קבצים שנצפו. קבע את iddb-id ו- thetvdb-id כדי לזהות סרטים ופרטי טלוויזיה. לאחר מכן שמור את הרשימה בטבלה עצמאית חדשה.\n" +"ייבוא: הגדר את מצב נצפה עבור כל קובץ וידאו בקודי.\n" +"תהליך רקע אוטומטי ללא אינטראקציה עם המשתמש." + +msgctxt "Addon Disclaimer" +msgid "This script does not regard the file format. A Movie watched in DVD quality will also set\tthe 1080p version as watched." +msgstr "הסקריפט הזה אינו מתייחס לתבנית הקובץ. סרט שנצפה באיכות DVD, יקבע גם את גרסת 1080p כנצפה." + +# Notification headers +msgctxt "#30001" +msgid "Basic Settings" +msgstr "הגדרות בסיסיות" + +msgctxt "#30002" +msgid "Database" +msgstr "מסד נתונים" + +msgctxt "#30011" +msgid "Update movies watched state" +msgstr "עדכון מצב נצפה לסרטים" + +msgctxt "#30012" +msgid "Update episodes watched state" +msgstr "עדכון מצב נצפה לפרקים" + +msgctxt "#30013" +msgid "autostart mode" +msgstr "מצב אתחול אוטומטי" + +msgctxt "#30014" +msgid "Update interval [hours]" +msgstr "מרווח בין עדכונים (שעות)" + +msgctxt "#30015" +msgid "Startup delay before action [minutes]" +msgstr "השהיית הפעלה לפני פעולה [דקות]" + +msgctxt "#30016" +msgid "Progress Dialog" +msgstr "דיאלוג התקדמות" + +msgctxt "#30017" +msgid "Use non-default database file" +msgstr "השתמש בקובץ מסד נתונים שאינו ברירת מחדל" + +msgctxt "#30018" +msgid "Path to database file" +msgstr "הנתיב אל קובץ מסד הנתונים" + +msgctxt "#30019" +msgid "Database filename (SQLite Database, *.db)" +msgstr "שם הקובץ של מסד הנתונים (מסד הנתונים SQLite, * .db)" + +msgctxt "#30020" +msgid "Number of backup copies (-1=infinite)" +msgstr "מספר עותקי גיבוי (-1 = אינסופי)" + +msgctxt "#30021" +msgid "Start with Kodi (autorun)" +msgstr "להתחיל עם קודי (הפעלה אוטומטית)" + +msgctxt "#30022" +msgid "follow user setting watched/unwatched" +msgstr "עקוב אחר הגדרות המשתמש למצב נצפה או לא נצפה" + +msgctxt "#30023" +msgid "Dropbox Auth Code" +msgstr "קוד אימות בדרופבוקס" + +msgctxt "#30024" +msgid "Amount of User Information" +msgstr "כמות מידע משתמש" + +msgctxt "#30025" +msgid "All" +msgstr "הכול" + +msgctxt "#30026" +msgid "Only Info" +msgstr "רק מידע" + +msgctxt "#30027" +msgid "Only Warning" +msgstr "רק אזהרה" + +msgctxt "#30028" +msgid "Only Error" +msgstr "רק שגיאה" + +msgctxt "#30029" +msgid "None" +msgstr "ללא" + +msgctxt "#30030" +msgid "no update" +msgstr "אין עדכון" + +msgctxt "#30031" +msgid "one update" +msgstr "עדכון אחד" + +msgctxt "#30032" +msgid "periodic" +msgstr "תקופתיים" + +# empty strings from id 30033 to 30039 +msgctxt "#30040" +msgid "DB Method" +msgstr "שיטת DB" + +msgctxt "#30041" +msgid "File" +msgstr "קובץ" + +msgctxt "#30042" +msgid "MySQL" +msgstr "MySQL" + +msgctxt "#30043" +msgid "Options for accessing SQLite-DB-File" +msgstr "אפשרויות לגישה SQLite-DB-File" + +msgctxt "#30044" +msgid "Options for accessing MySQL-Server" +msgstr "אפשרויות לגישה שרת MySQL" + +msgctxt "#30045" +msgid "Dropbox synchronization" +msgstr "סנכרון דרופבוקס" + +# empty strings from id 30046 to 30050 +msgctxt "#30051" +msgid "MySQL Server" +msgstr "MySQL שרת" + +msgctxt "#30052" +msgid "MySQL Database" +msgstr "MySQL מסד הנתונים" + +msgctxt "#30053" +msgid "MySQL Username" +msgstr "MySQL שם המשתמש" + +msgctxt "#30054" +msgid "MySQL Password" +msgstr "MySQL סיסמה" + +msgctxt "#30055" +msgid "MySQL Port" +msgstr "MySQL פורט" + +# empty strings from id 30056 to 32000 +msgctxt "#32001" +msgid "manually run the database update again?" +msgstr "להפעיל באופן ידני את העדכון מסד הנתונים שוב?" + +msgctxt "#32002" +msgid "DB path does not exist: %s" +msgstr "לא קיים נתיב לבסיס הנתונים: %s" + +msgctxt "#32003" +msgid "next update in %d hours" +msgstr "העדכון הבא בעוד %d שעות" + +msgctxt "#32004" +msgid "begin update in %d minutes" +msgstr "העדכון הבא בעוד %d דקות" + +msgctxt "#32005" +msgid "running observation of changes of watched states" +msgstr "מריץ סריקה לשינויים במצב נצפה" + +# empty strings from id 32006 to 32100 +msgctxt "#32101" +msgid "WatchedList" +msgstr "רשימת נצפה" + +msgctxt "#32102" +msgid "Watchedlist: Error" +msgstr "רשימת נצפה: שגיאה" + +msgctxt "#32103" +msgid "Load watched states from addon-database..." +msgstr "טוען מצב נצפה מתוך מסד הנתונים של ההרחבה..." + +msgctxt "#32104" +msgid "load watched states Kodi-database ..." +msgstr "טוען מצב נצפה מתוך מסד הנתונים של קודי..." + +msgctxt "#32105" +msgid "update the addon watched-database ..." +msgstr "עדכון את מצב נצפה במסד הנתונים של ההרחבה..." + +msgctxt "#32106" +msgid "update the Kodi-database ..." +msgstr "עדכון את מסד הנתונים של קודי..." + +msgctxt "#32107" +msgid "update complete." +msgstr "העדכון הושלם..." + +msgctxt "#32108" +msgid "Watchedlist: MySQL Error (WL DB)" +msgstr "רשימת נצפה: שגיאה MySQL (WL DB)" + +msgctxt "#32109" +msgid "Watchedlist: SQLite Error (WL DB)" +msgstr "רשימת נצפה: שגיאה SQLite (WL DB)" + +# empty strings from id 32110 to 32201 +msgctxt "#32202" +msgid "Addon movie database" +msgstr "מסד נתוני סרטים של ההרחבה" + +msgctxt "#32203" +msgid "Addon episode database" +msgstr "מסד נתוני פרקים של ההרחבה" + +msgctxt "#32204" +msgid "Kodi-movie database" +msgstr "מסד נתוני סרטים של קודי" + +msgctxt "#32205" +msgid "Kodi-episode database" +msgstr "מסד נתוני פרקים של קודי" + +# empty strings from id 32206 to 32207 +msgctxt "#32208" +msgid "Access Denied (username/password/rights)" +msgstr "הגישה נדחתה (שם משתמש/סיסמה/זכויות)" + +msgctxt "#32209" +msgid "Database '%s' does not exist" +msgstr "מסד הנתונים '%s' אינו קיים" + +msgctxt "#32210" +msgid "Access denied (user '%s', DB '%s')" +msgstr "הגישה נדחתה (המשתמש '%s', DB '%s')" + +# empty strings from id 32211 to 32296 +msgctxt "#32297" +msgid "TV-Show \"%s\" (ID %d) has no tvdb-number. No processing with WL possible. Try rescraping." +msgstr "סדרות \"%s\" (מזהה %d) אין מספר-tvdb. אין אפשרות לעבד עם WL. נסה לבצע סקרייפינג מחדש." + +msgctxt "#32298" +msgid "%d movies and %d episodes read from WL." +msgstr "%d סרטים, פרקים %d נקראו מ-WL." + +msgctxt "#32299" +msgid "%d movies and %d episodes read from Kodi-DB." +msgstr "%d סרטים, פרקים %d נקראו ממסד הנתונים של קודי." + +# empty string with id 32300 +msgctxt "#32301" +msgid "%d watched new. %d updated" +msgstr "%d מצב נצפה חדש. %d עודכן" + +msgctxt "#32302" +msgid "%d movies marked as watched" +msgstr "%d סרטים שסומנו כנצפה" + +msgctxt "#32303" +msgid "%d episodes marked as watched" +msgstr "%d פרקים שסומנו כנצפה" + +# Error Messages +# empty strings from id 32304 to 32400 +msgctxt "#32401" +msgid "Set as watched (Kodi-DB)" +msgstr "הגדר כנצפה (קודי-DB)" + +msgctxt "#32402" +msgid "Remember as newly watched (WL-DB)" +msgstr "זכור כנצפה לאחרונה (WL-DB)" + +msgctxt "#32403" +msgid "Remember as watched (updated) (WL-DB)" +msgstr "זכור כנצפה (מעודכן) (WL-DB)" + +msgctxt "#32404" +msgid "Set as not watched (Kodi-DB)" +msgstr "הגדר כלא נצפה (קודי-DB)" + +msgctxt "#32405" +msgid "Remember as not watched (WL-DB)" +msgstr "זכור כלא נצפה (WL-DB)" + +# Notification text +# empty strings from id 32406 to 32600 +msgctxt "#32601" +msgid "Error opening WL-database" +msgstr "שגיאה בפתיחת מסד הנתונים WL" + +msgctxt "#32602" +msgid "Error loading WL-database" +msgstr "שגיאה בטעינת מסד הנתונים WL" + +msgctxt "#32603" +msgid "Error loading Kodi-database" +msgstr "שגיאה בטעינת מסד הנתונים של קודי" + +msgctxt "#32604" +msgid "Error updating WL database" +msgstr "שגיאה בעת עדכון מסד נתונים WL" + +msgctxt "#32605" +msgid "Error updating Kodi-database" +msgstr "שגיאה בעת עדכון מסד נתונים קודי" + +msgctxt "#32606" +msgid "Writing the WL-database file %s" +msgstr "כתיבת קובץ WL-מסד הנתונים %s" + +msgctxt "#32607" +msgid "Unable to merge dropbox data" +msgstr "אין אפשרות למזג נתונים מדרופבוקס" + +# Progress Dialog +# empty string with id 32609 +msgctxt "#32610" +msgid "%d/%d: %s" +msgstr "% d/%d: %s" + +msgctxt "#32611" +msgid "%d/%d: %s S%02dE%02d" +msgstr "% d/%d: %s S % 02dE % 02d" + +# Dropbox related messages +# empty strings from id 32612 to 32707 +msgctxt "#32708" +msgid "Dropbox Error" +msgstr "שגיאה בדרופבוקס" + +msgctxt "#32709" +msgid "Unable to upload" +msgstr "לא מצליח להעלות" + +msgctxt "#32710" +msgid "Unable to download" +msgstr "לא מצליח להוריד" + +msgctxt "#32711" +msgid "WatchedList: Dropbox-Import (Movies)" +msgstr "דרופבוקס-ייבוא (סרטים)" + +msgctxt "#32712" +msgid "WatchedList: Dropbox-Import (Episodes)" +msgstr "דרופבוקס-ייבוא (פרקים)" + +msgctxt "#32713" +msgid "Dropbox synchronization" +msgstr "סנכרון דרופבוקס" + +msgctxt "#32714" +msgid "Upload successfull" +msgstr "העלאה הסתיימה בהצלחה" + +msgctxt "#32715" +msgid "Empty authorization code in settings" +msgstr "קוד אישור ריק בהגדרות" + +msgctxt "#32716" +msgid "Update the Dropbox database: ..." +msgstr "עדכן את מסד הנתונים של דרופבוקס:..." + +msgctxt "#32717" +msgid "Dropbox database updated: %d entries." +msgstr "דרופבוקס - עדכון מסד הנתונים: %d ערכים." + +msgctxt "#32718" +msgid "WatchedList: Dropbox-Export (Movies)" +msgstr "דרופבוקס-ייצוא (סרטים)" + +msgctxt "#32719" +msgid "WatchedList: Dropbox-Export (Episodes)" +msgstr "דרופבוקס-ייצוא (פרקים)" + +msgctxt "#32720" +msgid "Error importing python Dropbox API. Disable function." +msgstr "שגיאת ייבוא מפתח פיתון Dropbox API. בטל את הפונקציה." diff --git a/service.watchedlist/resources/settings.xml b/service.watchedlist/resources/settings.xml new file mode 100644 index 0000000000..3635d162f5 --- /dev/null +++ b/service.watchedlist/resources/settings.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +