From 48d555ac9831a70ba1ea4f49729b32513733a649 Mon Sep 17 00:00:00 2001 From: Attente <19653207+wikrin@users.noreply.github.com> Date: Fri, 6 Sep 2024 04:40:25 +0800 Subject: [PATCH 01/14] init commit --- .gitignore | 163 +++++++++++++ LICENSE | 674 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 837 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ae6c655 --- /dev/null +++ b/.gitignore @@ -0,0 +1,163 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +.idea/ +.vscode/ \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -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 +. From d961afb0101de010b7ffe4d32d02154751ed6464 Mon Sep 17 00:00:00 2001 From: Attente <19653207+wikrin@users.noreply.github.com> Date: Fri, 6 Sep 2024 04:45:56 +0800 Subject: [PATCH 02/14] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E6=8F=92=E4=BB=B6?= =?UTF-8?q?=EF=BC=9ABangumiColl?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- icons/bangumi_b.png | Bin 0 -> 4355 bytes package.json | 14 + plugins/bangumicoll/__init__.py | 505 ++++++++++++++++++++++++++++++++ 3 files changed, 519 insertions(+) create mode 100644 icons/bangumi_b.png create mode 100644 package.json create mode 100644 plugins/bangumicoll/__init__.py diff --git a/icons/bangumi_b.png b/icons/bangumi_b.png new file mode 100644 index 0000000000000000000000000000000000000000..29ea9b4e36fe30a046e0ea952c6d3ae2b69ab92c GIT binary patch literal 4355 zcmV+e5&Z6nP)Px_y-7qtRCr$PU2Sq3ISyqjRqM?u;@m?2);Wnso`WPlNNn#(;{4MsqB+Hkw<_u_ zN@}~^YLWm5QY8E7uRxG|;A;Z>06SCB@9*{F^~#uAWA@jbF+cyc{qw1!<}bFXFYCvz z#`J$20qCBtwwwD}!02jesBPyz>xUnmF*k2*?!MIoc1>7owe^4N?|<~BdmQQ8U2X3^ zYw1s|rz(QHtRMPwKtPhzgG8$TIOF%frsemh`|@$Sd6w$US*`(s9Hwo|BsoV7v99wO z|5)&9dsof4tEQnA*qP~iFx9R$-pK=L3w@%^)C20Sxdop%vGvdV<&v z_-2y5={B{jl$1T>>8*3QR>t&CSKB`~bWP<*Ry%`GW)hGj??8K5KiDPR>q)Iux>ilh zARtLz0{CikE$P;@=P}p6>Sqv;97l|Zh<69Jauo{*6&(1O%Q^+1(HOP#B~s{71yeHg1p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Z3F6u#NMs4GTFnFtq4xVe3_06DA#12Fk^keU z2?aoFD2iMvnN*npeeDe``=;uv%azGl-%wWw_r=d3moQ2xbU=tv3#K#&xuLT57w zfFRA75*SKS$@Tq9}sE%~Bl;P&Pq8l6k&3f?yWGxK4op zclBy$LvaK-HZ08xtSNwp&N>i~zP?*1K|qo^hFu-4l#;{tPJ6#w&b)Y*eY5PZF42GY0#1D8sM{ah*TY9e_Cv6aEq zVjC*B5#`f}j}ja2Pyx0*SOgi7#2!DvFMt4NDxa#t$4Gy8NoI34K`@ih4Mz z(J>}U?)IkJeB5rHiSn;vB7%S<6qxzJIb13Vu51~$TQ#mhOprH{s2mz&_qy}~+@)Q( zRO%L0IRqO;kfBS8rz_P_x{N~J>;acb+e&)ZC{zeCCdvo1zv&OBF1u^JQLy2WO73@zO5UrQ#mFW;7L| zN(g`;L?Hba#*VQA$E8C0RU+^g76U3?KKp+X?4F;Yyh=L#j xD_M7IZ@Syljmcea%&s%tGadmFfLVBv{{vxQ$bCF3@jd_m002ovPDHLkV1l6k&rARS literal 0 HcmV?d00001 diff --git a/package.json b/package.json new file mode 100644 index 0000000..384ccf0 --- /dev/null +++ b/package.json @@ -0,0 +1,14 @@ +{ + "BangumiColl": { + "name": "Bangumi收藏订阅", + "description": "Bangumi用户收藏添加到订阅", + "labels": "订阅", + "version": "1.0", + "icon": "https://raw.githubusercontent.com/wikrin/MoviePilot-Plugins/main/icons/bangumi_b.png", + "author": "Attente", + "level": 2, + "history": { + "v1.0": "将bangumi用户收藏添加到 MP 订阅,部分功能未实现" + } + }, +} diff --git a/plugins/bangumicoll/__init__.py b/plugins/bangumicoll/__init__.py new file mode 100644 index 0000000..7cb76b7 --- /dev/null +++ b/plugins/bangumicoll/__init__.py @@ -0,0 +1,505 @@ +import datetime + +from typing import Optional, Any, List, Dict + +import pytz +from apscheduler.schedulers.background import BackgroundScheduler + +from apscheduler.triggers.cron import CronTrigger + +from app.chain.subscribe import SubscribeChain +from app.core.config import settings + +from app.core.context import MediaInfo +from app.core.metainfo import MetaInfo +from app.log import logger +from app.plugins import _PluginBase +from app.db.site_oper import SiteOper +from app.utils.http import RequestUtils + + +class BangumiColl(_PluginBase): + # 插件名称 + plugin_name = "bangumi收藏订阅" + # 插件描述 + plugin_desc = "将bangumi用户收藏添加到订阅" + # 插件图标 + plugin_icon = "https://raw.githubusercontent.com/wikrin/MoviePilot-Plugins/main/icons/bangumi_b.png" + # 插件版本 + plugin_version = "1.0" + # 插件作者 + plugin_author = "Attente" + # 作者主页 + author_url = "https://github.com/wikrin" + # 插件配置项ID前缀 + plugin_config_prefix = "bangumicoll_" + # 加载顺序 + plugin_order = 23 + # 可使用的用户级别 + auth_level = 2 + + # 私有变量 + _scheduler: Optional[BackgroundScheduler] = None + siteoper: SiteOper = None + + # 配置属性 + _enabled: bool = False + _cron: str = "" + _notify: bool = False + _onlyonce: bool = False + _include: str = "" + _exclude: str = "" + _uid: str = "" + _collection_type = [] + _collection: Dict = {} + _save_path: str = "" + _sites: list = [] + + + def init_plugin(self, config: dict = None): + self.subscribechain = SubscribeChain() + self.siteoper = SiteOper() + + # 停止现有任务 + self.stop_service() + + # 配置 + if config: + self._enabled = config.get("enabled") + self._cron = config.get("cron") + self._notify = config.get("notify") + self._onlyonce = config.get("onlyonce") + self._include = config.get("include") + self._exclude = config.get("exclude") + self._uid = config.get("uid") + self._collection_type = config.get("collection_type") or [3] + self._collection = config.get("collection") + self._save_path = config.get("save_path") + self._sites = config.get("sites") + + if self._onlyonce: + self._scheduler = BackgroundScheduler(timezone=settings.TZ) + logger.info(f"bangumi收藏订阅启动,立即运行一次") + self._scheduler.add_job( + func=self.bangumi_coll, + trigger='date', + run_date=datetime.datetime.now(tz=pytz.timezone(settings.TZ)) + + datetime.timedelta(seconds=3), + ) + + # 启动任务 + if self._scheduler.get_jobs(): + self._scheduler.print_jobs() + self._scheduler.start() + + if self._onlyonce: + # 关闭一次性开关 + self._onlyonce = False + # 保存设置 + self.__update_config() + + def __update_config(self): + """ + 更新设置 + """ + self.update_config( + { + "enabled": self._enabled, + "notify": self._notify, + "onlyonce": self._onlyonce, + "cron": self._cron, + "uid": self._uid, + "collection_type": self._collection_type, + "collection": self._collection, + "include": self._include, + "exclude": self._exclude, + "save_path": self._save_path, + "sites": self._sites, + } + ) + + def get_api(self): + pass + + def get_command(self): + pass + + def get_form(self): + # 列出所有站点 + sites_options = [ + {"title": site.name, "value": site.id} + for site in self.siteoper.list_order_by_pri() + ] + + return [ + { + 'component': 'VForm', + 'content': [ + { + 'component': 'VRow', + 'content': [ + { + 'component': 'VCol', + 'props': {'cols': 12, 'md': 4}, + 'content': [ + { + 'component': 'VSwitch', + 'props': { + 'model': 'enabled', + 'label': '启用插件', + }, + } + ], + }, + { + 'component': 'VCol', + 'props': {'cols': 12, 'md': 4}, + 'content': [ + { + 'component': 'VSwitch', + 'props': { + 'model': 'notify', + 'label': '发送通知', + }, + } + ], + }, + { + 'component': 'VCol', + 'props': {'cols': 12, 'md': 4}, + 'content': [ + { + 'component': 'VSwitch', + 'props': { + 'model': 'onlyonce', + 'label': '立即运行一次', + }, + } + ], + }, + ], + }, + { + 'component': 'VRow', + 'content': [ + { + 'component': 'VCol', + 'props': {'cols': 12, 'md': 6}, + 'content': [ + { + 'component': 'VTextField', + 'props': { + 'model': 'cron', + 'label': '执行周期', + 'placeholder': '5位cron表达式,留空自动', + }, + } + ], + }, + ], + }, + { + 'component': 'VRow', + 'content': [ + { + 'component': 'VCol', + 'props': {'cols': 12, 'md': 6}, + 'content': [ + { + 'component': 'VTextField', + 'props': { + 'model': 'uid', + 'label': 'UID/用户名', + 'placeholder': '设置了用户名填写用户名,否则填写UID', + }, + }, + ], + }, + { + 'component': 'VCol', + 'props': {'cols': 12, 'md': 6}, + 'content': [ + { + 'component': 'VSelect', + 'props': { + 'model': 'collection_type', + 'label': '收藏类型', + 'chips': True, + 'multiple': True, + 'items': [ + {'title': '在看', 'value': 3}, + {'title': '想看', 'value': 1}, + ], + }, + } + ], + }, + ], + }, + { + 'component': 'VRow', + 'content': [ + { + 'component': 'VCol', + 'props': {'cols': 12, 'md': 6}, + 'content': [ + { + 'component': 'VTextField', + 'props': { + 'model': 'include', + 'label': '包含', + 'placeholder': '暂未实现', + }, + } + ], + }, + { + 'component': 'VCol', + 'props': {'cols': 12, 'md': 6}, + 'content': [ + { + 'component': 'VTextField', + 'props': { + 'model': 'exclude', + 'label': '排除', + 'placeholder': '暂未实现', + }, + } + ], + }, + ], + }, + { + 'component': 'VRow', + 'content': [ + { + 'component': 'VCol', + 'props': {'cols': 12, 'md': 6}, + 'content': [ + { + 'component': 'VTextField', + 'props': { + 'model': 'save_path', + 'label': '保存目录', + 'placeholder': '留空自动', + }, + } + ], + }, + { + 'component': 'VCol', + 'props': {'cols': 12, 'md': 6}, + 'content': [ + { + 'component': 'VSelect', + 'props': { + 'model': 'sites', + 'label': '选择站点', + 'chips': True, + 'multiple': True, + 'items': sites_options, + }, + } + ], + }, + ], + }, + ], + } + ], { + "enabled": False, + "notify": False, + "onlyonce": False, + "cron": "", + "uid": "", + "collection_type": [3], + "include": "", + "exclude": "", + "save_path": "", + "sites": [], + } + + def get_page(self): + pass + + # 注册定时任务 + def get_service(self) -> List[Dict[str, Any]]: + """ + 注册插件公共服务 + [{ + "id": "服务ID", + "name": "服务名称", + "trigger": "触发器:cron/interval/date/CronTrigger.from_crontab()", + "func": self.xxx, + "kwargs": {} # 定时器参数 + }] + """ + if self._enabled and self._cron: + return [ + { + "id": "BangumiColl", + "name": "Bangumi收藏订阅", + "trigger": CronTrigger.from_crontab(self._cron), + "func": self.bangumi_coll, + "kwargs": {}, + } + ] + elif self._enabled: + return [ + { + "id": "BangumiColl", + "name": "Bangumi收藏订阅", + "trigger": "interval", + "func": self.bangumi_coll, + "kwargs": {"hours": 6}, + } + ] + return [] + + def stop_service(self): + """ + 退出插件 + """ + try: + if self._scheduler: + self._scheduler.remove_all_jobs() + if self._scheduler.running: + self._scheduler.shutdown() + self._scheduler = None + except Exception as e: + logger.error("退出插件失败:%s" % str(e)) + + def get_state(self): + return self._enabled + + def bangumi_coll(self): + """ + 订阅bangumi用户收藏 + """ + if not self._uid: + logger.error("请设置UID") + return + + addr = f"https://api.bgm.tv/v0/users/{self._uid}/collections?subject_type=2" + headers = { + "User-Agent": "jxxghp/MoviePilot-Plugins (https://github.com/jxxghp/MoviePilot-Plugins)" + } + + try: + logger.info(f"查询bangumi条目信息:{addr} ...") + res = RequestUtils(headers=headers).get_res(url=addr) + res = res.json().get("data") + if not res: + logger.error(f"bangumi用户:{self._uid} ,未查询到数据") + except Exception as e: + logger.error(f"获取bangumi收藏数据失败:{addr} 失败:{str(e)}") + + # 解析出必要数据 + items: Dict[int, Dict[str, Any]] = {} + logger.info(f"解析bangumi条目信息...") + for item in res: + if item.get("type") not in self._collection_type: + continue + # 条目id + subject_id = item.get("subject_id") + # 主标题 + name = item['subject'].get('name') + # 中文标题 + name_cn = item['subject'].get('name_cn') + # 放送时间 + date = item['subject'].get('date') + ## 这里在后面添加排除规则 + items.update({subject_id: {"name": name, "name_cn": name_cn, "date": date}}) + ## 获取此插件添加的订阅 + db_sub = {i.bangumiid: i.id for i in self.subscribechain.subscribeoper.list() if i.bangumiid and i.username == "Bangumi订阅"} + # 新增条目 + new_sub = items.keys() - db_sub.keys() + # 移除条目, 这里暂时不做 + # del_sub = dbrid.keys() - items.keys() + logger.info(f"解析bangumi条目信息完成,共{len(items)}条,新增{len(new_sub)}条") + + # # 执行移除操作 + # if del_sub: + # del_items = {dbrid[i]: i for i in del_sub} + # logger.info(f"开始移除订阅...") + # self.delete_subscribe(del_items) + + # 执行添加操作 + if new_sub: + new_sub = {i: items[i] for i in new_sub} + logger.info(f"开始添加订阅...") + self.add_subscribe(new_sub) + + # 结束 + logger.info(f"bangumi收藏订阅执行完成") + + + + # 添加订阅 + def add_subscribe(self, items: Dict[int, Dict[str, Any]]): + for subject_id, item in items.items(): + meta = MetaInfo(item.get("name_cn")) + if not meta.name: + logger.warn(f"{item.get('name_cn')} 未识别到有效数据") + continue + # 由于bangumi的api不包含季度信息,不传入bangumi条目id,默认使用tmdb + mediainfo: MediaInfo = self.chain.recognize_media(meta=meta) + # 对比bangumi和tmdb的信息确定季度 + for info in mediainfo.season_info: + # 对比日期, 误差默认7天 + if not self.are_dates(item.get("date"), info.get("air_date")): + continue + else: + # 更新季度信息 + mediainfo.number_of_seasons = info.get("season_number") + # 更新集数信息 + mediainfo.number_of_episodes = info.get("episode_count") + + # 检查是否已经订阅 + subflag = self.subscribechain.exists(mediainfo=mediainfo, meta=meta) + if subflag: + logger.info(f'{mediainfo.title_year} {meta.season} 正在订阅中') + continue + + # 额外参数 + kwargs = { + "save_path": self._save_path, + "sites": self._sites, + } + # 添加到订阅 + self.subscribechain.add( + title=mediainfo.title, + year=mediainfo.year, + mtype=mediainfo.type, + tmdbid=mediainfo.tmdb_id, + bangumiid=subject_id, + season=mediainfo.number_of_seasons, + exist_ok=True, + username="Bangumi订阅", + **kwargs, + ) + + def delete_subscribe(self, del_items: dict): + pass + + @staticmethod + def are_dates(date_str1, date_str2, threshold_days: int = 7) -> bool: + """ + 对比两个日期字符串是否接近 + :param date_str1: 第一个日期字符串,格式为'YYYY-MM-DD' + :param date_str2: 第二个日期字符串,格式为'YYYY-MM-DD' + :param threshold_days: 阈值天数,默认为1天 + :return: 如果两个日期之间的差异小于等于阈值天数,则返回True,否则返回False + """ + # 将日期字符串转换为datetime对象 + date1 = datetime.datetime.strptime(date_str1, '%Y-%m-%d') + date2 = datetime.datetime.strptime(date_str2, '%Y-%m-%d') + + # 计算两个日期之间的差异 + delta = abs(date1 - date2) + + # 将阈值转换为timedelta对象 + threshold = datetime.timedelta(days=threshold_days) + + # 比较差异和阈值 + return delta <= threshold From 16984969e7544696b0a84122163dbd18ec9577b2 Mon Sep 17 00:00:00 2001 From: Attente <19653207+wikrin@users.noreply.github.com> Date: Fri, 6 Sep 2024 05:01:51 +0800 Subject: [PATCH 03/14] fix --- package.json | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/package.json b/package.json index 384ccf0..d81f56b 100644 --- a/package.json +++ b/package.json @@ -1,14 +1,14 @@ { - "BangumiColl": { - "name": "Bangumi收藏订阅", - "description": "Bangumi用户收藏添加到订阅", - "labels": "订阅", - "version": "1.0", - "icon": "https://raw.githubusercontent.com/wikrin/MoviePilot-Plugins/main/icons/bangumi_b.png", - "author": "Attente", - "level": 2, - "history": { - "v1.0": "将bangumi用户收藏添加到 MP 订阅,部分功能未实现" - } - }, + "BangumiColl": { + "name": "Bangumi收藏订阅", + "description": "Bangumi用户收藏添加到订阅", + "labels": "订阅", + "version": "1.0", + "icon": "https://raw.githubusercontent.com/wikrin/MoviePilot-Plugins/main/icons/bangumi_b.png", + "author": "Attente", + "level": 2, + "history": { + "v1.0": "将bangumi用户收藏添加到 MP 订阅,部分功能未实现" + } + } } From 842b5650debcbc5204632484220f828b093580e8 Mon Sep 17 00:00:00 2001 From: Attente <19653207+wikrin@users.noreply.github.com> Date: Fri, 6 Sep 2024 08:55:22 +0800 Subject: [PATCH 04/14] =?UTF-8?q?=E6=9B=B4=E6=94=B9=E5=9B=BE=E6=A0=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- icons/bangumi_b.png | Bin 4355 -> 5166 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/icons/bangumi_b.png b/icons/bangumi_b.png index 29ea9b4e36fe30a046e0ea952c6d3ae2b69ab92c..a6fffff4b55c59f02ca99699ee5fbfde0ee023b1 100644 GIT binary patch literal 5166 zcmcIoc{r5syB|!`n;98G*33+$Nn)~p31jR+_E3@~`h}ETFyKddgupU)G^w*|G{0(fm|ig92nYj?)@N1f16}zs7`XKHbo=T(S376(1tYfF zK%cc{pFZUmT}UD?tf{@+tZm$$MV~W9*UnURyX*Fy3x3xs@BCCjV35ohmaXl`D{?T| zBkPB<3yEowcv7y4{Ji1m;14t%VZ;;dN?nMIp(6A3V7m0gEL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Q2xbU=tv3#K#&xuLT57w zfFRA75*SKS$@Tq9}sE%~Bl;P&Pq8l6k&3f?yWGxK4op zclBy$LvaK-HZ08xtSNwp&N>i~zP?*1K|qo^hFu-4l#;{tPJ6#w&b)Y*eY5PZF42GY0#1D8sM{ah*TY9e_Cv6aEq zVjC*B5#`f}j}ja2Pyx0*SOgi7#2!DvFMt4NDxa#t$4Gy8NoI34K`@ih4Mz z(J>}U?)IkJeB5rHiSn;vB7%S<6qxzJIb13Vu51~$TQ#mhOprH{s2mz&_qy}~+@)Q( zRO%L0IRqO;kfBS8rz_P_x{N~J>;acb+e&)ZC{zeCCdvo1zv&OBF1u^JQLy2WO73@zO5UrQ#mFW;7L| zN(g`;L?Hba#*VQA$E8C0RU+^g76U3?KKp+X?4F;Yyh=L#j xD_M7IZ@Syljmcea%&s%tGadmFfLVBv{{vxQ$bCF3@jd_m002ovPDHLkV1l6k&rARS From 8eed22c8a744ddea67afbdcb946834fe4e58f56b Mon Sep 17 00:00:00 2001 From: Attente <19653207+wikrin@users.noreply.github.com> Date: Fri, 6 Sep 2024 09:19:52 +0800 Subject: [PATCH 05/14] =?UTF-8?q?=E7=BB=9F=E4=B8=80=E5=AD=97=E7=AC=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugins/bangumicoll/__init__.py | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/plugins/bangumicoll/__init__.py b/plugins/bangumicoll/__init__.py index 7cb76b7..b19b256 100644 --- a/plugins/bangumicoll/__init__.py +++ b/plugins/bangumicoll/__init__.py @@ -20,9 +20,9 @@ from app.utils.http import RequestUtils class BangumiColl(_PluginBase): # 插件名称 - plugin_name = "bangumi收藏订阅" + plugin_name = "Bangumi收藏订阅" # 插件描述 - plugin_desc = "将bangumi用户收藏添加到订阅" + plugin_desc = "将Bangumi用户收藏添加到订阅" # 插件图标 plugin_icon = "https://raw.githubusercontent.com/wikrin/MoviePilot-Plugins/main/icons/bangumi_b.png" # 插件版本 @@ -79,7 +79,7 @@ class BangumiColl(_PluginBase): if self._onlyonce: self._scheduler = BackgroundScheduler(timezone=settings.TZ) - logger.info(f"bangumi收藏订阅启动,立即运行一次") + logger.info(f"Bangumi收藏订阅启动,立即运行一次") self._scheduler.add_job( func=self.bangumi_coll, trigger='date', @@ -374,7 +374,7 @@ class BangumiColl(_PluginBase): def bangumi_coll(self): """ - 订阅bangumi用户收藏 + 订阅Bangumi用户收藏 """ if not self._uid: logger.error("请设置UID") @@ -390,13 +390,13 @@ class BangumiColl(_PluginBase): res = RequestUtils(headers=headers).get_res(url=addr) res = res.json().get("data") if not res: - logger.error(f"bangumi用户:{self._uid} ,未查询到数据") + logger.error(f"Bangumi用户:{self._uid} ,未查询到数据") except Exception as e: - logger.error(f"获取bangumi收藏数据失败:{addr} 失败:{str(e)}") + logger.error(f"获取Bangumi收藏数据失败:{addr} 失败:{str(e)}") # 解析出必要数据 items: Dict[int, Dict[str, Any]] = {} - logger.info(f"解析bangumi条目信息...") + logger.info(f"解析Bangumi条目信息...") for item in res: if item.get("type") not in self._collection_type: continue @@ -416,7 +416,7 @@ class BangumiColl(_PluginBase): new_sub = items.keys() - db_sub.keys() # 移除条目, 这里暂时不做 # del_sub = dbrid.keys() - items.keys() - logger.info(f"解析bangumi条目信息完成,共{len(items)}条,新增{len(new_sub)}条") + logger.info(f"解析Bangumi条目信息完成,共{len(items)}条,新增{len(new_sub)}条") # # 执行移除操作 # if del_sub: @@ -431,7 +431,7 @@ class BangumiColl(_PluginBase): self.add_subscribe(new_sub) # 结束 - logger.info(f"bangumi收藏订阅执行完成") + logger.info(f"Bangumi收藏订阅执行完成") @@ -442,9 +442,9 @@ class BangumiColl(_PluginBase): if not meta.name: logger.warn(f"{item.get('name_cn')} 未识别到有效数据") continue - # 由于bangumi的api不包含季度信息,不传入bangumi条目id,默认使用tmdb + # 由于Bangumi的api不包含季度信息,不传入Bangumi条目id,默认使用tmdb mediainfo: MediaInfo = self.chain.recognize_media(meta=meta) - # 对比bangumi和tmdb的信息确定季度 + # 对比Bangumi和tmdb的信息确定季度 for info in mediainfo.season_info: # 对比日期, 误差默认7天 if not self.are_dates(item.get("date"), info.get("air_date")): From fd44eb70b037aad4fa1f0e1c1a4bb8f1f25ba5f6 Mon Sep 17 00:00:00 2001 From: Attente <19653207+wikrin@users.noreply.github.com> Date: Mon, 9 Sep 2024 05:34:19 +0800 Subject: [PATCH 06/14] =?UTF-8?q?=E4=BF=AE=E6=94=B9:=20UA,=20=E9=94=99?= =?UTF-8?q?=E8=AF=AF=E5=AD=97=E7=AC=A6=20=E6=96=B0=E5=A2=9E:=20=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E5=8F=96=E6=B6=88=E8=AE=A2=E9=98=85=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 3 +- plugins/bangumicoll/__init__.py | 97 +++++++++++++++++++++++---------- 2 files changed, 71 insertions(+), 29 deletions(-) diff --git a/package.json b/package.json index d81f56b..9a6f9e7 100644 --- a/package.json +++ b/package.json @@ -3,11 +3,12 @@ "name": "Bangumi收藏订阅", "description": "Bangumi用户收藏添加到订阅", "labels": "订阅", - "version": "1.0", + "version": "1.1", "icon": "https://raw.githubusercontent.com/wikrin/MoviePilot-Plugins/main/icons/bangumi_b.png", "author": "Attente", "level": 2, "history": { + "v1.1": "新增根据收藏状态移除由此插件添加的订阅", "v1.0": "将bangumi用户收藏添加到 MP 订阅,部分功能未实现" } } diff --git a/plugins/bangumicoll/__init__.py b/plugins/bangumicoll/__init__.py index b19b256..52a0dbc 100644 --- a/plugins/bangumicoll/__init__.py +++ b/plugins/bangumicoll/__init__.py @@ -1,12 +1,9 @@ import datetime - from typing import Optional, Any, List, Dict - import pytz + from apscheduler.schedulers.background import BackgroundScheduler - from apscheduler.triggers.cron import CronTrigger - from app.chain.subscribe import SubscribeChain from app.core.config import settings @@ -16,6 +13,9 @@ from app.log import logger from app.plugins import _PluginBase from app.db.site_oper import SiteOper from app.utils.http import RequestUtils +from app.db.subscribe_oper import SubscribeOper +from app.helper.subscribe import SubscribeHelper +from app.schemas.types import NotificationType class BangumiColl(_PluginBase): @@ -26,7 +26,7 @@ class BangumiColl(_PluginBase): # 插件图标 plugin_icon = "https://raw.githubusercontent.com/wikrin/MoviePilot-Plugins/main/icons/bangumi_b.png" # 插件版本 - plugin_version = "1.0" + plugin_version = "1.1" # 插件作者 plugin_author = "Attente" # 作者主页 @@ -41,6 +41,8 @@ class BangumiColl(_PluginBase): # 私有变量 _scheduler: Optional[BackgroundScheduler] = None siteoper: SiteOper = None + subscribehelper: SubscribeHelper = None + subscribeoper: SubscribeOper = None # 配置属性 _enabled: bool = False @@ -51,14 +53,14 @@ class BangumiColl(_PluginBase): _exclude: str = "" _uid: str = "" _collection_type = [] - _collection: Dict = {} _save_path: str = "" _sites: list = [] - def init_plugin(self, config: dict = None): self.subscribechain = SubscribeChain() self.siteoper = SiteOper() + self.subscribehelper = SubscribeHelper() + self.subscribeoper = SubscribeOper() # 停止现有任务 self.stop_service() @@ -73,7 +75,6 @@ class BangumiColl(_PluginBase): self._exclude = config.get("exclude") self._uid = config.get("uid") self._collection_type = config.get("collection_type") or [3] - self._collection = config.get("collection") self._save_path = config.get("save_path") self._sites = config.get("sites") @@ -110,7 +111,6 @@ class BangumiColl(_PluginBase): "cron": self._cron, "uid": self._uid, "collection_type": self._collection_type, - "collection": self._collection, "include": self._include, "exclude": self._exclude, "save_path": self._save_path, @@ -159,7 +159,7 @@ class BangumiColl(_PluginBase): 'component': 'VSwitch', 'props': { 'model': 'notify', - 'label': '发送通知', + 'label': '自动取消订阅并通知', }, } ], @@ -323,6 +323,7 @@ class BangumiColl(_PluginBase): pass # 注册定时任务 + def get_service(self) -> List[Dict[str, Any]]: """ 注册插件公共服务 @@ -382,11 +383,11 @@ class BangumiColl(_PluginBase): addr = f"https://api.bgm.tv/v0/users/{self._uid}/collections?subject_type=2" headers = { - "User-Agent": "jxxghp/MoviePilot-Plugins (https://github.com/jxxghp/MoviePilot-Plugins)" + "User-Agent": "wikrin/MoviePilot-Plugins (https://github.com/wikrin/MoviePilot-Plugins)" } try: - logger.info(f"查询bangumi条目信息:{addr} ...") + logger.info(f"查询bangumi条目信息:{addr}") res = RequestUtils(headers=headers).get_res(url=addr) res = res.json().get("data") if not res: @@ -399,7 +400,11 @@ class BangumiColl(_PluginBase): logger.info(f"解析Bangumi条目信息...") for item in res: if item.get("type") not in self._collection_type: + logger.debug( + f"条目: {item['subject'].get('name_cn')} 类型:{item.get('type')} 不符合" + ) continue + # 条目id subject_id = item.get("subject_id") # 主标题 @@ -411,32 +416,44 @@ class BangumiColl(_PluginBase): ## 这里在后面添加排除规则 items.update({subject_id: {"name": name, "name_cn": name_cn, "date": date}}) ## 获取此插件添加的订阅 - db_sub = {i.bangumiid: i.id for i in self.subscribechain.subscribeoper.list() if i.bangumiid and i.username == "Bangumi订阅"} + db_sub = { + i.bangumiid: i.id + for i in self.subscribechain.subscribeoper.list() + if i.bangumiid and i.username == "Bangumi订阅" + } # 新增条目 new_sub = items.keys() - db_sub.keys() - # 移除条目, 这里暂时不做 - # del_sub = dbrid.keys() - items.keys() + logger.debug(f"待新增条目:{new_sub}") + # 移除条目 + del_sub = db_sub.keys() - items.keys() + logger.debug(f"待移除条目:{del_sub}") + logger.info(f"解析Bangumi条目信息完成,共{len(items)}条,新增{len(new_sub)}条") - # # 执行移除操作 - # if del_sub: - # del_items = {dbrid[i]: i for i in del_sub} - # logger.info(f"开始移除订阅...") - # self.delete_subscribe(del_items) - + # 执行移除操作 + if del_sub and self._notify: + # 数据库id为键,bgm条目id为值 + del_items = {db_sub[i]: i for i in del_sub} + logger.info(f"开始移除订阅...") + self.delete_subscribe(del_items) + # 执行添加操作 if new_sub: + # bgm条目id为键,bgm条目信息为值 new_sub = {i: items[i] for i in new_sub} logger.info(f"开始添加订阅...") self.add_subscribe(new_sub) - + # 结束 logger.info(f"Bangumi收藏订阅执行完成") - - # 添加订阅 + def add_subscribe(self, items: Dict[int, Dict[str, Any]]): + ''' + 添加订阅 + :param items: bgm条目id为键,bgm条目信息为值 + ''' for subject_id, item in items.items(): meta = MetaInfo(item.get("name_cn")) if not meta.name: @@ -478,9 +495,33 @@ class BangumiColl(_PluginBase): username="Bangumi订阅", **kwargs, ) - - def delete_subscribe(self, del_items: dict): - pass + + # 移除订阅 + + def delete_subscribe(self, del_items: Dict[int, int]): + ''' + 删除订阅 + :param del_items: 数据库id为键,bgm条目id为值 + ''' + args = [i for i in del_items.keys()] + for arg in args: + subscribe_id = int(arg) + subscribe = self.subscribeoper.get(subscribe_id) + if subscribe: + self.subscribeoper.delete(subscribe_id) + # 统计订阅 + self.subscribehelper.sub_done_async( + {"tmdbid": subscribe.tmdbid, "doubanid": subscribe.doubanid} + ) + # 发送通知 + self.post_message( + mtype=NotificationType.Subscribe, + title=f"{subscribe.name}({subscribe.year}) 第{subscribe.season}季 已取消订阅", + text="原因: 未在Bangumi收藏中找到该条目\n" + + f"订阅用户: {subscribe.username}\n" + + f"创建时间: {subscribe.date}", + image=subscribe.backdrop, + ) @staticmethod def are_dates(date_str1, date_str2, threshold_days: int = 7) -> bool: @@ -488,7 +529,7 @@ class BangumiColl(_PluginBase): 对比两个日期字符串是否接近 :param date_str1: 第一个日期字符串,格式为'YYYY-MM-DD' :param date_str2: 第二个日期字符串,格式为'YYYY-MM-DD' - :param threshold_days: 阈值天数,默认为1天 + :param threshold_days: 阈值天数,默认为7天 :return: 如果两个日期之间的差异小于等于阈值天数,则返回True,否则返回False """ # 将日期字符串转换为datetime对象 From eab8d9d4a76a39a8829203459d45a192bf5a28c0 Mon Sep 17 00:00:00 2001 From: Attente <19653207+wikrin@users.noreply.github.com> Date: Sat, 28 Sep 2024 00:16:57 +0800 Subject: [PATCH 07/14] =?UTF-8?q?fix:=20=E5=B7=B2=E5=AE=8C=E6=88=90?= =?UTF-8?q?=E8=AE=A2=E9=98=85=E8=A2=AB=E5=AE=9A=E6=97=B6=E4=BB=BB=E5=8A=A1?= =?UTF-8?q?=E9=87=8D=E5=A4=8D=E6=B7=BB=E5=8A=A0=E8=80=8C=E4=BA=92=E7=9B=B8?= =?UTF-8?q?=E8=A6=86=E7=9B=96=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 3 ++- plugins/bangumicoll/__init__.py | 23 ++++++++++++++++++----- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index 9a6f9e7..651a73d 100644 --- a/package.json +++ b/package.json @@ -3,11 +3,12 @@ "name": "Bangumi收藏订阅", "description": "Bangumi用户收藏添加到订阅", "labels": "订阅", - "version": "1.1", + "version": "1.2", "icon": "https://raw.githubusercontent.com/wikrin/MoviePilot-Plugins/main/icons/bangumi_b.png", "author": "Attente", "level": 2, "history": { + "v1.2": "修复已完成订阅条目重复添加的问题", "v1.1": "新增根据收藏状态移除由此插件添加的订阅", "v1.0": "将bangumi用户收藏添加到 MP 订阅,部分功能未实现" } diff --git a/plugins/bangumicoll/__init__.py b/plugins/bangumicoll/__init__.py index 52a0dbc..adddc34 100644 --- a/plugins/bangumicoll/__init__.py +++ b/plugins/bangumicoll/__init__.py @@ -16,6 +16,9 @@ from app.utils.http import RequestUtils from app.db.subscribe_oper import SubscribeOper from app.helper.subscribe import SubscribeHelper from app.schemas.types import NotificationType +from app.db import db_query +from app.db.models.subscribehistory import SubscribeHistory +from sqlalchemy.orm import Session class BangumiColl(_PluginBase): @@ -26,7 +29,7 @@ class BangumiColl(_PluginBase): # 插件图标 plugin_icon = "https://raw.githubusercontent.com/wikrin/MoviePilot-Plugins/main/icons/bangumi_b.png" # 插件版本 - plugin_version = "1.1" + plugin_version = "1.2" # 插件作者 plugin_author = "Attente" # 作者主页 @@ -421,8 +424,10 @@ class BangumiColl(_PluginBase): for i in self.subscribechain.subscribeoper.list() if i.bangumiid and i.username == "Bangumi订阅" } + ## 获取历史订阅 + db_hist = self.get_subscribe_history() # 新增条目 - new_sub = items.keys() - db_sub.keys() + new_sub = items.keys() - db_sub.keys() - db_hist logger.debug(f"待新增条目:{new_sub}") # 移除条目 del_sub = db_sub.keys() - items.keys() @@ -481,7 +486,7 @@ class BangumiColl(_PluginBase): # 额外参数 kwargs = { "save_path": self._save_path, - "sites": self._sites, + "sites": str(self._sites), } # 添加到订阅 self.subscribechain.add( @@ -527,8 +532,7 @@ class BangumiColl(_PluginBase): def are_dates(date_str1, date_str2, threshold_days: int = 7) -> bool: """ 对比两个日期字符串是否接近 - :param date_str1: 第一个日期字符串,格式为'YYYY-MM-DD' - :param date_str2: 第二个日期字符串,格式为'YYYY-MM-DD' + :param date_str: 日期字符串,格式为'YYYY-MM-DD' :param threshold_days: 阈值天数,默认为7天 :return: 如果两个日期之间的差异小于等于阈值天数,则返回True,否则返回False """ @@ -544,3 +548,12 @@ class BangumiColl(_PluginBase): # 比较差异和阈值 return delta <= threshold + + @db_query + def get_subscribe_history(self, db: Session = None) -> set: + ''' + 获取已完成的订阅 + ''' + result = db.query(SubscribeHistory).filter(SubscribeHistory.bangumiid != None).all() + return set([i.bangumiid for i in result]) + \ No newline at end of file From f140c1197abcb7ca5a29636615052382e8172d43 Mon Sep 17 00:00:00 2001 From: Attente <19653207+wikrin@users.noreply.github.com> Date: Wed, 9 Oct 2024 22:13:33 +0800 Subject: [PATCH 08/14] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8Dtmdbapi=E8=BF=94?= =?UTF-8?q?=E5=9B=9ENone=E5=AF=BC=E8=87=B4=E6=8F=92=E4=BB=B6=E5=B4=A9?= =?UTF-8?q?=E6=BA=83=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 3 ++- plugins/bangumicoll/__init__.py | 15 ++++++++++----- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index 651a73d..b648f0f 100644 --- a/package.json +++ b/package.json @@ -3,11 +3,12 @@ "name": "Bangumi收藏订阅", "description": "Bangumi用户收藏添加到订阅", "labels": "订阅", - "version": "1.2", + "version": "1.2.1", "icon": "https://raw.githubusercontent.com/wikrin/MoviePilot-Plugins/main/icons/bangumi_b.png", "author": "Attente", "level": 2, "history": { + "v1.2.1": "修复tmdb没有查询到条目导致插件崩溃的问题", "v1.2": "修复已完成订阅条目重复添加的问题", "v1.1": "新增根据收藏状态移除由此插件添加的订阅", "v1.0": "将bangumi用户收藏添加到 MP 订阅,部分功能未实现" diff --git a/plugins/bangumicoll/__init__.py b/plugins/bangumicoll/__init__.py index adddc34..01d48ca 100644 --- a/plugins/bangumicoll/__init__.py +++ b/plugins/bangumicoll/__init__.py @@ -29,7 +29,7 @@ class BangumiColl(_PluginBase): # 插件图标 plugin_icon = "https://raw.githubusercontent.com/wikrin/MoviePilot-Plugins/main/icons/bangumi_b.png" # 插件版本 - plugin_version = "1.2" + plugin_version = "1.2.1" # 插件作者 plugin_author = "Attente" # 作者主页 @@ -464,8 +464,12 @@ class BangumiColl(_PluginBase): if not meta.name: logger.warn(f"{item.get('name_cn')} 未识别到有效数据") continue - # 由于Bangumi的api不包含季度信息,不传入Bangumi条目id,默认使用tmdb + # 设置默认年份, 避免出现多个结果使用早期条目 + meta.year = item.get("date")[:4] mediainfo: MediaInfo = self.chain.recognize_media(meta=meta) + # 识别失败则跳过 + if not mediainfo: + continue # 对比Bangumi和tmdb的信息确定季度 for info in mediainfo.season_info: # 对比日期, 误差默认7天 @@ -548,12 +552,13 @@ class BangumiColl(_PluginBase): # 比较差异和阈值 return delta <= threshold - + @db_query def get_subscribe_history(self, db: Session = None) -> set: ''' 获取已完成的订阅 ''' - result = db.query(SubscribeHistory).filter(SubscribeHistory.bangumiid != None).all() + result = ( + db.query(SubscribeHistory).filter(SubscribeHistory.bangumiid != None).all() + ) return set([i.bangumiid for i in result]) - \ No newline at end of file From cdc1079af695bc9591182a0a353af1024de4e973 Mon Sep 17 00:00:00 2001 From: Attente <19653207+wikrin@users.noreply.github.com> Date: Fri, 11 Oct 2024 01:37:40 +0800 Subject: [PATCH 09/14] =?UTF-8?q?feat:=20=E8=AE=A2=E9=98=85=E5=A4=B1?= =?UTF-8?q?=E8=B4=A5=E7=9A=84=E6=9D=A1=E7=9B=AE=E6=B1=87=E6=80=BB=E8=BE=93?= =?UTF-8?q?=E5=87=BA=E5=88=B0=E6=97=A5=E5=BF=97=20feat:=20=E5=AF=B9?= =?UTF-8?q?=E5=B7=B2=E5=AD=98=E5=9C=A8=E7=9A=84=E6=9D=A1=E7=9B=AE=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0Bangumi=E6=9D=A1=E7=9B=AEID=20fix:=20=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D=E9=80=9A=E8=BF=87=E5=85=B6=E4=BB=96=E6=96=B9=E5=BC=8F?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=9A=84=E8=AE=A2=E9=98=85=E9=87=8D=E5=A4=8D?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 9 +++--- plugins/bangumicoll/__init__.py | 57 ++++++++++++++++++++++----------- 2 files changed, 43 insertions(+), 23 deletions(-) diff --git a/package.json b/package.json index b648f0f..07ae074 100644 --- a/package.json +++ b/package.json @@ -3,15 +3,14 @@ "name": "Bangumi收藏订阅", "description": "Bangumi用户收藏添加到订阅", "labels": "订阅", - "version": "1.2.1", + "version": "1.2.2", "icon": "https://raw.githubusercontent.com/wikrin/MoviePilot-Plugins/main/icons/bangumi_b.png", "author": "Attente", - "level": 2, + "level": 1, "history": { + "v1.2.2": "新增: 订阅添加失败总览 修复: 其他方式添加的订阅反复添加的问题", "v1.2.1": "修复tmdb没有查询到条目导致插件崩溃的问题", - "v1.2": "修复已完成订阅条目重复添加的问题", - "v1.1": "新增根据收藏状态移除由此插件添加的订阅", - "v1.0": "将bangumi用户收藏添加到 MP 订阅,部分功能未实现" + "v1.1": "新增根据收藏状态移除由此插件添加的订阅" } } } diff --git a/plugins/bangumicoll/__init__.py b/plugins/bangumicoll/__init__.py index 01d48ca..3f6d76a 100644 --- a/plugins/bangumicoll/__init__.py +++ b/plugins/bangumicoll/__init__.py @@ -29,7 +29,7 @@ class BangumiColl(_PluginBase): # 插件图标 plugin_icon = "https://raw.githubusercontent.com/wikrin/MoviePilot-Plugins/main/icons/bangumi_b.png" # 插件版本 - plugin_version = "1.2.1" + plugin_version = "1.2.2" # 插件作者 plugin_author = "Attente" # 作者主页 @@ -39,7 +39,7 @@ class BangumiColl(_PluginBase): # 加载顺序 plugin_order = 23 # 可使用的用户级别 - auth_level = 2 + auth_level = 1 # 私有变量 _scheduler: Optional[BackgroundScheduler] = None @@ -325,8 +325,7 @@ class BangumiColl(_PluginBase): def get_page(self): pass - # 注册定时任务 - + # 注册定时任务 def get_service(self) -> List[Dict[str, Any]]: """ 注册插件公共服务 @@ -418,11 +417,11 @@ class BangumiColl(_PluginBase): date = item['subject'].get('date') ## 这里在后面添加排除规则 items.update({subject_id: {"name": name, "name_cn": name_cn, "date": date}}) - ## 获取此插件添加的订阅 + ## 获取已添加的订阅 db_sub = { i.bangumiid: i.id for i in self.subscribechain.subscribeoper.list() - if i.bangumiid and i.username == "Bangumi订阅" + if i.bangumiid } ## 获取历史订阅 db_hist = self.get_subscribe_history() @@ -447,21 +446,28 @@ class BangumiColl(_PluginBase): # bgm条目id为键,bgm条目信息为值 new_sub = {i: items[i] for i in new_sub} logger.info(f"开始添加订阅...") - self.add_subscribe(new_sub) + msg = self.add_subscribe(new_sub) + if msg: + # 订阅失败的条目打印至日志 + logger.info("\n".ljust(49, ' ').join(list(msg.values()))) # 结束 logger.info(f"Bangumi收藏订阅执行完成") - # 添加订阅 - - def add_subscribe(self, items: Dict[int, Dict[str, Any]]): + # 添加订阅 + def add_subscribe(self, items: Dict[int, Dict[str, Any]]) -> Dict: ''' 添加订阅 :param items: bgm条目id为键,bgm条目信息为值 ''' + # 记录失败条目 + fail_items = {} for subject_id, item in items.items(): meta = MetaInfo(item.get("name_cn")) if not meta.name: + fail_items.update( + {subject_id: f"{item.get('name_cn')} 未识别到有效数据"} + ) logger.warn(f"{item.get('name_cn')} 未识别到有效数据") continue # 设置默认年份, 避免出现多个结果使用早期条目 @@ -469,6 +475,9 @@ class BangumiColl(_PluginBase): mediainfo: MediaInfo = self.chain.recognize_media(meta=meta) # 识别失败则跳过 if not mediainfo: + fail_items.update( + {subject_id: f"{item.get('name_cn')} 媒体信息识别失败"} + ) continue # 对比Bangumi和tmdb的信息确定季度 for info in mediainfo.season_info: @@ -481,19 +490,28 @@ class BangumiColl(_PluginBase): # 更新集数信息 mediainfo.number_of_episodes = info.get("episode_count") - # 检查是否已经订阅 - subflag = self.subscribechain.exists(mediainfo=mediainfo, meta=meta) - if subflag: - logger.info(f'{mediainfo.title_year} {meta.season} 正在订阅中') + # 检查是否已经订阅, 添加bangumiid + sid = self.subscribeoper.list_by_tmdbid( + mediainfo.tmdb_id, mediainfo.number_of_seasons + ) + if sid: + logger.info(f"{mediainfo.title_year} {meta.season} 正在订阅中") + if len(sid) == 1: + self.subscribeoper.update( + sid=sid[0].id, payload={"bangumiid": subject_id} + ) + logger.info( + f"{mediainfo.title_year} {meta.season} Bangumi条目id更新成功" + ) continue # 额外参数 kwargs = { "save_path": self._save_path, - "sites": str(self._sites), + "sites": self._sites, } # 添加到订阅 - self.subscribechain.add( + sid, msg = self.subscribechain.add( title=mediainfo.title, year=mediainfo.year, mtype=mediainfo.type, @@ -504,9 +522,12 @@ class BangumiColl(_PluginBase): username="Bangumi订阅", **kwargs, ) + if not sid: + fail_items.update({subject_id: f"{item.get('name_cn')} {msg}"}) + continue + return fail_items - # 移除订阅 - + # 移除订阅 def delete_subscribe(self, del_items: Dict[int, int]): ''' 删除订阅 From f4ba85aaa36850d8b8c61f5d78b9d9d1b313af92 Mon Sep 17 00:00:00 2001 From: Attente <19653207+wikrin@users.noreply.github.com> Date: Sat, 12 Oct 2024 03:40:14 +0800 Subject: [PATCH 10/14] =?UTF-8?q?feat:=20=E4=BC=98=E5=8C=96=E8=AE=A2?= =?UTF-8?q?=E9=98=85,=20=E5=BD=93=E4=BF=A1=E6=81=AF=E4=B8=8D=E4=B8=80?= =?UTF-8?q?=E8=87=B4=E4=BC=98=E5=85=88BGM?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 3 +- plugins/bangumicoll/__init__.py | 107 ++++++++++++++++++++++++++------ 2 files changed, 89 insertions(+), 21 deletions(-) diff --git a/package.json b/package.json index 07ae074..fae2e2c 100644 --- a/package.json +++ b/package.json @@ -3,11 +3,12 @@ "name": "Bangumi收藏订阅", "description": "Bangumi用户收藏添加到订阅", "labels": "订阅", - "version": "1.2.2", + "version": "1.3", "icon": "https://raw.githubusercontent.com/wikrin/MoviePilot-Plugins/main/icons/bangumi_b.png", "author": "Attente", "level": 1, "history": { + "v1.3": "添加订阅逻辑优化", "v1.2.2": "新增: 订阅添加失败总览 修复: 其他方式添加的订阅反复添加的问题", "v1.2.1": "修复tmdb没有查询到条目导致插件崩溃的问题", "v1.1": "新增根据收藏状态移除由此插件添加的订阅" diff --git a/plugins/bangumicoll/__init__.py b/plugins/bangumicoll/__init__.py index 3f6d76a..e09c33b 100644 --- a/plugins/bangumicoll/__init__.py +++ b/plugins/bangumicoll/__init__.py @@ -29,7 +29,7 @@ class BangumiColl(_PluginBase): # 插件图标 plugin_icon = "https://raw.githubusercontent.com/wikrin/MoviePilot-Plugins/main/icons/bangumi_b.png" # 插件版本 - plugin_version = "1.2.2" + plugin_version = "1.3" # 插件作者 plugin_author = "Attente" # 作者主页 @@ -383,19 +383,11 @@ class BangumiColl(_PluginBase): logger.error("请设置UID") return - addr = f"https://api.bgm.tv/v0/users/{self._uid}/collections?subject_type=2" - headers = { - "User-Agent": "wikrin/MoviePilot-Plugins (https://github.com/wikrin/MoviePilot-Plugins)" - } - - try: - logger.info(f"查询bangumi条目信息:{addr}") - res = RequestUtils(headers=headers).get_res(url=addr) - res = res.json().get("data") - if not res: - logger.error(f"Bangumi用户:{self._uid} ,未查询到数据") - except Exception as e: - logger.error(f"获取Bangumi收藏数据失败:{addr} 失败:{str(e)}") + # 获取收藏列表 + res = self.get_bgm_res(addr="UserCollections", id=self._uid) + res = res.json().get("data") + if not res: + logger.error(f"Bangumi用户:{self._uid} ,没有任何收藏") # 解析出必要数据 items: Dict[int, Dict[str, Any]] = {} @@ -415,8 +407,19 @@ class BangumiColl(_PluginBase): name_cn = item['subject'].get('name_cn') # 放送时间 date = item['subject'].get('date') + # 集数 + eps = item['subject'].get('eps') ## 这里在后面添加排除规则 - items.update({subject_id: {"name": name, "name_cn": name_cn, "date": date}}) + items.update( + { + subject_id: { + "name": name, + "name_cn": name_cn, + "date": date, + "eps": eps, + } + } + ) ## 获取已添加的订阅 db_sub = { i.bangumiid: i.id @@ -460,6 +463,7 @@ class BangumiColl(_PluginBase): 添加订阅 :param items: bgm条目id为键,bgm条目信息为值 ''' + # 记录失败条目 fail_items = {} for subject_id, item in items.items(): @@ -490,6 +494,63 @@ class BangumiColl(_PluginBase): # 更新集数信息 mediainfo.number_of_episodes = info.get("episode_count") + # 总集数 + total_episode = len( + mediainfo.seasons.get(mediainfo.number_of_seasons) or [] + ) + # 额外参数 + kwargs = { + "save_path": self._save_path, + "sites": self._sites, + "total_episode": total_episode, + } + + # 对比BGM 和 TMDB 季度和集数 + if ( + meta.begin_season + and mediainfo.number_of_seasons != meta.begin_season + or (item.get('eps') != 0 and total_episode != item.get('eps')) + or (item.get('eps') == 0 and not total_episode >= 12) + ): + ''' + 1. 标题识别到季度且与tmdb不一致 + 2. eps 字段为0且总集数小于12 + 3. eps 字段不为0且总集数与Bangumi集数不一致 + ''' + + def get_eps(id: str, addr: str = "getEpisodes") -> tuple: + """ + 获取Bangumi条目的集数信息 + :param id: bangumi条目id + :param addr: API地址 + """ + ep: int = 1 + sort: int = 1 + total: int = 24 + res = self.get_bgm_res(addr=addr, id=id) + res = res.json() + data = res.get("data") + if data: + # 当前季的集数 + ep = data[0].get("ep") + # 系列的累计集数 + sort = data[0].get("sort") + # 当前集的总集数 + total = res.get("total") + begin_ep = sort + total_ep = sort + total - ep + return begin_ep, total_ep + + if meta.begin_season: + # 使用标题识别到的季号 + mediainfo.number_of_seasons = meta.begin_season + + begin_ep, total_ep = get_eps(id=subject_id) + logger.info( + f"{mediainfo.title_year} 识别到Bangumi与TMDB的季数和集数不一致" + ) + kwargs.update({"start_episode": begin_ep, "total_episode": total_ep}) + # 检查是否已经订阅, 添加bangumiid sid = self.subscribeoper.list_by_tmdbid( mediainfo.tmdb_id, mediainfo.number_of_seasons @@ -505,11 +566,6 @@ class BangumiColl(_PluginBase): ) continue - # 额外参数 - kwargs = { - "save_path": self._save_path, - "sites": self._sites, - } # 添加到订阅 sid, msg = self.subscribechain.add( title=mediainfo.title, @@ -553,6 +609,17 @@ class BangumiColl(_PluginBase): image=subscribe.backdrop, ) + @staticmethod + def get_bgm_res(addr: str, id: int | str): + url = { + "UserCollections": f"https://api.bgm.tv/v0/users/{str(id)}/collections?subject_type=2", + "getEpisodes": f"https://api.bgm.tv/v0/episodes?subject_id={str(id)}&type=0&limit=1", + } + headers = { + "User-Agent": "wikrin/MoviePilot-Plugins (https://github.com/wikrin/MoviePilot-Plugins)" + } + return RequestUtils(headers=headers).get_res(url=url[addr]) + @staticmethod def are_dates(date_str1, date_str2, threshold_days: int = 7) -> bool: """ From 2d79912a963243df19288ef54dcdb7a3f872c714 Mon Sep 17 00:00:00 2001 From: Attente <19653207+wikrin@users.noreply.github.com> Date: Sat, 12 Oct 2024 23:24:35 +0800 Subject: [PATCH 11/14] =?UTF-8?q?frat:=20=E5=85=BC=E5=AE=B9V2=20fix:=20?= =?UTF-8?q?=E6=92=A4=E9=94=80=E5=AD=A3=E5=8F=B7=E8=B7=9F=E9=9A=8F=E5=89=A7?= =?UTF-8?q?=E9=9B=86=E6=A0=87=E9=A2=98,=20=E4=BC=9A=E5=AF=BC=E8=87=B4?= =?UTF-8?q?=E8=AE=A2=E9=98=85=E6=9C=AA=E4=B8=8B=E8=BD=BD=E5=AE=8C=E6=95=B4?= =?UTF-8?q?=E5=B0=B1=E5=AE=8C=E6=88=90=E8=AE=A2=E9=98=85=20other:=20?= =?UTF-8?q?=E5=8C=85=E5=AF=BC=E5=85=A5=E6=8E=92=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 7 +-- plugins/bangumicoll/__init__.py | 89 +++++++++++++++++++++++---------- 2 files changed, 67 insertions(+), 29 deletions(-) diff --git a/package.json b/package.json index fae2e2c..0c43c28 100644 --- a/package.json +++ b/package.json @@ -3,15 +3,16 @@ "name": "Bangumi收藏订阅", "description": "Bangumi用户收藏添加到订阅", "labels": "订阅", - "version": "1.3", + "version": "1.3.1", "icon": "https://raw.githubusercontent.com/wikrin/MoviePilot-Plugins/main/icons/bangumi_b.png", "author": "Attente", "level": 1, + "v2": true, "history": { + "v1.3.1": "修复因修改季号导致未下载剧集而完成订阅的问题", "v1.3": "添加订阅逻辑优化", "v1.2.2": "新增: 订阅添加失败总览 修复: 其他方式添加的订阅反复添加的问题", - "v1.2.1": "修复tmdb没有查询到条目导致插件崩溃的问题", - "v1.1": "新增根据收藏状态移除由此插件添加的订阅" + "v1.2.1": "修复tmdb没有查询到条目导致插件崩溃的问题" } } } diff --git a/plugins/bangumicoll/__init__.py b/plugins/bangumicoll/__init__.py index e09c33b..41009a1 100644 --- a/plugins/bangumicoll/__init__.py +++ b/plugins/bangumicoll/__init__.py @@ -1,23 +1,25 @@ import datetime -from typing import Optional, Any, List, Dict +import json import pytz +from typing import Any, Dict, List, Optional, Type + +from app.chain.subscribe import SubscribeChain, Subscribe +from app.core.config import settings +from app.core.context import MediaInfo +from app.core.metainfo import MetaInfo +from app.db.models.subscribehistory import SubscribeHistory +from app.db.site_oper import SiteOper +from app.db.subscribe_oper import SubscribeOper +from app.db import db_query +from app.helper.subscribe import SubscribeHelper +from app.log import logger +from app.plugins import _PluginBase +from app.schemas.types import NotificationType +from app.utils.http import RequestUtils from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.triggers.cron import CronTrigger -from app.chain.subscribe import SubscribeChain -from app.core.config import settings - -from app.core.context import MediaInfo -from app.core.metainfo import MetaInfo -from app.log import logger -from app.plugins import _PluginBase -from app.db.site_oper import SiteOper -from app.utils.http import RequestUtils -from app.db.subscribe_oper import SubscribeOper -from app.helper.subscribe import SubscribeHelper -from app.schemas.types import NotificationType -from app.db import db_query -from app.db.models.subscribehistory import SubscribeHistory +from sqlalchemy import JSON from sqlalchemy.orm import Session @@ -29,7 +31,7 @@ class BangumiColl(_PluginBase): # 插件图标 plugin_icon = "https://raw.githubusercontent.com/wikrin/MoviePilot-Plugins/main/icons/bangumi_b.png" # 插件版本 - plugin_version = "1.3" + plugin_version = "1.3.1" # 插件作者 plugin_author = "Attente" # 作者主页 @@ -466,6 +468,13 @@ class BangumiColl(_PluginBase): # 记录失败条目 fail_items = {} + # 格式化站点 + sites = ( + self._sites + if self.are_types_equal(attribute_name='sites') + else json.dumps(self._sites) + ) + for subject_id, item in items.items(): meta = MetaInfo(item.get("name_cn")) if not meta.name: @@ -501,7 +510,7 @@ class BangumiColl(_PluginBase): # 额外参数 kwargs = { "save_path": self._save_path, - "sites": self._sites, + "sites": sites, "total_episode": total_episode, } @@ -517,6 +526,7 @@ class BangumiColl(_PluginBase): 2. eps 字段为0且总集数小于12 3. eps 字段不为0且总集数与Bangumi集数不一致 ''' + logger.info(f"{mediainfo.title_year} 与Bangumi的集数不一致") def get_eps(id: str, addr: str = "getEpisodes") -> tuple: """ @@ -537,19 +547,29 @@ class BangumiColl(_PluginBase): sort = data[0].get("sort") # 当前集的总集数 total = res.get("total") - begin_ep = sort - total_ep = sort + total - ep + begin_ep = sort - ep + 1 + total_ep = sort - ep + total return begin_ep, total_ep - if meta.begin_season: - # 使用标题识别到的季号 - mediainfo.number_of_seasons = meta.begin_season - begin_ep, total_ep = get_eps(id=subject_id) - logger.info( - f"{mediainfo.title_year} 识别到Bangumi与TMDB的季数和集数不一致" + prev_eps = [i for i in range(1, begin_ep)] + # 更新参数 + note = ( + prev_eps + if self.are_types_equal(attribute_name='note') + else json.dumps(prev_eps) + ) + kwargs.update( + { + "total_episode": total_ep, # 总集数 + "start_episode": begin_ep, # 开始集数 + "lack_episode": total_ep - begin_ep + 1, # 缺失集数 + "note": note, # 忽略之前季度的集数 + } + ) + logger.info( + f"{mediainfo.title_year} 更新总集数为: {total_ep},开始集数为: {begin_ep}" ) - kwargs.update({"start_episode": begin_ep, "total_episode": total_ep}) # 检查是否已经订阅, 添加bangumiid sid = self.subscribeoper.list_by_tmdbid( @@ -650,3 +670,20 @@ class BangumiColl(_PluginBase): db.query(SubscribeHistory).filter(SubscribeHistory.bangumiid != None).all() ) return set([i.bangumiid for i in result]) + + @staticmethod + def are_types_equal( + attribute_name: str, expected_type: Type[Any] = JSON(), class_=Subscribe + ) -> bool: + """ + 比较类中属性的类型与expected_type是否一致 + :param class_: 类 + :param attribute_name: 属性名称 + :param expected_type: 期望的类型 + """ + column = class_.__table__.columns.get(attribute_name) + if column is None: + raise AttributeError( + f"Class: {class_.__name__} 没有属性: '{attribute_name}'" + ) + return isinstance(column.type, type(expected_type)) From b10cfe36a5c59a356f22ab54098632e81014e5f0 Mon Sep 17 00:00:00 2001 From: Attente <19653207+wikrin@users.noreply.github.com> Date: Sun, 13 Oct 2024 15:00:09 +0800 Subject: [PATCH 12/14] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E7=BB=93=E6=9E=84?= =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 3 +- plugins/bangumicoll/__init__.py | 482 +++++++++++++------------------- 2 files changed, 198 insertions(+), 287 deletions(-) diff --git a/package.json b/package.json index 0c43c28..2e84c46 100644 --- a/package.json +++ b/package.json @@ -3,12 +3,13 @@ "name": "Bangumi收藏订阅", "description": "Bangumi用户收藏添加到订阅", "labels": "订阅", - "version": "1.3.1", + "version": "1.4", "icon": "https://raw.githubusercontent.com/wikrin/MoviePilot-Plugins/main/icons/bangumi_b.png", "author": "Attente", "level": 1, "v2": true, "history": { + "v1.4": "结构优化", "v1.3.1": "修复因修改季号导致未下载剧集而完成订阅的问题", "v1.3": "添加订阅逻辑优化", "v1.2.2": "新增: 订阅添加失败总览 修复: 其他方式添加的订阅反复添加的问题", diff --git a/plugins/bangumicoll/__init__.py b/plugins/bangumicoll/__init__.py index 41009a1..21d071e 100644 --- a/plugins/bangumicoll/__init__.py +++ b/plugins/bangumicoll/__init__.py @@ -16,7 +16,6 @@ from app.log import logger from app.plugins import _PluginBase from app.schemas.types import NotificationType from app.utils.http import RequestUtils - from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.triggers.cron import CronTrigger from sqlalchemy import JSON @@ -31,7 +30,7 @@ class BangumiColl(_PluginBase): # 插件图标 plugin_icon = "https://raw.githubusercontent.com/wikrin/MoviePilot-Plugins/main/icons/bangumi_b.png" # 插件版本 - plugin_version = "1.3.1" + plugin_version = "1.4" # 插件作者 plugin_author = "Attente" # 作者主页 @@ -69,45 +68,43 @@ class BangumiColl(_PluginBase): # 停止现有任务 self.stop_service() + self.load_config(config) - # 配置 + if self._onlyonce: + self.schedule_once() + + def load_config(self, config: dict): + """加载配置""" if config: - self._enabled = config.get("enabled") - self._cron = config.get("cron") - self._notify = config.get("notify") - self._onlyonce = config.get("onlyonce") - self._include = config.get("include") - self._exclude = config.get("exclude") - self._uid = config.get("uid") - self._collection_type = config.get("collection_type") or [3] - self._save_path = config.get("save_path") - self._sites = config.get("sites") + self._enabled = config.get("enabled", self._enabled) + self._cron = config.get("cron", self._cron) + self._notify = config.get("notify", self._notify) + self._onlyonce = config.get("onlyonce", self._onlyonce) + self._include = config.get("include", self._include) + self._exclude = config.get("exclude", self._exclude) + self._uid = config.get("uid", self._uid) + self._collection_type = config.get("collection_type", [3]) + self._save_path = config.get("save_path", self._save_path) + self._sites = config.get("sites", self._sites) - if self._onlyonce: - self._scheduler = BackgroundScheduler(timezone=settings.TZ) - logger.info(f"Bangumi收藏订阅启动,立即运行一次") - self._scheduler.add_job( - func=self.bangumi_coll, - trigger='date', - run_date=datetime.datetime.now(tz=pytz.timezone(settings.TZ)) - + datetime.timedelta(seconds=3), - ) + def schedule_once(self): + """调度一次性任务""" + self._scheduler = BackgroundScheduler(timezone=settings.TZ) + logger.info("Bangumi收藏订阅,立即运行一次") + self._scheduler.add_job( + func=self.bangumi_coll, + trigger='date', + run_date=datetime.datetime.now(tz=pytz.timezone(settings.TZ)) + + datetime.timedelta(seconds=3), + ) + self._scheduler.start() - # 启动任务 - if self._scheduler.get_jobs(): - self._scheduler.print_jobs() - self._scheduler.start() - - if self._onlyonce: - # 关闭一次性开关 - self._onlyonce = False - # 保存设置 - self.__update_config() + # 关闭一次性开关 + self._onlyonce = False + self.__update_config() def __update_config(self): - """ - 更新设置 - """ + """更新设置""" self.update_config( { "enabled": self._enabled, @@ -123,12 +120,6 @@ class BangumiColl(_PluginBase): } ) - def get_api(self): - pass - - def get_command(self): - pass - def get_form(self): # 列出所有站点 sites_options = [ @@ -324,254 +315,129 @@ class BangumiColl(_PluginBase): "sites": [], } - def get_page(self): - pass - - # 注册定时任务 def get_service(self) -> List[Dict[str, Any]]: - """ - 注册插件公共服务 - [{ - "id": "服务ID", - "name": "服务名称", - "trigger": "触发器:cron/interval/date/CronTrigger.from_crontab()", - "func": self.xxx, - "kwargs": {} # 定时器参数 - }] - """ - if self._enabled and self._cron: + """注册插件公共服务""" + if self._enabled: + trigger = CronTrigger.from_crontab(self._cron) if self._cron else "interval" + kwargs = {"hours": 6} if not self._cron else {} return [ { "id": "BangumiColl", "name": "Bangumi收藏订阅", - "trigger": CronTrigger.from_crontab(self._cron), + "trigger": trigger, "func": self.bangumi_coll, - "kwargs": {}, - } - ] - elif self._enabled: - return [ - { - "id": "BangumiColl", - "name": "Bangumi收藏订阅", - "trigger": "interval", - "func": self.bangumi_coll, - "kwargs": {"hours": 6}, + "kwargs": kwargs, } ] return [] def stop_service(self): - """ - 退出插件 - """ + """退出插件""" try: if self._scheduler: self._scheduler.remove_all_jobs() - if self._scheduler.running: - self._scheduler.shutdown() + self._scheduler.shutdown() self._scheduler = None except Exception as e: - logger.error("退出插件失败:%s" % str(e)) + logger.error(f"退出插件失败:{str(e)}") + + def get_api(self): + pass + + def get_command(self): + pass + + def get_page(self): + pass def get_state(self): return self._enabled def bangumi_coll(self): - """ - 订阅Bangumi用户收藏 - """ + """订阅Bangumi用户收藏""" if not self._uid: logger.error("请设置UID") return - # 获取收藏列表 - res = self.get_bgm_res(addr="UserCollections", id=self._uid) - res = res.json().get("data") - if not res: - logger.error(f"Bangumi用户:{self._uid} ,没有任何收藏") + try: + res = self.get_bgm_res(addr="UserCollections", id=self._uid) + items = self.parse_collection_items(res) - # 解析出必要数据 - items: Dict[int, Dict[str, Any]] = {} - logger.info(f"解析Bangumi条目信息...") - for item in res: + # 新增和移除条目 + self.manage_subscriptions(items) + + logger.info("Bangumi收藏订阅执行完成") + except Exception as e: + logger.error(f"执行失败: {str(e)}") + + def parse_collection_items(self, response) -> Dict[int, Dict[str, Any]]: + """解析获取的收藏条目""" + data = response.json().get("data") + if not data: + logger.error(f"Bangumi用户:{self._uid} ,没有任何收藏") + return {} + + items = {} + logger.info("解析Bangumi条目信息...") + for item in data: if item.get("type") not in self._collection_type: logger.debug( f"条目: {item['subject'].get('name_cn')} 类型:{item.get('type')} 不符合" ) continue - # 条目id - subject_id = item.get("subject_id") - # 主标题 - name = item['subject'].get('name') - # 中文标题 - name_cn = item['subject'].get('name_cn') - # 放送时间 - date = item['subject'].get('date') - # 集数 - eps = item['subject'].get('eps') - ## 这里在后面添加排除规则 - items.update( - { - subject_id: { - "name": name, - "name_cn": name_cn, - "date": date, - "eps": eps, - } - } - ) - ## 获取已添加的订阅 + items[item.get("subject_id")] = { + "name": item['subject'].get('name'), + "name_cn": item['subject'].get('name_cn'), + "date": item['subject'].get('date'), + "eps": item['subject'].get('eps'), + } + return items + + def manage_subscriptions(self, items: Dict[int, Dict[str, Any]]): + """管理订阅的新增和删除""" db_sub = { i.bangumiid: i.id for i in self.subscribechain.subscribeoper.list() if i.bangumiid } - ## 获取历史订阅 db_hist = self.get_subscribe_history() - # 新增条目 new_sub = items.keys() - db_sub.keys() - db_hist - logger.debug(f"待新增条目:{new_sub}") - # 移除条目 del_sub = db_sub.keys() - items.keys() + + logger.debug(f"待新增条目:{new_sub}") logger.debug(f"待移除条目:{del_sub}") - logger.info(f"解析Bangumi条目信息完成,共{len(items)}条,新增{len(new_sub)}条") - - # 执行移除操作 if del_sub and self._notify: - # 数据库id为键,bgm条目id为值 del_items = {db_sub[i]: i for i in del_sub} - logger.info(f"开始移除订阅...") + logger.info("开始移除订阅...") self.delete_subscribe(del_items) - # 执行添加操作 if new_sub: - # bgm条目id为键,bgm条目信息为值 - new_sub = {i: items[i] for i in new_sub} - logger.info(f"开始添加订阅...") - msg = self.add_subscribe(new_sub) + logger.info("开始添加订阅...") + msg = self.add_subscribe({i: items[i] for i in new_sub}) if msg: - # 订阅失败的条目打印至日志 logger.info("\n".ljust(49, ' ').join(list(msg.values()))) - # 结束 - logger.info(f"Bangumi收藏订阅执行完成") - # 添加订阅 def add_subscribe(self, items: Dict[int, Dict[str, Any]]) -> Dict: - ''' - 添加订阅 - :param items: bgm条目id为键,bgm条目信息为值 - ''' - - # 记录失败条目 + """添加订阅""" fail_items = {} - # 格式化站点 - sites = ( - self._sites - if self.are_types_equal(attribute_name='sites') - else json.dumps(self._sites) - ) - - for subject_id, item in items.items(): + for self._subid, item in items.items(): meta = MetaInfo(item.get("name_cn")) if not meta.name: - fail_items.update( - {subject_id: f"{item.get('name_cn')} 未识别到有效数据"} - ) + fail_items[self._subid] = f"{item.get('name_cn')} 未识别到有效数据" logger.warn(f"{item.get('name_cn')} 未识别到有效数据") continue - # 设置默认年份, 避免出现多个结果使用早期条目 - meta.year = item.get("date")[:4] - mediainfo: MediaInfo = self.chain.recognize_media(meta=meta) - # 识别失败则跳过 + + meta.year = item.get("date")[:4] if item.get("date") else None + mediainfo = self.chain.recognize_media(meta=meta) if not mediainfo: - fail_items.update( - {subject_id: f"{item.get('name_cn')} 媒体信息识别失败"} - ) + fail_items[self._subid] = f"{item.get('name_cn')} 媒体信息识别失败" continue - # 对比Bangumi和tmdb的信息确定季度 - for info in mediainfo.season_info: - # 对比日期, 误差默认7天 - if not self.are_dates(item.get("date"), info.get("air_date")): - continue - else: - # 更新季度信息 - mediainfo.number_of_seasons = info.get("season_number") - # 更新集数信息 - mediainfo.number_of_episodes = info.get("episode_count") - # 总集数 - total_episode = len( - mediainfo.seasons.get(mediainfo.number_of_seasons) or [] - ) - # 额外参数 - kwargs = { - "save_path": self._save_path, - "sites": sites, - "total_episode": total_episode, - } + self.update_media_info(item, mediainfo) - # 对比BGM 和 TMDB 季度和集数 - if ( - meta.begin_season - and mediainfo.number_of_seasons != meta.begin_season - or (item.get('eps') != 0 and total_episode != item.get('eps')) - or (item.get('eps') == 0 and not total_episode >= 12) - ): - ''' - 1. 标题识别到季度且与tmdb不一致 - 2. eps 字段为0且总集数小于12 - 3. eps 字段不为0且总集数与Bangumi集数不一致 - ''' - logger.info(f"{mediainfo.title_year} 与Bangumi的集数不一致") - - def get_eps(id: str, addr: str = "getEpisodes") -> tuple: - """ - 获取Bangumi条目的集数信息 - :param id: bangumi条目id - :param addr: API地址 - """ - ep: int = 1 - sort: int = 1 - total: int = 24 - res = self.get_bgm_res(addr=addr, id=id) - res = res.json() - data = res.get("data") - if data: - # 当前季的集数 - ep = data[0].get("ep") - # 系列的累计集数 - sort = data[0].get("sort") - # 当前集的总集数 - total = res.get("total") - begin_ep = sort - ep + 1 - total_ep = sort - ep + total - return begin_ep, total_ep - - begin_ep, total_ep = get_eps(id=subject_id) - prev_eps = [i for i in range(1, begin_ep)] - # 更新参数 - note = ( - prev_eps - if self.are_types_equal(attribute_name='note') - else json.dumps(prev_eps) - ) - kwargs.update( - { - "total_episode": total_ep, # 总集数 - "start_episode": begin_ep, # 开始集数 - "lack_episode": total_ep - begin_ep + 1, # 缺失集数 - "note": note, # 忽略之前季度的集数 - } - ) - logger.info( - f"{mediainfo.title_year} 更新总集数为: {total_ep},开始集数为: {begin_ep}" - ) - - # 检查是否已经订阅, 添加bangumiid sid = self.subscribeoper.list_by_tmdbid( mediainfo.tmdb_id, mediainfo.number_of_seasons ) @@ -579,55 +445,114 @@ class BangumiColl(_PluginBase): logger.info(f"{mediainfo.title_year} {meta.season} 正在订阅中") if len(sid) == 1: self.subscribeoper.update( - sid=sid[0].id, payload={"bangumiid": subject_id} + sid=sid[0].id, payload={"bangumiid": self._subid} ) logger.info( f"{mediainfo.title_year} {meta.season} Bangumi条目id更新成功" ) continue - # 添加到订阅 sid, msg = self.subscribechain.add( title=mediainfo.title, year=mediainfo.year, mtype=mediainfo.type, tmdbid=mediainfo.tmdb_id, - bangumiid=subject_id, + bangumiid=self._subid, season=mediainfo.number_of_seasons, exist_ok=True, username="Bangumi订阅", - **kwargs, + **self.prepare_kwargs(item, meta.begin_season, mediainfo), ) if not sid: - fail_items.update({subject_id: f"{item.get('name_cn')} {msg}"}) - continue + fail_items[self._subid] = f"{item.get('name_cn')} {msg}" + return fail_items + def prepare_kwargs(self, item: dict, meta_season: int, mediainfo: MediaInfo): + """准备额外参数""" + kwargs = { + "save_path": self._save_path, + "sites": ( + self._sites + if self.are_types_equal(attribute_name='sites') + else json.dumps(self._sites) + ), + } + + if self.check_series_info(meta_season, item.get("eps", 0), mediainfo): + begin_ep, total_ep = self.get_eps() + prev_eps: list = [i for i in range(1, begin_ep)] + kwargs.update( + { + "total_episode": total_ep, + "start_episode": begin_ep, + "lack_episode": total_ep - begin_ep + 1, + "note": ( + prev_eps + if self.are_types_equal("note") + else json.dumps(prev_eps) + ), + } + ) + logger.info( + f"{mediainfo.title_year} 更新总集数为: {total_ep},开始集数为: {begin_ep}" + ) + + return kwargs + + @staticmethod + def check_series_info(meta_season: int, bgm_eps: int, mediainfo: MediaInfo) -> bool: + """检查系列信息是否不一致""" + total_episode = len(mediainfo.seasons.get(mediainfo.number_of_seasons) or []) + return ( + meta_season + and mediainfo.number_of_seasons != meta_season + or (bgm_eps != 0 and total_episode != bgm_eps) + or (bgm_eps == 0 and not total_episode >= 12) + ) + + def update_media_info(self, item, mediainfo): + """更新媒体信息""" + for info in mediainfo.season_info: + if self.are_dates(item.get("date"), info.get("air_date")): + mediainfo.number_of_seasons = info.get("season_number") + mediainfo.number_of_episodes = info.get("episode_count") + break + + def get_eps(self) -> tuple: + """获取Bangumi条目的集数信息""" + try: + res = self.get_bgm_res(addr="getEpisodes", id=self._subid) + data = res.json().get("data", [{}])[0] + ep = data.get("ep", 1) + sort = data.get("sort", 1) + total = res.json().get("total", 24) + begin_ep = sort - ep + 1 + total_ep = sort - ep + total + return begin_ep, total_ep + except Exception as e: + logger.error(f"获取集数信息失败: {str(e)}") + return 1, 24 # 默认值 + # 移除订阅 def delete_subscribe(self, del_items: Dict[int, int]): - ''' - 删除订阅 - :param del_items: 数据库id为键,bgm条目id为值 - ''' - args = [i for i in del_items.keys()] - for arg in args: - subscribe_id = int(arg) - subscribe = self.subscribeoper.get(subscribe_id) - if subscribe: - self.subscribeoper.delete(subscribe_id) - # 统计订阅 - self.subscribehelper.sub_done_async( - {"tmdbid": subscribe.tmdbid, "doubanid": subscribe.doubanid} - ) - # 发送通知 - self.post_message( - mtype=NotificationType.Subscribe, - title=f"{subscribe.name}({subscribe.year}) 第{subscribe.season}季 已取消订阅", - text="原因: 未在Bangumi收藏中找到该条目\n" - + f"订阅用户: {subscribe.username}\n" - + f"创建时间: {subscribe.date}", - image=subscribe.backdrop, - ) + """删除订阅""" + for subscribe_id in del_items.keys(): + try: + subscribe = self.subscribeoper.get(subscribe_id) + if subscribe: + self.subscribeoper.delete(subscribe_id) + self.subscribehelper.sub_done_async( + {"tmdbid": subscribe.tmdbid, "doubanid": subscribe.doubanid} + ) + self.post_message( + mtype=NotificationType.Subscribe, + title=f"{subscribe.name}({subscribe.year}) 第{subscribe.season}季 已取消订阅", + text=f"原因: 未在Bangumi收藏中找到该条目\n订阅用户: {subscribe.username}\n创建时间: {subscribe.date}", + image=subscribe.backdrop, + ) + except Exception as e: + logger.error(f"删除订阅失败 {subscribe_id}: {str(e)}") @staticmethod def get_bgm_res(addr: str, id: int | str): @@ -642,45 +567,30 @@ class BangumiColl(_PluginBase): @staticmethod def are_dates(date_str1, date_str2, threshold_days: int = 7) -> bool: - """ - 对比两个日期字符串是否接近 - :param date_str: 日期字符串,格式为'YYYY-MM-DD' - :param threshold_days: 阈值天数,默认为7天 - :return: 如果两个日期之间的差异小于等于阈值天数,则返回True,否则返回False - """ - # 将日期字符串转换为datetime对象 + """对比两个日期字符串是否接近""" date1 = datetime.datetime.strptime(date_str1, '%Y-%m-%d') date2 = datetime.datetime.strptime(date_str2, '%Y-%m-%d') - - # 计算两个日期之间的差异 - delta = abs(date1 - date2) - - # 将阈值转换为timedelta对象 - threshold = datetime.timedelta(days=threshold_days) - - # 比较差异和阈值 - return delta <= threshold + return abs((date1 - date2).days) <= threshold_days @db_query def get_subscribe_history(self, db: Session = None) -> set: - ''' - 获取已完成的订阅 - ''' - result = ( - db.query(SubscribeHistory).filter(SubscribeHistory.bangumiid != None).all() - ) - return set([i.bangumiid for i in result]) + """获取已完成的订阅""" + try: + result = ( + db.query(SubscribeHistory) + .filter(SubscribeHistory.bangumiid.isnot(None)) + .all() + ) + return {i.bangumiid for i in result} + except Exception as e: + logger.error(f"获取订阅历史失败: {str(e)}") + return set() @staticmethod def are_types_equal( attribute_name: str, expected_type: Type[Any] = JSON(), class_=Subscribe ) -> bool: - """ - 比较类中属性的类型与expected_type是否一致 - :param class_: 类 - :param attribute_name: 属性名称 - :param expected_type: 期望的类型 - """ + """比较类中属性的类型与expected_type是否一致""" column = class_.__table__.columns.get(attribute_name) if column is None: raise AttributeError( From 6d6de8b22f4e0175feebc05f2da521639cb26d48 Mon Sep 17 00:00:00 2001 From: Attente <19653207+wikrin@users.noreply.github.com> Date: Mon, 21 Oct 2024 20:37:01 +0800 Subject: [PATCH 13/14] =?UTF-8?q?feat:=20=E4=BF=AE=E5=A4=8D=E4=BB=8EBGM?= =?UTF-8?q?=E8=8E=B7=E5=8F=96=E7=9A=84=E6=80=BB=E9=9B=86=E6=95=B0=E4=BC=9A?= =?UTF-8?q?=E8=A2=ABTMDB=E8=A6=86=E7=9B=96=E7=9A=84=E9=97=AE=E9=A2=98,=20?= =?UTF-8?q?=E6=96=B0=E5=A2=9E=E5=BC=80=E5=85=B3=E9=80=89=E9=A1=B9=E4=BB=A5?= =?UTF-8?q?=E6=8E=A7=E5=88=B6=20=20=20=20=20=20=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E5=BA=95=E9=83=A8=E8=AF=B4=E6=98=8E.=20other:=20=E5=88=86?= =?UTF-8?q?=E7=A6=BB=E7=BB=84=E4=BB=B6,=20=E7=BB=84=E4=BB=B6=E6=94=AF?= =?UTF-8?q?=E6=8C=81HTML=E6=A0=BC=E5=BC=8F=E7=9A=84=E6=96=87=E6=9C=AC?= =?UTF-8?q?=E6=98=BE=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 8 +- plugins/bangumicoll/__init__.py | 314 +++++------------------- plugins/bangumicoll/page_components.py | 318 +++++++++++++++++++++++++ 3 files changed, 386 insertions(+), 254 deletions(-) create mode 100644 plugins/bangumicoll/page_components.py diff --git a/package.json b/package.json index 2e84c46..82e637b 100644 --- a/package.json +++ b/package.json @@ -3,17 +3,15 @@ "name": "Bangumi收藏订阅", "description": "Bangumi用户收藏添加到订阅", "labels": "订阅", - "version": "1.4", + "version": "1.5", "icon": "https://raw.githubusercontent.com/wikrin/MoviePilot-Plugins/main/icons/bangumi_b.png", "author": "Attente", "level": 1, "v2": true, "history": { + "v1.5": "修复总集数会同步TMDB变动的问题,增加开关选项", "v1.4": "结构优化", - "v1.3.1": "修复因修改季号导致未下载剧集而完成订阅的问题", - "v1.3": "添加订阅逻辑优化", - "v1.2.2": "新增: 订阅添加失败总览 修复: 其他方式添加的订阅反复添加的问题", - "v1.2.1": "修复tmdb没有查询到条目导致插件崩溃的问题" + "v1.3.1": "修复因修改季号导致未下载剧集而完成订阅的问题" } } } diff --git a/plugins/bangumicoll/__init__.py b/plugins/bangumicoll/__init__.py index 21d071e..192d236 100644 --- a/plugins/bangumicoll/__init__.py +++ b/plugins/bangumicoll/__init__.py @@ -1,11 +1,20 @@ +# 基础库 import datetime import json -import pytz from typing import Any, Dict, List, Optional, Type +# 第三方库 +from apscheduler.schedulers.background import BackgroundScheduler +from apscheduler.triggers.cron import CronTrigger +import pytz +from sqlalchemy import JSON +from sqlalchemy.orm import Session + +# 项目库 from app.chain.subscribe import SubscribeChain, Subscribe from app.core.config import settings from app.core.context import MediaInfo +from app.core.meta import MetaBase from app.core.metainfo import MetaInfo from app.db.models.subscribehistory import SubscribeHistory from app.db.site_oper import SiteOper @@ -16,10 +25,6 @@ from app.log import logger from app.plugins import _PluginBase from app.schemas.types import NotificationType from app.utils.http import RequestUtils -from apscheduler.schedulers.background import BackgroundScheduler -from apscheduler.triggers.cron import CronTrigger -from sqlalchemy import JSON -from sqlalchemy.orm import Session class BangumiColl(_PluginBase): @@ -30,7 +35,7 @@ class BangumiColl(_PluginBase): # 插件图标 plugin_icon = "https://raw.githubusercontent.com/wikrin/MoviePilot-Plugins/main/icons/bangumi_b.png" # 插件版本 - plugin_version = "1.4" + plugin_version = "1.5" # 插件作者 plugin_author = "Attente" # 作者主页 @@ -50,6 +55,7 @@ class BangumiColl(_PluginBase): # 配置属性 _enabled: bool = False + _total_change: bool = False _cron: str = "" _notify: bool = False _onlyonce: bool = False @@ -76,16 +82,19 @@ class BangumiColl(_PluginBase): def load_config(self, config: dict): """加载配置""" if config: - self._enabled = config.get("enabled", self._enabled) - self._cron = config.get("cron", self._cron) - self._notify = config.get("notify", self._notify) - self._onlyonce = config.get("onlyonce", self._onlyonce) - self._include = config.get("include", self._include) - self._exclude = config.get("exclude", self._exclude) - self._uid = config.get("uid", self._uid) - self._collection_type = config.get("collection_type", [3]) - self._save_path = config.get("save_path", self._save_path) - self._sites = config.get("sites", self._sites) + # 遍历配置中的键并设置相应的属性 + for key in ( + "enabled", + "total_change", + "cron", + "notify", + "onlyonce", + "uid", + "collection_type", + "save_path", + "sites", + ): + setattr(self, f"_{key}", config.get(key, getattr(self, f"_{key}"))) def schedule_once(self): """调度一次性任务""" @@ -109,6 +118,7 @@ class BangumiColl(_PluginBase): { "enabled": self._enabled, "notify": self._notify, + "total_change": self._total_change, "onlyonce": self._onlyonce, "cron": self._cron, "uid": self._uid, @@ -121,199 +131,15 @@ class BangumiColl(_PluginBase): ) def get_form(self): + from .page_components import form + # 列出所有站点 sites_options = [ {"title": site.name, "value": site.id} for site in self.siteoper.list_order_by_pri() ] - return [ - { - 'component': 'VForm', - 'content': [ - { - 'component': 'VRow', - 'content': [ - { - 'component': 'VCol', - 'props': {'cols': 12, 'md': 4}, - 'content': [ - { - 'component': 'VSwitch', - 'props': { - 'model': 'enabled', - 'label': '启用插件', - }, - } - ], - }, - { - 'component': 'VCol', - 'props': {'cols': 12, 'md': 4}, - 'content': [ - { - 'component': 'VSwitch', - 'props': { - 'model': 'notify', - 'label': '自动取消订阅并通知', - }, - } - ], - }, - { - 'component': 'VCol', - 'props': {'cols': 12, 'md': 4}, - 'content': [ - { - 'component': 'VSwitch', - 'props': { - 'model': 'onlyonce', - 'label': '立即运行一次', - }, - } - ], - }, - ], - }, - { - 'component': 'VRow', - 'content': [ - { - 'component': 'VCol', - 'props': {'cols': 12, 'md': 6}, - 'content': [ - { - 'component': 'VTextField', - 'props': { - 'model': 'cron', - 'label': '执行周期', - 'placeholder': '5位cron表达式,留空自动', - }, - } - ], - }, - ], - }, - { - 'component': 'VRow', - 'content': [ - { - 'component': 'VCol', - 'props': {'cols': 12, 'md': 6}, - 'content': [ - { - 'component': 'VTextField', - 'props': { - 'model': 'uid', - 'label': 'UID/用户名', - 'placeholder': '设置了用户名填写用户名,否则填写UID', - }, - }, - ], - }, - { - 'component': 'VCol', - 'props': {'cols': 12, 'md': 6}, - 'content': [ - { - 'component': 'VSelect', - 'props': { - 'model': 'collection_type', - 'label': '收藏类型', - 'chips': True, - 'multiple': True, - 'items': [ - {'title': '在看', 'value': 3}, - {'title': '想看', 'value': 1}, - ], - }, - } - ], - }, - ], - }, - { - 'component': 'VRow', - 'content': [ - { - 'component': 'VCol', - 'props': {'cols': 12, 'md': 6}, - 'content': [ - { - 'component': 'VTextField', - 'props': { - 'model': 'include', - 'label': '包含', - 'placeholder': '暂未实现', - }, - } - ], - }, - { - 'component': 'VCol', - 'props': {'cols': 12, 'md': 6}, - 'content': [ - { - 'component': 'VTextField', - 'props': { - 'model': 'exclude', - 'label': '排除', - 'placeholder': '暂未实现', - }, - } - ], - }, - ], - }, - { - 'component': 'VRow', - 'content': [ - { - 'component': 'VCol', - 'props': {'cols': 12, 'md': 6}, - 'content': [ - { - 'component': 'VTextField', - 'props': { - 'model': 'save_path', - 'label': '保存目录', - 'placeholder': '留空自动', - }, - } - ], - }, - { - 'component': 'VCol', - 'props': {'cols': 12, 'md': 6}, - 'content': [ - { - 'component': 'VSelect', - 'props': { - 'model': 'sites', - 'label': '选择站点', - 'chips': True, - 'multiple': True, - 'items': sites_options, - }, - } - ], - }, - ], - }, - ], - } - ], { - "enabled": False, - "notify": False, - "onlyonce": False, - "cron": "", - "uid": "", - "collection_type": [3], - "include": "", - "exclude": "", - "save_path": "", - "sites": [], - } + return form(sites_options) def get_service(self) -> List[Dict[str, Any]]: """注册插件公共服务""" @@ -372,27 +198,22 @@ class BangumiColl(_PluginBase): def parse_collection_items(self, response) -> Dict[int, Dict[str, Any]]: """解析获取的收藏条目""" - data = response.json().get("data") + data = response.json().get("data", []) if not data: logger.error(f"Bangumi用户:{self._uid} ,没有任何收藏") return {} - items = {} logger.info("解析Bangumi条目信息...") - for item in data: - if item.get("type") not in self._collection_type: - logger.debug( - f"条目: {item['subject'].get('name_cn')} 类型:{item.get('type')} 不符合" - ) - continue - - items[item.get("subject_id")] = { + return { + item.get("subject_id"): { "name": item['subject'].get('name'), "name_cn": item['subject'].get('name_cn'), "date": item['subject'].get('date'), "eps": item['subject'].get('eps'), } - return items + for item in data + if item.get("type") in self._collection_type + } def manage_subscriptions(self, items: Dict[int, Dict[str, Any]]): """管理订阅的新增和删除""" @@ -422,6 +243,7 @@ class BangumiColl(_PluginBase): # 添加订阅 def add_subscribe(self, items: Dict[int, Dict[str, Any]]) -> Dict: """添加订阅""" + fail_items = {} for self._subid, item in items.items(): meta = MetaInfo(item.get("name_cn")) @@ -432,6 +254,7 @@ class BangumiColl(_PluginBase): meta.year = item.get("date")[:4] if item.get("date") else None mediainfo = self.chain.recognize_media(meta=meta) + meta.total_episode = item.get("eps", 0) if not mediainfo: fail_items[self._subid] = f"{item.get('name_cn')} 媒体信息识别失败" continue @@ -442,33 +265,28 @@ class BangumiColl(_PluginBase): mediainfo.tmdb_id, mediainfo.number_of_seasons ) if sid: - logger.info(f"{mediainfo.title_year} {meta.season} 正在订阅中") + logger.info(f"{mediainfo.title_year} 正在订阅中") if len(sid) == 1: self.subscribeoper.update( sid=sid[0].id, payload={"bangumiid": self._subid} ) - logger.info( - f"{mediainfo.title_year} {meta.season} Bangumi条目id更新成功" - ) + logger.info(f"{mediainfo.title_year} Bangumi条目id更新成功") continue sid, msg = self.subscribechain.add( title=mediainfo.title, year=mediainfo.year, - mtype=mediainfo.type, - tmdbid=mediainfo.tmdb_id, bangumiid=self._subid, - season=mediainfo.number_of_seasons, exist_ok=True, username="Bangumi订阅", - **self.prepare_kwargs(item, meta.begin_season, mediainfo), + **self.prepare_kwargs(meta, mediainfo), ) if not sid: fail_items[self._subid] = f"{item.get('name_cn')} {msg}" return fail_items - def prepare_kwargs(self, item: dict, meta_season: int, mediainfo: MediaInfo): + def prepare_kwargs(self, meta: MetaBase, mediainfo: MediaInfo) -> Dict: """准备额外参数""" kwargs = { "save_path": self._save_path, @@ -479,14 +297,24 @@ class BangumiColl(_PluginBase): ), } - if self.check_series_info(meta_season, item.get("eps", 0), mediainfo): - begin_ep, total_ep = self.get_eps() - prev_eps: list = [i for i in range(1, begin_ep)] + total_episode = len(mediainfo.seasons.get(mediainfo.number_of_seasons) or []) + if ( + meta.begin_season + and mediainfo.number_of_seasons != meta.begin_season + or total_episode != meta.total_episode + ): + meta = self.get_eps(meta) + total_ep: int = meta.end_episode if meta.end_episode else total_episode + lock_eps: int = total_ep - meta.begin_episode + 1 + prev_eps: list = [i for i in range(1, meta.begin_episode)] kwargs.update( { "total_episode": total_ep, - "start_episode": begin_ep, - "lack_episode": total_ep - begin_ep + 1, + "start_episode": meta.begin_episode, + "lack_episode": lock_eps, + "manual_total_episode": ( + 1 if meta.total_episode and self._total_change else 0 + ), # 手动修改过总集数 "note": ( prev_eps if self.are_types_equal("note") @@ -495,23 +323,12 @@ class BangumiColl(_PluginBase): } ) logger.info( - f"{mediainfo.title_year} 更新总集数为: {total_ep},开始集数为: {begin_ep}" + f"{mediainfo.title_year} 更新总集数为: {total_ep},开始集数为: {meta.begin_episode}" ) return kwargs - @staticmethod - def check_series_info(meta_season: int, bgm_eps: int, mediainfo: MediaInfo) -> bool: - """检查系列信息是否不一致""" - total_episode = len(mediainfo.seasons.get(mediainfo.number_of_seasons) or []) - return ( - meta_season - and mediainfo.number_of_seasons != meta_season - or (bgm_eps != 0 and total_episode != bgm_eps) - or (bgm_eps == 0 and not total_episode >= 12) - ) - - def update_media_info(self, item, mediainfo): + def update_media_info(self, item: dict, mediainfo: MediaInfo): """更新媒体信息""" for info in mediainfo.season_info: if self.are_dates(item.get("date"), info.get("air_date")): @@ -519,20 +336,19 @@ class BangumiColl(_PluginBase): mediainfo.number_of_episodes = info.get("episode_count") break - def get_eps(self) -> tuple: + def get_eps(self, meta: MetaBase) -> MetaBase: """获取Bangumi条目的集数信息""" try: res = self.get_bgm_res(addr="getEpisodes", id=self._subid) data = res.json().get("data", [{}])[0] - ep = data.get("ep", 1) - sort = data.get("sort", 1) - total = res.json().get("total", 24) - begin_ep = sort - ep + 1 - total_ep = sort - ep + total - return begin_ep, total_ep + prev = data.get("sort", 1) - data.get("ep", 1) + total = res.json().get("total", None) + meta.begin_episode = prev + 1 + meta.end_episode = prev + total if total else None except Exception as e: logger.error(f"获取集数信息失败: {str(e)}") - return 1, 24 # 默认值 + finally: + return meta # 移除订阅 def delete_subscribe(self, del_items: Dict[int, int]): diff --git a/plugins/bangumicoll/page_components.py b/plugins/bangumicoll/page_components.py new file mode 100644 index 0000000..044299c --- /dev/null +++ b/plugins/bangumicoll/page_components.py @@ -0,0 +1,318 @@ +from bs4 import BeautifulSoup + + +def form(sites_options) -> list: + return [ + { + 'component': 'VForm', + 'content': [ + { + 'component': 'VRow', + 'content': [ + { + 'component': 'VCol', + 'props': {'cols': 12, 'md': 3}, + 'content': [ + { + 'component': 'VSwitch', + 'props': { + 'model': 'enabled', + 'label': '启用插件', + }, + } + ], + }, + { + 'component': 'VCol', + 'props': {'cols': 12, 'md': 3}, + 'content': [ + { + 'component': 'VSwitch', + 'props': { + 'model': 'notify', + 'label': '自动取消订阅并通知', + }, + } + ], + }, + { + 'component': 'VCol', + 'props': {'cols': 12, 'md': 3}, + 'content': [ + { + 'component': 'VSwitch', + 'props': { + 'model': 'total_change', + 'label': '不跟随TMDB变动', + }, + } + ], + }, + { + 'component': 'VCol', + 'props': {'cols': 12, 'md': 3}, + 'content': [ + { + 'component': 'VSwitch', + 'props': { + 'model': 'onlyonce', + 'label': '立即运行一次', + }, + } + ], + }, + ], + }, + { + 'component': 'VRow', + 'content': [ + { + 'component': 'VCol', + 'props': {'cols': 8, 'md': 4}, + 'content': [ + { + 'component': 'VTextField', + 'props': { + 'model': 'cron', + 'label': '执行周期', + 'placeholder': '5位cron表达式,留空自动', + }, + } + ], + }, + { + 'component': 'VCol', + 'props': {'cols': 8, 'md': 4}, + 'content': [ + { + 'component': 'VTextField', + 'props': { + 'model': 'uid', + 'label': 'UID/用户名', + 'placeholder': '设置了用户名填写用户名,否则填写UID', + }, + }, + ], + }, + { + 'component': 'VCol', + 'props': {'cols': 8, 'md': 4}, + 'content': [ + { + 'component': 'VSelect', + 'props': { + 'model': 'collection_type', + 'label': '收藏类型', + 'chips': True, + 'multiple': True, + 'items': [ + {'title': '在看', 'value': 3}, + {'title': '想看', 'value': 1}, + ], + }, + } + ], + }, + ], + }, + { + 'component': 'VRow', + 'content': [ + { + 'component': 'VCol', + 'props': {'cols': 12, 'md': 6}, + 'content': [ + { + 'component': 'VTextField', + 'props': { + 'model': 'include', + 'label': '包含', + 'placeholder': '暂未实现', + }, + } + ], + }, + { + 'component': 'VCol', + 'props': {'cols': 12, 'md': 6}, + 'content': [ + { + 'component': 'VTextField', + 'props': { + 'model': 'exclude', + 'label': '排除', + 'placeholder': '暂未实现', + }, + } + ], + }, + ], + }, + { + 'component': 'VRow', + 'content': [ + { + 'component': 'VCol', + 'props': {'cols': 12, 'md': 6}, + 'content': [ + { + 'component': 'VTextField', + 'props': { + 'model': 'save_path', + 'label': '保存目录', + 'placeholder': '留空自动', + }, + } + ], + }, + { + 'component': 'VCol', + 'props': {'cols': 12, 'md': 6}, + 'content': [ + { + 'component': 'VSelect', + 'props': { + 'model': 'sites', + 'label': '选择站点', + 'chips': True, + 'multiple': True, + 'items': sites_options, + }, + } + ], + }, + ], + }, + { + 'component': 'VRow', + 'content': [ + { + 'component': 'VCol', + 'props': { + 'cols': 12, + }, + 'content': [ + { + 'component': 'VAlert', + 'props': { + 'type': 'info', + 'variant': 'tonal', + }, + 'content': parse_html( + '

注意: 该插件仅会将公开的收藏添加到订阅

' + ), + } + ], + } + ], + }, + { + 'component': 'VRow', + 'content': [ + { + 'component': 'VCol', + 'props': { + 'cols': 12, + }, + 'content': [ + { + 'component': 'VAlert', + 'props': { + 'type': 'info', + 'variant': 'tonal', + }, + 'content': parse_html( + '

注意: 开启自动取消订阅并通知后,已添加的订阅在下一次执行时若不在已选择的收藏类型中,将会被取消订阅。

' + ), + } + ], + } + ], + }, + ], + }, + { + 'component': 'VRow', + 'content': [ + { + 'component': 'VCol', + 'props': { + 'cols': 12, + }, + 'content': [ + { + 'component': 'VAlert', + 'props': { + 'type': 'info', + 'variant': 'tonal', + }, + 'content': parse_html( + '

注意: 开启不跟随TMDB变动后,从Bangumi API获取的总集数将不再跟随TMDB的集数变动。

' + ), + }, + ], + }, + ], + }, + ], { + "enabled": False, + "total_change": False, + "notify": False, + "onlyonce": False, + "cron": "", + "uid": "", + "collection_type": [3], + "include": "", + "exclude": "", + "save_path": "", + "sites": [], + } + + +def parse_html(html_string: str) -> list: + soup = BeautifulSoup(html_string, 'html.parser') + result: list = [] + + # 定义需要直接转为文本的标签 + inline_text_tags = {'strong', 'u', 'em', 'b', 'i'} + + def process_element(element: BeautifulSoup): + # 处理纯文本节点 + if element.name is None: + text = element.strip() + return text if text else "" + + # 处理HTML标签 + component = element.name + props = {attr: element[attr] for attr in element.attrs} + content = [] + + # 递归处理子元素 + for child in element.children: + child_content = process_element(child) + if isinstance(child_content, str): + content.append({'component': 'span', 'text': child_content}) + elif child_content: # 只有在child_content不为空时添加 + content.append(child_content) + + # 构建标签对象 + tag_data = { + 'component': component, + 'props': props, + 'content': content if component not in inline_text_tags else [], + } + + if content and component in inline_text_tags: + tag_data['text'] = ' '.join( + item['text'] for item in content if 'text' in item + ) + + return tag_data + + # 遍历所有子元素 + for element in soup.children: + element_content = process_element(element) + if element_content: # 只增加非空内容 + result.append(element_content) + + return result From ef2f91f22291d5d5b06e66516c6729c899394a04 Mon Sep 17 00:00:00 2001 From: Attente <19653207+wikrin@users.noreply.github.com> Date: Wed, 23 Oct 2024 07:08:03 +0800 Subject: [PATCH 14/14] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=E7=94=A8?= =?UTF-8?q?=E6=88=B7=E5=88=A0=E9=99=A4=E7=AB=99=E7=82=B9,=E5=90=8C?= =?UTF-8?q?=E6=AD=A5=E5=88=A0=E9=99=A4=E7=AB=99=E7=82=B9=E5=88=97=E8=A1=A8?= =?UTF-8?q?,=20=E4=B8=8D=E4=BC=9A=E5=86=8D=E7=95=99=E4=B8=8B=E7=BC=96?= =?UTF-8?q?=E5=8F=B7=20fix:=20=E4=BF=AE=E5=A4=8D=E5=9B=A0=E6=9C=AA?= =?UTF-8?q?=E4=BC=A0=E9=80=92=E5=8F=82=E6=95=B0=E5=AF=BC=E8=87=B4=E7=9A=84?= =?UTF-8?q?=E5=AD=A3=E5=BA=A6=E8=AF=86=E5=88=AB=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 3 ++- plugins/bangumicoll/__init__.py | 25 +++++++++++++++++++++---- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index 82e637b..cf47843 100644 --- a/package.json +++ b/package.json @@ -3,12 +3,13 @@ "name": "Bangumi收藏订阅", "description": "Bangumi用户收藏添加到订阅", "labels": "订阅", - "version": "1.5", + "version": "1.5.1", "icon": "https://raw.githubusercontent.com/wikrin/MoviePilot-Plugins/main/icons/bangumi_b.png", "author": "Attente", "level": 1, "v2": true, "history": { + "v1.5.1": "修复季度信息未传递的问题. 新增站点列表同步删除", "v1.5": "修复总集数会同步TMDB变动的问题,增加开关选项", "v1.4": "结构优化", "v1.3.1": "修复因修改季号导致未下载剧集而完成订阅的问题" diff --git a/plugins/bangumicoll/__init__.py b/plugins/bangumicoll/__init__.py index 192d236..e101103 100644 --- a/plugins/bangumicoll/__init__.py +++ b/plugins/bangumicoll/__init__.py @@ -14,6 +14,7 @@ from sqlalchemy.orm import Session from app.chain.subscribe import SubscribeChain, Subscribe from app.core.config import settings from app.core.context import MediaInfo +from app.core.event import eventmanager, Event from app.core.meta import MetaBase from app.core.metainfo import MetaInfo from app.db.models.subscribehistory import SubscribeHistory @@ -23,7 +24,7 @@ from app.db import db_query from app.helper.subscribe import SubscribeHelper from app.log import logger from app.plugins import _PluginBase -from app.schemas.types import NotificationType +from app.schemas.types import EventType, NotificationType from app.utils.http import RequestUtils @@ -35,7 +36,7 @@ class BangumiColl(_PluginBase): # 插件图标 plugin_icon = "https://raw.githubusercontent.com/wikrin/MoviePilot-Plugins/main/icons/bangumi_b.png" # 插件版本 - plugin_version = "1.5" + plugin_version = "1.5.1" # 插件作者 plugin_author = "Attente" # 作者主页 @@ -47,7 +48,7 @@ class BangumiColl(_PluginBase): # 可使用的用户级别 auth_level = 1 - # 私有变量 + # 私有属性 _scheduler: Optional[BackgroundScheduler] = None siteoper: SiteOper = None subscribehelper: SubscribeHelper = None @@ -95,6 +96,12 @@ class BangumiColl(_PluginBase): "sites", ): setattr(self, f"_{key}", config.get(key, getattr(self, f"_{key}"))) + # 获得所有站点 + site_ids = {site.id for site in self.siteoper.list_order_by_pri()} + # 过滤已删除的站点 + self._sites = [site_id for site_id in self._sites if site_id in site_ids] + # 更新配置 + self.__update_config() def schedule_once(self): """调度一次性任务""" @@ -138,7 +145,6 @@ class BangumiColl(_PluginBase): {"title": site.name, "value": site.id} for site in self.siteoper.list_order_by_pri() ] - return form(sites_options) def get_service(self) -> List[Dict[str, Any]]: @@ -167,6 +173,16 @@ class BangumiColl(_PluginBase): except Exception as e: logger.error(f"退出插件失败:{str(e)}") + @eventmanager.register(EventType.SiteDeleted) + def site_deleted(self, event: Event): + """ + 删除对应站点 + """ + site_id = event.event_data.get("site_id") + if site_id in self._sites: + self._sites.remove(site_id) + self.__update_config() + def get_api(self): pass @@ -276,6 +292,7 @@ class BangumiColl(_PluginBase): sid, msg = self.subscribechain.add( title=mediainfo.title, year=mediainfo.year, + season=mediainfo.number_of_seasons, bangumiid=self._subid, exist_ok=True, username="Bangumi订阅",