├── .gitignore ├── LICENSE ├── MP-README.md ├── README.md ├── document └── playlist.md ├── icons ├── maoyan.jpg ├── music.png └── musicd.png ├── package.json ├── package.v2.json ├── plugins.v2 ├── maoyanrank │ └── __init__.py └── syncmusiclist │ ├── QQmusic.py │ ├── __init__.py │ ├── cloudmusic.py │ ├── emby_music.py │ ├── netcloudmusic │ ├── NeteaseCloudMusicApi.js │ ├── __init__.py │ ├── config.json │ ├── help.py │ ├── main.py │ └── utils.py │ ├── plex_music.py │ ├── requirement.txt │ ├── requirements.txt │ └── utils.py └── plugins ├── maoyanrank └── __init__.py └── syncmusiclist ├── QQmusic.py ├── __init__.py ├── cloudmusic.py ├── emby_music.py ├── netcloudmusic ├── NeteaseCloudMusicApi.js ├── __init__.py ├── config.json ├── help.py ├── main.py └── utils.py ├── plex_music.py ├── requirement.txt ├── requirements.txt └── utils.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | .idea/ 161 | /plugins/syncmusiclist/cache/ 162 | /plugins/syncmusiclist/cookie_storage 163 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /MP-README.md: -------------------------------------------------------------------------------- 1 | # MoviePilot-Plugins 2 | MoviePilot官方插件市场:https://github.com/jxxghp/MoviePilot-Plugins 3 | 4 | ## 第三方插件库开发说明 5 | > 请不要开发用于破解MoviePilot用户认证、色情、赌博等违法违规内容的插件,共同维护健康的开发环境! 6 | 7 | 8 | ### 1. 目录结构 9 | - 插件仓库需要保持与本项目一致的目录结构(建议fork后修改),仅支持Github仓库,`plugins`存放插件代码,一个插件一个子目录,**子目录名必须为插件类名的小写**,插件主类在`__init__.py`中编写。 10 | - `package.json`为插件仓库中所有插件概要信息,用于在MoviePilot的插件市场显示,其中版本号等需与插件代码保持一致,通过修改版本号可触发MoviePilot显示插件更新。 11 | 12 | ### 2. 插件图标 13 | - 插件图标可复用官方插件库中`icons`下已有图标,否则需使用完整的http格式的url图片链接(包括package.json中的icon和插件代码中的plugin_icon)。 14 | - 插件的背景颜色会自动提取使用图标的主色调。 15 | 16 | ### 3. 插件命名 17 | - 插件命名请勿与官方库插件中的插件冲突,否则会在MoviePilot版本升级时被官方插件覆盖。 18 | 19 | ### 4. 依赖 20 | - 可在插件目录中放置`requirement.txt`文件,用于指定插件依赖的第三方库,MoviePilot会在插件安装时自动安装依赖库。 21 | 22 | ### 5. 界面开发 23 | - 插件支持`插件配置`及`详情展示`两个展示页面,通过配置化的方式组装,使用[Vuetify](https://vuetifyjs.com/)组件库,所有该组件库有的组件都可以通过Json配置使用。 24 | 25 | 26 | ## 常见问题 27 | 28 | ### 1. 如何扩展消息推送渠道? 29 | - 注册 `NoticeMessage` 事件响应,`event_data` 包含消息中的所有数据,参考 `IYUU消息通知` 插件: 30 | 31 | 注册事件: 32 | ```python 33 | @eventmanager.register(EventType.NoticeMessage) 34 | ``` 35 | 36 | - 事件对象: 37 | ```json 38 | { 39 | "channel": MessageChannel|None, 40 | "type": NotificationType|None, 41 | "title": str, 42 | "text": str, 43 | "image": str, 44 | "userid": str|int, 45 | } 46 | ``` 47 | 48 | PS:MoviePilot中的其它事件也是同样方法实现响应: 49 | ```python 50 | class EventType(Enum): 51 | # 插件重载 52 | PluginReload = "plugin.reload" 53 | # 插件动作 54 | PluginAction = "plugin.action" 55 | # 执行命令 56 | CommandExcute = "command.excute" 57 | # 站点删除 58 | SiteDeleted = "site.deleted" 59 | # Webhook消息 60 | WebhookMessage = "webhook.message" 61 | # 转移完成 62 | TransferComplete = "transfer.complete" 63 | # 添加下载 64 | DownloadAdded = "download.added" 65 | # 删除历史记录 66 | HistoryDeleted = "history.deleted" 67 | # 删除下载源文件 68 | DownloadFileDeleted = "downloadfile.deleted" 69 | # 用户外来消息 70 | UserMessage = "user.message" 71 | # 通知消息 72 | NoticeMessage = "notice.message" 73 | # 名称识别请求 74 | NameRecognize = "name.recognize" 75 | # 名称识别结果 76 | NameRecognizeResult = "name.recognize.result" 77 | ``` 78 | 79 | ### 2. 如何在插件中实现远程命令响应? 80 | - 实现 `get_command()` 方法,按以下格式返回命令列表: 81 | ```json 82 | [{ 83 | "cmd": "/douban_sync", // 动作ID,必须以/开始 84 | "event": EventType.PluginAction,// 事件类型,固定值 85 | "desc": "命令名称", 86 | "category": "命令菜单(微信)", 87 | "data": { 88 | "action": "douban_sync" // 动作标识 89 | } 90 | }] 91 | ``` 92 | 93 | - 注册 `PluginAction` 事件响应,根据 `event_data.action` 是否为插件设定的动作标识来判断是否为本插件事件: 94 | 95 | 注册事件: 96 | ```python 97 | @eventmanager.register(EventType.PluginAction) 98 | ``` 99 | 100 | 事件判定: 101 | ```python 102 | event_data = event.event_data 103 | if not event_data or event_data.get("action") != "douban_sync": 104 | return 105 | ``` 106 | 107 | ### 3. 如何在插件中对外暴露API? 108 | - 实现 `get_api()` 方法,按以下格式返回API列表: 109 | ```json 110 | [{ 111 | "path": "/refresh_by_domain", // API路径,必须以/开始 112 | "endpoint": self.refresh_by_domain, // API响应方法 113 | "methods": ["GET"], // 请求方式:GET/POST/PUT/DELETE 114 | "summary": "刷新站点数据", // API名称 115 | "description": "刷新对应域名的站点数据", // API描述 116 | }] 117 | ``` 118 | 119 | - 在对应的方法中实现API响应方法逻辑,通过 `http://localhost:3001/docs` 查看API文档和调试 120 | 121 | ### 4. 如何通过插件增强MoviePilot的识别功能? 122 | - 注册 `NameRecognize` 事件,实现识别逻辑(参考ChatGPT插件),注意:只有主程序无法识别时才会触发该事件 123 | ```python 124 | @eventmanager.register(EventType.NameRecognize) 125 | ``` 126 | 127 | - 完成识别后发送 `NameRecognizeResult` 事件,将识别结果注入主程序 128 | ```python 129 | eventmanager.send_event( 130 | EventType.NameRecognizeResult, 131 | { 132 | 'title': title, # 原传入标题 133 | 'name': str, # 识别的名称 134 | 'year': str, # 识别的年份 135 | 'season': int, # 识别的季号 136 | 'episode': int, # 识别的集号 137 | } 138 | ) 139 | ``` 140 | 141 | - 注意:识别请求需要在15秒内响应,否则结果会被丢弃;**插件未启用或参数不完整时应立即回复空结果事件,避免主程序等待;** 多个插件开启识别功能时,以先收到的识别结果事件为准。 142 | ```python 143 | eventmanager.send_event( 144 | EventType.NameRecognizeResult, 145 | { 146 | 'title': title # 结果只含原标题,代表空识别结果事件 147 | } 148 | ) 149 | ``` -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MoviePilot-Plugins 2 | MoviePilot官方插件市场:https://github.com/jxxghp/MoviePilot-Plugins 3 | - [食用说明](MP-README.md) 4 | 5 | ### 本仓库插件说明 6 | 7 | - [歌单同步工具](document/playlist.md) -------------------------------------------------------------------------------- /document/playlist.md: -------------------------------------------------------------------------------- 1 | ### 同步QQ/网易云歌单 2 | 3 | - 说明: 同步QQ/网易云歌单到plex&emby 4 | - ⚠️警告: 只同步歌单不进行任何音乐下载 5 | - 仅供学习使用 6 | 7 | ### 食用指南 8 | 1. plex/emby服务器中存在音乐类型的库 9 | 2. plex/emby的播放列表需要提前创建好, 如不存在会自动创建歌单, 如库中没符合的歌曲会创建失败 10 | 3. 歌单同步只会搜索已存在歌曲进行添加,不会自动下载 11 | 4. 歌曲匹配是模糊匹配只匹配曲名不匹配歌手 12 | 5. 网易云歌单同步最好登录自己的账号,失败率会小很多 13 | 6. emby支持多用户设置,plex自带分享无需创建 14 | 7. 无任何下载功能,只是歌单获取同步 15 | 16 | 17 | ### 更新记录 18 | - 3.7: 支持emby多用户,fixbug 19 | - 2.7: 支持emby服务歌单同步 20 | - 1.7: 支持plex服务歌单同步 21 | - 0.7: 初版,获取QQ、网易云歌单 22 | 23 | -------------------------------------------------------------------------------- /icons/maoyan.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/baozaodetudou/MoviePilot-Plugins/c82bc1fca235cdcb868c897a08ba902a6d132927/icons/maoyan.jpg -------------------------------------------------------------------------------- /icons/music.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/baozaodetudou/MoviePilot-Plugins/c82bc1fca235cdcb868c897a08ba902a6d132927/icons/music.png -------------------------------------------------------------------------------- /icons/musicd.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/baozaodetudou/MoviePilot-Plugins/c82bc1fca235cdcb868c897a08ba902a6d132927/icons/musicd.png -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "SyncMusicList": { 3 | "name": "歌单同步", 4 | "description": "同步QQ/网易云歌单到plex&emby。", 5 | "version": "7.1", 6 | "icon": "https://raw.githubusercontent.com/baozaodetudou/MoviePilot-Plugins/main/icons/music.png", 7 | "color": "#7eabf3", 8 | "author": "逗猫", 9 | "level": 2, 10 | "history": { 11 | "v7.1": "1. UI优化 2. 歌单去重 3. plex默认获取最高码率的歌", 12 | "v7.0": "1. cookie缓存 2. 支持网抑云获取每日推荐", 13 | "v6.7": "1. 优化plex搜索 2. 修复插件安装错误", 14 | "v5.7": "1. 重写网易云歌单获取; 2. 优化标题后处理; 3. 优化歌手精准匹配 4. 支持多歌手单个匹配入库 5. 修复bug", 15 | "v4.7": "增加精准匹配功能", 16 | "v3.7": "emby支持多用户, 修复bug", 17 | "v2.7": "修复bug,添加日志说明", 18 | "v1.7": "支持emby", 19 | "v0.7": "初始化版本音乐插件" 20 | } 21 | }, 22 | "MaoyanRank": { 23 | "name": "猫眼榜单订阅", 24 | "description": "监控猫眼数据,自动添加订阅。", 25 | "version": "0.8", 26 | "icon": "https://raw.githubusercontent.com/baozaodetudou/MoviePilot-Plugins/main/icons/maoyan.jpg", 27 | "color": "#fefefe", 28 | "author": "逗猫", 29 | "level": 2, 30 | "history": { 31 | "v1.0": "修复使用缓存进行订阅搜索集数不全的问题", 32 | "v0.7": "界面点击名称跳转TMDB", 33 | "v0.6": "更改图标", 34 | "v0.5": "更改爬取方式,提高成功率", 35 | "v0.4": "电视剧订阅添加去重", 36 | "v0.3": "增加平台分类", 37 | "v0.2": "电视剧电影以及综艺的分类", 38 | "v0.1": "初始化版本猫眼订阅功能" 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /package.v2.json: -------------------------------------------------------------------------------- 1 | { 2 | "SyncMusicList": { 3 | "name": "歌单同步", 4 | "description": "同步QQ/网易云歌单到plex&emby。", 5 | "version": "7.2", 6 | "icon": "https://raw.githubusercontent.com/baozaodetudou/MoviePilot-Plugins/main/icons/music.png", 7 | "color": "#7eabf3", 8 | "author": "逗猫", 9 | "level": 1, 10 | "history": { 11 | "v7.2": "适配v2版本", 12 | "v7.1": "1. UI优化 2. 歌单去重 3. plex默认获取最高码率的歌", 13 | "v7.0": "1. cookie缓存 2. 支持网抑云获取每日推荐", 14 | "v6.7": "1. 优化plex搜索 2. 修复插件安装错误", 15 | "v5.7": "1. 重写网易云歌单获取; 2. 优化标题后处理; 3. 优化歌手精准匹配 4. 支持多歌手单个匹配入库 5. 修复bug", 16 | "v4.7": "增加精准匹配功能", 17 | "v3.7": "emby支持多用户, 修复bug", 18 | "v2.7": "修复bug,添加日志说明", 19 | "v1.7": "支持emby", 20 | "v0.7": "初始化版本音乐插件" 21 | } 22 | }, 23 | "MaoyanRank": { 24 | "name": "猫眼榜单订阅", 25 | "description": "监控猫眼数据,自动添加订阅。", 26 | "version": "2.7", 27 | "icon": "https://raw.githubusercontent.com/baozaodetudou/MoviePilot-Plugins/main/icons/maoyan.jpg", 28 | "color": "#fefefe", 29 | "author": "逗猫", 30 | "level": 1, 31 | "history": { 32 | "v2.7": "增加优酷平台获取", 33 | "v1.7": "更改榜单的排列组合支持多个平台同时订阅的功能", 34 | "v1.6": "适配新的url获取", 35 | "v1.5": "增加了条数配置选项支持1,2,3,5,7,10选择", 36 | "v1.4": "增加支持了网络电影的订阅功能", 37 | "v1.3": "取消猫眼榜单删除的平台", 38 | "v1.2": "修改获取榜单的方法增加成功率", 39 | "v1.1": "优化执行周期录入", 40 | "v1.0": "修复使用缓存进行订阅搜索集数不全的问题", 41 | "v0.7": "界面点击名称跳转TMDB", 42 | "v0.6": "更改图标", 43 | "v0.5": "更改爬取方式,提高成功率", 44 | "v0.4": "电视剧订阅添加去重", 45 | "v0.3": "增加平台分类", 46 | "v0.2": "电视剧电影以及综艺的分类", 47 | "v0.1": "初始化版本猫眼订阅功能" 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /plugins.v2/syncmusiclist/QQmusic.py: -------------------------------------------------------------------------------- 1 | import re 2 | import json 3 | import uuid 4 | 5 | from app.plugins.syncmusiclist.utils import sub_str, change_str 6 | from app.utils.http import RequestUtils 7 | 8 | 9 | class QQMusicApi(object): 10 | """ 11 | QQ音乐获取信息的api 12 | """ 13 | def __init__(self): 14 | self.req = None 15 | self.cookie = "" 16 | self.headers = {} 17 | self.set_session() 18 | 19 | def set_cookie(self, cookie): 20 | self.cookie = cookie 21 | 22 | def set_headers(self): 23 | self.headers = { 24 | "authority": "u6.y.qq.com", 25 | "User-Agent": "QQ音乐/73222 CFNetwork/1406.0.2 Darwin/22.4.0".encode("utf-8"), 26 | "Accept": "*/*", 27 | "Accept-Language": "zh-CN,zh-Hans;q=0.9", 28 | "Referer": "http://y.qq.com", 29 | "Content-Type": "application/json; charset=UTF-8", 30 | "Cookie": self.cookie, 31 | } 32 | 33 | def set_session(self): 34 | self.set_headers() 35 | self.req = RequestUtils(headers=self.headers) 36 | return self.req 37 | 38 | def get_playlist_by_id(self, play_id): 39 | """ 40 | 通过歌单id获取歌单列表 41 | """ 42 | _uuid = uuid.uuid1().__str__() 43 | url = "https://u.y.qq.com/cgi-bin/musicu.fcg" 44 | payload = { 45 | "getMusicPlaylist": { 46 | "module": "music.srfDissInfo.aiDissInfo", 47 | "method": "uniform_get_Dissinfo", 48 | "param": { 49 | "disstid": int(play_id), 50 | "userinfo": 1, 51 | "tag": 1, 52 | "is_pc": 1, 53 | "guid": _uuid, 54 | }, 55 | }, 56 | "comm": { 57 | "g_tk": 0, 58 | "uin": "", 59 | "format": "json", 60 | "ct": 6, 61 | "cv": 80600, 62 | "platform": "wk_v17", 63 | "uid": "", 64 | "guid": _uuid, 65 | }, 66 | } 67 | data = json.dumps(payload, ensure_ascii=False) 68 | res_json = self.req.post(url=url, data=data).json() 69 | playlist = res_json.get("getMusicPlaylist") 70 | if playlist["code"] == 0: 71 | lst = playlist.get('data', {}).get('songlist', []) 72 | else: 73 | lst = [] 74 | list_clear = [] 75 | for i in lst: 76 | # 正则处理 77 | name = sub_str(i.get('name')) 78 | # 多歌手处理 79 | ars = [change_str(ar.get('name')) for ar in i.get('singer')] 80 | list_clear.append([name, ars]) 81 | return list_clear 82 | 83 | 84 | if __name__ == '__main__': 85 | qq = QQMusicApi() 86 | res = qq.get_playlist_by_id('7039481526') 87 | print(res) 88 | 89 | -------------------------------------------------------------------------------- /plugins.v2/syncmusiclist/cloudmusic.py: -------------------------------------------------------------------------------- 1 | 2 | import re 3 | import time 4 | 5 | 6 | from app.log import logger 7 | from app.plugins.syncmusiclist.netcloudmusic import NeteaseCloudMusicApi 8 | from app.plugins.syncmusiclist.utils import change_str, sub_str 9 | 10 | 11 | class CloudMusic(object): 12 | def __init__(self, path=None): 13 | self.music_api = NeteaseCloudMusicApi(path=path) # 初始化API 14 | version_result = self.music_api.request("inner_version") 15 | logger.info(f'当前使用NeteaseCloudMusicApi版本号:{version_result["NeteaseCloudMusicApi"]}\n' 16 | f'当前使用NeteaseCloudMusicApi_V8版本号:{version_result["NeteaseCloudMusicApi_V8"]}') 17 | 18 | def login_status(self): 19 | """账户登录状态""" 20 | try: 21 | if not self.music_api.cookie: 22 | return None 23 | response = self.music_api.request("/login/status") 24 | if response['data']['data']["code"] == 200: 25 | try: 26 | nickname = response["data"]["data"]["profile"]["nickname"] 27 | logger.info(f'当前登录账号:{nickname}') 28 | except: 29 | nickname = None 30 | return nickname 31 | else: 32 | return None 33 | except: 34 | return None 35 | 36 | def captcha_sent(self, _phone): 37 | """验证码""" 38 | response = self.music_api.request("/captcha/sent", {"phone": f"{_phone}"}) 39 | return response 40 | 41 | def login_cellphone(self, _phone, _captcha): 42 | """验证码登录""" 43 | response = self.music_api.request("/login/cellphone", {"phone": f"{_phone}", "captcha": f"{_captcha}"}) 44 | return response 45 | 46 | 47 | def login(self, username, password): 48 | """ 49 | 登陆到网易云音乐 50 | 调用登录接口后,会自动设置cookie,如果cookie失效,需要重新登录,登录过后api会在你的当前工作目录下创建cookie_storage文件保存你的cookie 51 | 在下次调用运行程序时,他会判断cookie是否过期,没有过期就自动读取cookie_storage文件中的cookie。 52 | 53 | 总的来说你不需要手动管理cookie,只需要调用登录接口,然后调用其他接口即可,cookie会自动设置,如果cookie过期,再次调用登录接口就好。 54 | 更好的办法是,在cookie还没有失效之前使用refresh_login接口刷新cookie,这样就不需要重新登录了(建议在你每次启动软件时都刷新,当然频繁重启调试的时候另算) 55 | 56 | 如果你想判断当前是否已经登录,if not netease_cloud_music_api.cookie 就可以了,或者调用/login/status接口 57 | 58 | """ 59 | # 登录 60 | if not self.music_api.cookie: 61 | if username.isdigit(): 62 | response = self.music_api.request("/login/cellphone", 63 | {"phone": f"{username}", "password": f"{password}"}) 64 | else: 65 | response = self.music_api.request("/login", 66 | {"email": f"{username}", "password": f"{password}"}) 67 | if response.get("code") == 200: 68 | logger.info("登录成功") 69 | if self.music_api.cookie: 70 | logger.info("cookie已缓存") 71 | else: 72 | logger.error("登录失败") 73 | 74 | def signin(self): 75 | """网易云签到""" 76 | res = self.music_api.request("/daily_signin") 77 | return res 78 | 79 | def get_list_days(self, nums=5): 80 | """每日推荐歌单""" 81 | res = self.music_api.request("/recommend/resource") 82 | recommend = res.get('data', {}).get('recommend', []) 83 | res = [[i.get("id"), i.get("name")] for i in recommend[:nums] if i.get("id")] 84 | return res 85 | 86 | def get_song_daily(self): 87 | """每日推荐歌曲""" 88 | res = self.music_api.request("/recommend/songs") 89 | dailySongs = res['data']['data']['dailySongs'] 90 | track_names = [] 91 | for i in dailySongs: 92 | # 正则处理 93 | name = sub_str(i.get('name')) 94 | # 多歌手处理 95 | ars = [change_str(ar.get('name')) for ar in i.get('ar')] 96 | track_names.append([name, ars]) 97 | return track_names 98 | 99 | 100 | def playlist(self, uid): 101 | """ 102 | 歌单 103 | Full request URI: http://music.163.com/api/playlist/detail?id=37880978&updateTime=-1 104 | GET http://music.163.com/api/playlist/detail 105 | 必要参数: 106 | id:歌单ID 107 | """ 108 | res = self.music_api.request(f"/playlist/track/all", {"id": f"{uid}"}) 109 | return res.get('data', {}).get('songs') 110 | 111 | def songofplaylist(self, uid): 112 | """ 113 | 获取歌单中歌曲 114 | """ 115 | tracks = [] 116 | # 循环进行重试 117 | # 设置最大重试次数 118 | max_retry_times = 5 119 | # 当前重试次数 120 | retry_times = 0 121 | while retry_times < max_retry_times: 122 | try: 123 | tracks = self.playlist(uid) 124 | break # 如果成功执行,跳出循环 125 | except Exception as e: 126 | logger.warn(f"第 {retry_times + 1} 次重试失败:获取歌单错误") 127 | retry_times += 1 128 | time.sleep(2) # 添加延时 129 | track_names = [] 130 | for i in tracks: 131 | # 正则处理 132 | name = sub_str(i.get('name')) 133 | # 多歌手处理 134 | ars = [change_str(ar.get('name')) for ar in i.get('ar')] 135 | track_names.append([name, ars]) 136 | return track_names 137 | 138 | 139 | if __name__ == '__main__': 140 | cm = CloudMusic() 141 | cm.signin() 142 | res_s = cm.get_song_daily() 143 | 144 | print(res_s) 145 | res_day = cm.get_list_days() 146 | 147 | res = cm.songofplaylist("365436873") 148 | print(res) 149 | 150 | 151 | -------------------------------------------------------------------------------- /plugins.v2/syncmusiclist/emby_music.py: -------------------------------------------------------------------------------- 1 | from typing import List, Optional, Union, Dict, Generator, Tuple 2 | 3 | from app.log import logger 4 | from app.schemas import MediaType, MediaServerLibrary 5 | from app.modules.emby import Emby 6 | from app.utils.http import RequestUtils 7 | from app.core.config import settings 8 | 9 | 10 | class EmbyMusic(Emby): 11 | """API for Plex 12 | 继承根项目, 实现音乐库相关的api 13 | """ 14 | 15 | def __init__(self, host: str = None, apikey: str = None, play_host: str = None, 16 | sync_libraries: list = None, **kwargs): 17 | Emby.__init__(self, host=host, apikey=apikey) 18 | self.default_user = self.get_default_user(settings.SUPERUSER) 19 | self.music_libraries = [] 20 | self.music_playlists = [] 21 | 22 | def get_default_user(self, user_name: str = None) -> Optional[Union[str, int]]: 23 | """ 24 | 获得管理员用户 25 | """ 26 | if not self._host or not self._apikey: 27 | return None 28 | req_url = "%sUsers?api_key=%s" % (self._host, self._apikey) 29 | try: 30 | res = RequestUtils().get_res(req_url) 31 | if res: 32 | users = res.json() 33 | # 先查询是否有与当前用户名称匹配的 34 | if user_name: 35 | for user in users: 36 | if user.get("Name") == user_name: 37 | return user.get("Name") 38 | # 查询管理员 39 | for user in users: 40 | if user.get("Policy", {}).get("IsAdministrator"): 41 | return user.get("Name") 42 | else: 43 | logger.error(f"Users 未获取到返回数据") 44 | except Exception as e: 45 | logger.error(f"连接Users出错:" + str(e)) 46 | return None 47 | 48 | def __get_emby_librarys(self) -> List[dict]: 49 | """ 50 | 获取Emby媒体库列表 51 | """ 52 | if not self._host or not self._apikey: 53 | return [] 54 | req_url = f"{self._host}emby/Users/{self.user}/Views?api_key={self._apikey}" 55 | try: 56 | res = RequestUtils().get_res(req_url) 57 | if res: 58 | return res.json().get("Items") 59 | else: 60 | logger.error(f"EmbyUser/Views 未获取到返回数据") 61 | return [] 62 | except Exception as e: 63 | logger.error(f"Emby连接User/Views 出错:" + str(e)) 64 | return [] 65 | 66 | def get_music_library(self): 67 | """ 68 | 获取媒体服务器所有音乐类型媒体库列表以及所有playlist 69 | """ 70 | if not self._host or not self._apikey: 71 | return [] 72 | emby_librarys = self.__get_emby_librarys() or [] 73 | self.music_playlists = [] 74 | self.music_libraries = [] 75 | for library in emby_librarys: 76 | if library.get("CollectionType") == 'music': 77 | self.music_libraries.append( 78 | MediaServerLibrary( 79 | server="emby", 80 | id=library.get("Id"), 81 | name=library.get("Name"), 82 | path=library.get("Path"), 83 | type=library.get("CollectionType") 84 | ) 85 | ) 86 | elif library.get("CollectionType") == 'playlists': 87 | url = f'{self._host}emby/Users/{self.user}/Items?ParentId={library.get("Id")}&api_key={self._apikey}' 88 | try: 89 | res = self.get_data(url) 90 | playlist = res.json().get("Items") 91 | except Exception as err: 92 | logger.error(f"Emby获取播放列表失败: {err}") 93 | playlist = [] 94 | self.music_playlists += playlist 95 | else: 96 | continue 97 | return self.music_libraries 98 | 99 | def get_tracks_by_playlist(self, playlist_title): 100 | """获取播放列表的详细歌单""" 101 | playlist_id = None 102 | for i in self.music_playlists: 103 | if playlist_title == i.get('Name'): 104 | playlist_id = i.get('Id') 105 | break 106 | if not playlist_id: 107 | logger.warn(f"Emby媒体库中播放列表为:[{[i.get('Name') for i in self.music_playlists]}]\n 不存在: [{playlist_title}], 稍后会自动创建,如果失败请手动创建") 108 | return '', [], [] 109 | url = f'{self._host}emby/Users/{self.user}/Items?ParentId={playlist_id}&api_key={self._apikey}' 110 | try: 111 | res = self.get_data(url) 112 | tracks = res.json().get("Items") 113 | except Exception as err: 114 | logger.error(f"Emby获取播放列表失败: {err}") 115 | tracks = [] 116 | music_ids = [i.get('Id') for i in tracks if i.get('Type') == 'Audio'] 117 | music_names = [i.get('Name') for i in tracks if i.get('Type') == 'Audio'] 118 | return playlist_id, music_ids, music_names 119 | 120 | def create_playlist(self, name, ids, user=settings.SUPERUSER): 121 | """创建播放列表""" 122 | if name in [i.get('Name') for i in self.music_playlists]: 123 | logger.info(f"Emby歌单: [{name}] 已经存在,跳过创建") 124 | # Playlists 125 | url = f'{self._host}emby/Playlists?api_key={self._apikey}&userId={self.user}&Name={name}&Ids={ids}' 126 | try: 127 | res = self.post_data( 128 | url, 129 | headers={"Content-Type": "application/json"} 130 | ) 131 | if res.status_code == 200: 132 | info = res.json() 133 | logger.info(f"Emby为用户{user}创建歌单成功:{info}") 134 | return True 135 | else: 136 | logger.error(f"Emby为用户{user}创建歌单失败:[{name}]") 137 | return False 138 | except Exception as e: 139 | logger.error(f"Emby为用户{user}创建歌单失败:[{name}]: {e}") 140 | return False 141 | 142 | def set_tracks_to_playlist(self, playlist_id, ids, user=settings.SUPERUSER): 143 | """添加歌曲到歌单中""" 144 | url = f'{self._host}emby/Playlists/{playlist_id}/Items?api_key={self._apikey}&userId={self.user}&Ids={ids}' 145 | try: 146 | res = self.post_data( 147 | url, 148 | headers={"Content-Type": "application/json"} 149 | ) 150 | if res.status_code == 200: 151 | info = res.json() 152 | logger.info(f"Emby为用户{user}的歌单添加歌曲成功:[{info}]") 153 | return True 154 | else: 155 | logger.error(f"Emby为用户{user}的歌单添加歌曲失败") 156 | return False 157 | except Exception as e: 158 | logger.error(e) 159 | return False 160 | 161 | def search_music(self, name_singer, exact_match=True): 162 | """通过歌曲名在库中进行搜索""" 163 | # /emby/Users/{}/Items?Recursive=true&SearchTerm={}&api_key={} 164 | name = name_singer[0] 165 | singers = name_singer[1] 166 | url = f'{self._host}emby/Users/{self.user}/Items?Recursive=true&SearchTerm={name}&api_key={self._apikey}' 167 | try: 168 | res = self.get_data(url) 169 | count = res.json().get("TotalRecordCount") 170 | if count > 0: 171 | items = res.json().get("Items") 172 | if exact_match: 173 | add_items = [] 174 | # 通过歌手过滤 175 | for i in items: 176 | arts = i.get("Artists", []) 177 | if len(set(arts) & set(singers)) > 0: 178 | # add 179 | add_items = [i] 180 | break 181 | else: 182 | str_arts = ' '.join(arts) 183 | for singer in singers: 184 | if singer in str_arts: 185 | # add 186 | add_items = [i] 187 | break 188 | if add_items: 189 | break 190 | else: 191 | add_items = items 192 | 193 | ids_list = [i.get('Id') for i in add_items if i.get('Type') == 'Audio'][:1] 194 | name_list = [i.get('Name') for i in add_items if i.get('Type') == 'Audio'][:1] 195 | else: 196 | ids_list = [] 197 | name_list = [] 198 | except Exception as err: 199 | logger.error(err) 200 | return [], [] 201 | return ids_list, name_list 202 | 203 | def mul_search_music(self, name_list, exact_match=True): 204 | logger.info(f"Emby中的播放列表为: {[i.get('Name') for i in self.music_playlists]}") 205 | all_list = [] 206 | lack_list = [] 207 | add_list = [] 208 | for names in name_list: 209 | ids_list, name_list = self.search_music(names, exact_match) 210 | if len(ids_list) == 0: 211 | lack_list.append(names) 212 | else: 213 | add_list += name_list 214 | all_list += ids_list 215 | logger.info(f"Emby搜索库中获取歌曲[{len(add_list)}]首,列表为: {add_list}") 216 | logger.info(f"Emby库中未搜到歌曲[{len(lack_list)}]首,列表为: {lack_list}") 217 | return all_list 218 | 219 | 220 | if __name__ == '__main__': 221 | em = EmbyMusic() 222 | emby_user = 'tzp' 223 | em.user = em.get_user(emby_user) 224 | em.get_music_library() 225 | media_playlist = "许嵩专版" 226 | t_tracks = [['通天大道宽又阔', ['崔京浩', '三叶草演唱组']], ['微微', ['傅如乔']], ['相思', ['毛阿敏']]] 227 | 228 | tracks = em.mul_search_music(t_tracks) 229 | playlist_id, music_ids, music_names = em.get_tracks_by_playlist(media_playlist) 230 | if playlist_id: 231 | ids = [i for i in tracks if i not in music_ids] 232 | em.set_tracks_to_playlist(playlist_id, ','.join(ids)) 233 | else: 234 | em.create_playlist(media_playlist, ','.join(tracks)) 235 | print(music_ids) 236 | 237 | 238 | -------------------------------------------------------------------------------- /plugins.v2/syncmusiclist/netcloudmusic/__init__.py: -------------------------------------------------------------------------------- 1 | from .main import NeteaseCloudMusicApi 2 | from .help import api_help, api_list 3 | from .utils import format_cookie_str, prase_cookie_str 4 | 5 | __version__ = '0.1.7' 6 | -------------------------------------------------------------------------------- /plugins.v2/syncmusiclist/netcloudmusic/help.py: -------------------------------------------------------------------------------- 1 | import json 2 | import pkg_resources 3 | 4 | # 载入配置 5 | resource_path = pkg_resources.resource_filename(__name__, 'config.json') 6 | 7 | # 不被支持的接口 8 | exclude = ["/request/reference", "/avatar/upload", "/cloud", "/playlist/cover/update", "/voice/upload", 9 | "/register/anonimous", "/verify/getQr"] 10 | 11 | with open(resource_path, 'r', encoding='utf-8') as f: 12 | config = json.loads(f.read()) 13 | 14 | 15 | def api_help(name: str = None) -> str: 16 | """ 17 | 获取接口帮助 18 | :param name: 接口名称 19 | :return: 20 | """ 21 | if name is None: 22 | result_str = ("from NeteaseCloudMusic import NeteaseCloudMusicApi, api_help, api_list\n\n" 23 | "netease_cloud_music_api = NeteaseCloudMusicApi() # 初始化API\n" 24 | "netease_cloud_music_api.cookie = YOUR_COOKIE # 设置cookie\n" 25 | "response = netease_cloud_music_api.request(apiName, queryDict) # 调用接口\n\n" 26 | "# Use ”help(apiName)“ to view detailed information about the interface\n" 27 | "# Use ”api_list()“ to view the interface list") 28 | elif name in api_list(): 29 | result_str = f'name: {name}\n {config[name]["name"]}\n {config[name]["explain"]}\n\n' 30 | 31 | result_str += "query example: \n" 32 | for example in config[name]["example"]: 33 | index = config[name]["example"].index(example) 34 | result_str += f'{json.dumps(config[name]["example"][index]["query"], indent=2, ensure_ascii=False)}\n\n' 35 | else: 36 | result_str = f'apiName: {name} not found,please use ”api_list()“ to view the interface list' 37 | 38 | return result_str 39 | 40 | 41 | def api_list(): 42 | """ 43 | 获取接口列表 44 | :return: 45 | """ 46 | return [item for item in list(config.keys()) if item not in exclude] 47 | -------------------------------------------------------------------------------- /plugins.v2/syncmusiclist/netcloudmusic/main.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os.path 3 | import socket 4 | import time 5 | from pprint import pprint 6 | import http.cookies 7 | import datetime 8 | from diskcache import Cache 9 | 10 | import pkg_resources 11 | import requests 12 | from py_mini_racer import py_mini_racer 13 | from .help import api_list 14 | from .utils import format_cookie_str, prase_cookie_str 15 | import urllib.parse 16 | 17 | 18 | class NeteaseCloudMusicApi: 19 | __cookie = None 20 | __ip = None 21 | 22 | 23 | # cache = TTLCache(maxsize=100, ttl=120) # 设置缓存大小为100,缓存项的生存时间为120秒 24 | 25 | def __init__(self, debug=False, cach=False, path=None): 26 | self.path = path 27 | if path: 28 | self.cache = Cache(str(self.path), timeout=120) # 设置缓存目录和过期时间 29 | else: 30 | self.cache = Cache('cache', timeout=120) # 设置缓存目录和过期时间 31 | 32 | self.DEBUG = debug # 是否开启调试模式 33 | self.CACHE = cach # 是否开启缓存 34 | 35 | self.special_api = {"/playlist/track/all": self.playlist_track_all, 36 | "/login/cellphone": self.login_cellphone, 37 | "/inner/version": self.inner_version, 38 | "/login/refresh": self.login_refresh} 39 | 40 | # 载入js代码 41 | resource_path = pkg_resources.resource_filename(__name__, 'NeteaseCloudMusicApi.js') 42 | 43 | with open(resource_path, 'r', encoding='utf-8') as file: 44 | js_code = file.read() 45 | self.ctx = py_mini_racer.MiniRacer() 46 | self.ctx.eval(js_code) 47 | 48 | def request(self, name: str, query: dict = None) -> dict: 49 | """ 50 | 调用接口 51 | 接口文档地址: https://docs.neteasecloudmusicapi.binaryify.com 52 | :param name: api名称 例如: song_url_v1, /song/url/v1 53 | :param query: 请求参数 54 | :return: 请求结果 示例:{"code": 200, "data": {}, "msg": "success"} 55 | """ 56 | 57 | special = { 58 | 'daily_signin': '/daily_signin', 59 | 'fm_trash': '/fm_trash', 60 | 'personal_fm': '/personal_fm', 61 | } 62 | 63 | yubei_special = {'/yunbei/tasks/receipt': '/yunbei/receipt', 64 | '/yunbei/tasks/expense': '/yunbei/expense'} # 这俩个接口准换的路由莫名奇妙 65 | 66 | # 测试name是否合法 67 | name.replace("\\", "/") 68 | if not name.startswith("/"): 69 | if name in special.keys(): 70 | name = special[name] 71 | else: 72 | name = "/" + name 73 | name = name.replace("_", "/") 74 | 75 | # 处理俩个云贝接口名称转换问题 76 | if name in yubei_special.keys(): 77 | name = yubei_special[name] 78 | # print("转换了个麻烦的路由", name) 79 | 80 | if name not in api_list(): 81 | if name not in yubei_special.values(): 82 | raise Exception(f"apiName: {name} not found,please use ”api_list()“ to view the interface list") 83 | 84 | # 生成一个唯一的键,用于在缓存中查找结果 85 | cache_key = (name, frozenset(query.items()) if query else None) 86 | 87 | if self.CACHE: 88 | # 检查缓存中是否已经有了结果 89 | if self.cache.get(cache_key): 90 | return self.cache.get(cache_key) 91 | 92 | if query is None: 93 | query = {} 94 | else: 95 | # 如果存在timestamp参数,那么删除它 96 | if query.get("timestamp"): 97 | del query["timestamp"] 98 | 99 | if query.get("cookie") is None: 100 | query["cookie"] = self.cookie 101 | 102 | if query.get("realIP") is None: 103 | query["realIP"] = self.ip 104 | else: 105 | query["realIP"] = query.get("realIP") 106 | 107 | # 特殊api处理 108 | if name in self.special_api.keys(): 109 | result = self.special_api[name](query) 110 | else: 111 | result = self.call_api(name, query) 112 | 113 | if self.CACHE: 114 | # 将结果存入缓存 115 | self.cache.set(cache_key, result) 116 | 117 | return result 118 | 119 | @staticmethod 120 | def get_local_ip(): 121 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 122 | try: 123 | # doesn't even have to be reachable 124 | s.connect(('10.255.255.255', 1)) 125 | IP = s.getsockname()[0] 126 | except Exception: 127 | print("get local ip error") 128 | IP = "116.25.146.177" 129 | finally: 130 | s.close() 131 | return IP 132 | 133 | @property 134 | def cookie(self): 135 | if self.__cookie is None: 136 | 137 | cookie_path = str(self.path / "cookie_storage") if self.path else "cookie_storage" 138 | if os.path.isfile(cookie_path): 139 | with open(cookie_path, "r", encoding='utf-8') as f: 140 | content = f.read() 141 | try: 142 | cookie_storage = json.loads(content) 143 | # 验证cookie是否过期 144 | create_time_stamp = cookie_storage['create_time_stamp'] 145 | 146 | if time.time() - create_time_stamp > 1296010: 147 | # cookie过期了 148 | self.__cookie = "" 149 | else: 150 | # 判断cookie生成时间是否超过1天 151 | if time.time() - create_time_stamp > 86400: 152 | # 更新cookie 153 | # Todo login_refresh接口返回cookie好像少一些值 154 | # self.request("/login/refresh", {"cookie": cookie_storage['cookie'], "timestamp": time.time()}) 155 | self.cookie = cookie_storage['cookie'] 156 | else: 157 | self.__cookie = cookie_storage['cookie'] 158 | except json.JSONDecodeError and KeyError: 159 | self.__cookie = "" 160 | else: 161 | self.__cookie = "" # 如果没有cookie文件,就设置为空 162 | 163 | return self.__cookie 164 | 165 | @cookie.setter 166 | def cookie(self, value): 167 | if value is None: 168 | self.__cookie = "" 169 | return 170 | 171 | "判断cookie是否合法, 简单检查一下关键的键" 172 | necessary_keys = ["__csrf", "MUSIC_A_T", "MUSIC_R_T"] 173 | cookie_dict = prase_cookie_str(value) 174 | for key in necessary_keys: 175 | if cookie_dict.get(key) is None: 176 | raise Exception(f"cookie is illegal, missing key: {key}.") 177 | 178 | self.__cookie = value 179 | cookie_path = str(self.path / "cookie_storage") if self.path else "cookie_storage" 180 | with open(cookie_path, "w+", encoding='utf-8') as f: 181 | f.write(json.dumps({"cookie": value, "create_time_stamp": time.time()}, indent=2, ensure_ascii=False)) 182 | 183 | @property 184 | def ip(self): 185 | if self.__ip is None: 186 | self.__ip = self.get_local_ip() 187 | return self.__ip 188 | 189 | def call_api(self, name, query): 190 | request_param = self.ctx.call('NeteaseCloudMusicApi.beforeRequest', name, query) # 拿到请求头和请求参数 191 | 192 | # Todo 了解 py_mini_racer 返回没有自动编码 而 node可以 193 | param_data = {} 194 | if request_param["data"] != "": 195 | for item in request_param["data"].split("&"): 196 | # param_data[item.split("=")[0]] = urllib.parse.quote(item.split("=")[1], safe='') # 不需要编码后反而出错 197 | param_data[item.split("=")[0]] = item.split("=")[1] 198 | 199 | if request_param.get("method") == "GET": 200 | response = requests.get(request_param["url"], params=param_data, headers=request_param["headers"]) 201 | else: 202 | response = requests.post(request_param["url"], data=param_data, headers=request_param["headers"]) 203 | 204 | try: 205 | data = json.loads(response.text) 206 | except json.JSONDecodeError: 207 | data = response.text 208 | 209 | response_result = { 210 | "headers": dict(response.headers), 211 | "data": data, 212 | "status": response.status_code, 213 | } 214 | 215 | result = self.ctx.call('NeteaseCloudMusicApi.afterRequest', 216 | json.dumps(response_result), 217 | request_param.get('crypto', None), 218 | request_param['apiName']) # 拿到请求结果 219 | 220 | return result 221 | 222 | def playlist_track_all(self, query): 223 | """ 224 | 获取歌单全部歌曲 225 | :param query: 226 | :return: 227 | """ 228 | 229 | detail_query = {"id": query.get("id"), "cookie": query.get("cookie"), "realIP": query.get("realIP")} 230 | 231 | result = self.call_api("/playlist/detail", detail_query) 232 | 233 | track_all_query = {"detail_result": json.dumps(result), "cookie": query.get("cookie"), 234 | "realIP": query.get("realIP")} 235 | if query.get("limit"): 236 | track_all_query["limit"] = query.get("limit") 237 | if query.get("offset"): 238 | track_all_query["offset"] = query.get("offset") 239 | 240 | result = self.call_api("/playlist/track/all", track_all_query) 241 | return result 242 | 243 | def inner_version(self, query): 244 | """ 245 | 获取所使用的 NeteaseCloudMusicApi 和 NeteaseCloudMusicApi_V8 版本号 246 | :param query: 247 | :return: 248 | """ 249 | result = self.ctx.call('NeteaseCloudMusicApi.inner_version') 250 | return result 251 | 252 | def login_cellphone(self, query): 253 | """ 254 | 手机号登录 255 | :param query: 256 | :return: 257 | """ 258 | result = self.call_api("/login/cellphone", query) 259 | 260 | # 自动 更新cookie 261 | if result["code"] == 200: 262 | if result.get("data").get("cookie"): 263 | # cookie_str = format_cookie_str(result.get("data").get("cookie")) 264 | cookie_str = result.get("data").get("cookie") 265 | result["data"]["cookie"] = cookie_str 266 | self.cookie = cookie_str 267 | return result 268 | 269 | def login_refresh(self, query): 270 | """ 271 | 刷新登录状态 272 | :param query: 273 | :return: 274 | """ 275 | result = self.call_api("/login/refresh", query) 276 | 277 | # 自动 更新cookie 278 | # if result["code"] == 200: 279 | # if result.get("data").get("cookie"): 280 | # # cookie_str = format_cookie_str(result.get("data").get("cookie")) 281 | # cookie_str = result.get("data").get("cookie") 282 | # result["data"]["cookie"] = cookie_str 283 | # pprint(cookie_str) 284 | # self.cookie = cookie_str 285 | return result 286 | -------------------------------------------------------------------------------- /plugins.v2/syncmusiclist/netcloudmusic/utils.py: -------------------------------------------------------------------------------- 1 | from pprint import pprint 2 | 3 | 4 | def format_cookie_str(cookie_str: str) -> str: 5 | """ 6 | 格式化cookie字符串 7 | 功能 8 | 处理以逗号分割的cookie字符串 9 | 删除max-age为0的cookie 10 | 注意: 11 | 传入cookie字符串必须是以 逗号+空格 或 分号+空格 分割的规范cookie字符串 12 | :param cookie_str: 13 | :return: 格式化后的cookie str 14 | """ 15 | 16 | if not cookie_str: 17 | return "" 18 | 19 | # 解析cookie字符串 20 | cookie_dict = prase_cookie_str(cookie_str) 21 | 22 | cookie_valid_dict = {} 23 | # 删除max-age为0的cookie 24 | for item in cookie_dict.keys(): 25 | max_age = cookie_dict[item].get("Max-Age") 26 | if max_age: 27 | max_age = int(max_age) 28 | if max_age != 0: 29 | cookie_valid_dict[item] = cookie_dict[item] 30 | 31 | # 重新拼接cookie字符串 32 | cookie = "" 33 | for item in cookie_valid_dict.keys(): 34 | cookie += item + "=" + cookie_valid_dict[item]["value"] + "; " 35 | for key in cookie_valid_dict[item].keys(): 36 | if key != "value": 37 | cookie += key + "=" + cookie_valid_dict[item][key] + "; " 38 | 39 | return cookie[: -2] 40 | 41 | 42 | def prase_cookie_str(cookie_str: str) -> dict: 43 | """ 44 | 解析cookie字符串 45 | 功能 46 | 处理以逗号分割的cookie字符串 47 | 注意: 48 | 传入cookie字符串必须是以 逗号+空格 或 分号+空格 分割的规范cookie字符串 49 | :param cookie_str: 50 | :return: cookie dict 51 | """ 52 | if not cookie_str: 53 | return {} 54 | 55 | # 解决用逗号分割的问题 56 | cookie_part = [] 57 | for item in cookie_str.split(", "): 58 | cookie_part.extend(item.split("; ")) 59 | 60 | cookies = [] 61 | for item in cookie_part: 62 | if "=" not in item: 63 | # 属于上一个cookie的一部分 64 | cookies[-1] = cookies[-1] + item 65 | else: 66 | cookies.append(item) 67 | 68 | cookie_dict = {} 69 | 70 | current_name = "" 71 | for cookie in cookies: 72 | # print(cookie) 73 | if cookie[-1] == "=": 74 | name = cookie[:-1] 75 | value = "" 76 | else: 77 | part = cookie.split("=") 78 | name = part[0] 79 | value = part[1] 80 | 81 | if name in ["Max-Age", "Expires", "Path", "Domain"]: 82 | cookie_dict[current_name][name] = value 83 | else: 84 | cookie_dict[name] = {"value": value} 85 | current_name = name 86 | 87 | return cookie_dict 88 | 89 | 90 | if __name__ == '__main__': 91 | cookie = ("MUSIC_R_T=1579622000495; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; " 92 | "Path=/openapi/clientlog; Domain=.music.163.com, MUSIC_A_T=1579621885297; Max-Age=2147483647; Expires=Wed, " 93 | "02 Jan 2092 11:39:38 GMT; Path=/wapi/feedback; Domain=.music.163.com, __remember_me=true; " 94 | "Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; Path=/; Domain=.music.163.com, " 95 | "MUSIC_A_T=1579621885297; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; Path=/api/feedback; " 96 | "Domain=.music.163.com, MUSIC_A_T=1579621885297; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; " 97 | "Path=/eapi/clientlog; Domain=.music.163.com, MUSIC_A_T=1579621885297; Max-Age=2147483647; Expires=Wed, " 98 | "02 Jan 2092 11:39:38 GMT; Path=/api/clientlog; Domain=.music.163.com, MUSIC_R_T=1579622000495; " 99 | "Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; Path=/wapi/feedback; Domain=.music.163.com, " 100 | "MUSIC_A_T=1579621885297; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; Path=/weapi/clientlog; " 101 | "Domain=.music.163.com, MUSIC_R_T=1579622000495; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; " 102 | "Path=/neapi/feedback; Domain=.music.163.com, MUSIC_R_T=1579622000495; Max-Age=2147483647; Expires=Wed, " 103 | "02 Jan 2092 11:39:38 GMT; Path=/eapi/clientlog; Domain=.music.163.com, MUSIC_R_T=1579622000495; " 104 | "Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; Path=/api/feedback; Domain=.music.163.com, " 105 | "MUSIC_A_T=1579621885297; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; Path=/weapi/feedback; " 106 | "Domain=.music.163.com, MUSIC_R_T=1579622000495; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; " 107 | "Path=/eapi/feedback; Domain=.music.163.com, MUSIC_A_T=1579621885297; Max-Age=2147483647; Expires=Wed, " 108 | "02 Jan 2092 11:39:38 GMT; Path=/neapi/clientlog; Domain=.music.163.com, MUSIC_R_T=1579622000495; " 109 | "Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; Path=/wapi/clientlog; Domain=.music.163.com, " 110 | "MUSIC_A_T=1579621885297; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; Path=/wapi/clientlog; " 111 | "Domain=.music.163.com, MUSIC_R_T=1579622000495; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; " 112 | "Path=/weapi/feedback; Domain=.music.163.com, NMTID=00OLqRn-wykrFFXdElLpZA3_-aaQtIAAAGMbJSp9A; " 113 | "Max-Age=315360000; Expires=Mon, 12 Dec 2033 08:25:31 GMT; Path=/; Domain=music.163.com, " 114 | "__csrf=4d5e515015723fd3d7edaa5b05f35b4d; Max-Age=1296010; Expires=Sat, 30 Dec 2023 08:25:41 GMT; Path=/; " 115 | "Domain=.music.163.com, MUSIC_R_T=1579622000495; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; " 116 | "Path=/neapi/clientlog; Domain=.music.163.com, MUSIC_A_T=1579621885297; Max-Age=2147483647; Expires=Wed, " 117 | "02 Jan 2092 11:39:38 GMT; Path=/openapi/clientlog; Domain=.music.163.com, MUSIC_A_T=1579621885297; " 118 | "Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; Path=/eapi/feedback; Domain=.music.163.com, " 119 | "MUSIC_R_T=1579622000495; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; Path=/weapi/clientlog; " 120 | "Domain=.music.163.com, MUSIC_R_T=1579622000495; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; " 121 | "Path=/api/clientlog; Domain=.music.163.com, MUSIC_SNS=; Max-Age=0; Expires=Fri, 15 Dec 2023 08:25:31 GMT; " 122 | "Path=/, " 123 | "MUSIC_U=00CCEEF2F7A9825637C9869A455B5CA8E009D905415134A7EDAC2E404A940B2D58BFF7129A413193E9A8FD6D1D497E1E8E9023611BA91D2CB28FA94B53DBE4C42699A30FF1448C8EFAF5B00E73ADD353C52F2E004C094AEAC4BA4D83C6FFBB4CD532DEEAEA8D5584E69AC78110BBA682829C263DA72F5AA290AD826A47F640CA3903AC652E4DDE946ACC4EB8A63E5853FA695B480A919CF84498B7084C5CA9A91297F2CF5AF45C2D545AC0D5C03A1641306BAC0FB6FFD57BC653A91F2483FB52BFE85DE39280B012BC036DF244883D9700480E5FDDCD5A417C60241AE08CD6AA84BFC1C8890AE4A08286144D9D1146E33C67CF7797CDB5A961C85DB5AC492B232601D80D4DB07E4F170F635ABC01E080B4D32408FA0698DAD95AD80CDB99F2F672638048F5116214319175B596BF68B2A7A0269746EABFD919D62C165353725E6B1253A7C5D6774D453DDDCC28524D3378; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; Path=/; Domain=.music.163.com, MUSIC_A_T=1579621885297; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; Path=/neapi/feedback; Domain=.music.163.com") 124 | pprint(prase_cookie_str(cookie)) 125 | -------------------------------------------------------------------------------- /plugins.v2/syncmusiclist/plex_music.py: -------------------------------------------------------------------------------- 1 | from urllib.parse import urlencode 2 | 3 | from app.log import logger 4 | from app.schemas import MediaServerLibrary 5 | from app.modules.plex import Plex 6 | from plexapi.myplex import MyPlexAccount 7 | from plexapi.library import Hub 8 | 9 | 10 | class PlexMusic(Plex): 11 | """API for Plex 12 | 继承根项目, 实现音乐库相关的api 13 | """ 14 | 15 | def __init__(self, host: str = None, token: str = None, play_host: str = None, 16 | sync_libraries: list = None, **kwargs): 17 | Plex.__init__(self, host=host, token=token) 18 | self.music_libraries = [] 19 | self.music_playlists = [] 20 | self.music_names = [] 21 | 22 | def get_user_name(self): 23 | account = MyPlexAccount(self._token) 24 | return account.username 25 | 26 | def get_music_library(self): 27 | """ 28 | 获取媒体服务器所有音乐类型媒体库列表 29 | """ 30 | if not self._plex: 31 | return [] 32 | try: 33 | _libraries = self._plex.library.sections() 34 | except Exception as err: 35 | logger.error(f"Plex获取媒体服务器所有媒体库列表出错:{str(err)}") 36 | return [] 37 | for library in _libraries: 38 | match library.type: 39 | case "artist": 40 | library_type = '音乐' 41 | case _: 42 | continue 43 | self.music_names.append(library.title) 44 | self.music_libraries.append( 45 | MediaServerLibrary( 46 | id=library.key, 47 | name=library.title, 48 | path=library.locations, 49 | type=library_type 50 | ) 51 | ) 52 | return self.music_libraries 53 | 54 | def get_playlists(self): 55 | """获取播放列表""" 56 | try: 57 | playlists = self._plex.playlists() 58 | except: 59 | playlists = [] 60 | for playlist in playlists: 61 | if playlist.isAudio: 62 | # music_playlists.append( 63 | # { 64 | # "name": playlist.title, 65 | # "id": playlist.ratingKey, 66 | # "url": playlist.thumbUrl, 67 | # } 68 | # ) 69 | self.music_playlists.append(playlist.title) 70 | return self.music_playlists 71 | 72 | def get_tracks_by_playlist(self, playlist_title): 73 | """获取播放列表的详细歌单""" 74 | if playlist_title not in self.music_playlists: 75 | logger.warn(f"Plex媒体库中播放列表为:{self.music_playlists}\n 不存在: {playlist_title}, 稍后会自动创建,如果失败请手动创建") 76 | return [] 77 | playlist = self._plex.playlist(playlist_title) 78 | # 获取歌单中的歌曲 79 | tracks = playlist.items() 80 | music_names = [i.title for i in tracks] 81 | return music_names 82 | 83 | def create_playlist(self, title, items): 84 | """创建播放列表""" 85 | self._plex.createPlaylist(title=title, items=items, libtype='track') 86 | 87 | def set_tracks_to_playlist(self, playlist_title, tracks): 88 | """添加歌曲到歌单中""" 89 | playlist = self._plex.playlist(playlist_title) 90 | playlist.addItems(tracks) 91 | 92 | def search(self, query, mediatype=None, limit=None, sectionId=None): 93 | """ Returns a list of media items or filter categories from the resulting 94 | `Hub Search `_ 95 | against all items in your Plex library. This searches genres, actors, directors, 96 | playlists, as well as all the obvious media titles. It performs spell-checking 97 | against your search terms (because KUROSAWA is hard to spell). It also provides 98 | contextual search results. So for example, if you search for 'Pernice', it’ll 99 | return 'Pernice Brothers' as the artist result, but we’ll also go ahead and 100 | return your most-listened to albums and tracks from the artist. If you type 101 | 'Arnold' you’ll get a result for the actor, but also the most recently added 102 | movies he’s in. 103 | 104 | Parameters: 105 | query (str): Query to use when searching your library. 106 | mediatype (str, optional): Limit your search to the specified media type. 107 | actor, album, artist, autotag, collection, director, episode, game, genre, 108 | movie, photo, photoalbum, place, playlist, shared, show, tag, track 109 | limit (int, optional): Limit to the specified number of results per Hub. 110 | sectionId (int, optional): The section ID (key) of the library to search within. 111 | """ 112 | results = [] 113 | params = { 114 | 'query': query, 115 | 'X-Plex-Token': self._token, 116 | 'includeCollections': 1, 117 | 'includeExternalMedia': 1} 118 | if limit: 119 | params['limit'] = limit 120 | if sectionId: 121 | params['sectionId'] = sectionId 122 | 123 | 124 | key = f'/hubs/search?{urlencode(params)}' 125 | for hub in self._plex.fetchItems(key, Hub): 126 | if mediatype: 127 | if hub.type == mediatype: 128 | return hub.items 129 | else: 130 | results += hub.items 131 | return results 132 | 133 | def search_music(self, name_singer, exact_match=True): 134 | """通过歌曲名在库中进行搜索""" 135 | name = name_singer[0] 136 | singers = name_singer[1] 137 | if len(self.music_libraries) == 1: 138 | search_res = self.search(name, mediatype='track', limit=20, sectionId=int(self.music_libraries[0].id)) 139 | else: 140 | search_res = self.search(name, mediatype='track', limit=20) 141 | add_items = [] 142 | if len(search_res) > 1: 143 | if exact_match: 144 | add_items = [] 145 | bitrate = 0 146 | # 通过歌手过滤 147 | for i in search_res: 148 | if i.grandparentTitle or i.grandparentTitle in singers: 149 | # add 150 | if i.media[0].bitrate or 1 > bitrate: 151 | bitrate = i.media[0].bitrate or 1 152 | add_items = [i] 153 | else: 154 | str_arts = i.originalTitle or i.grandparentTitle 155 | for singer in singers: 156 | if singer in str_arts: 157 | # add 158 | if i.media[0].bitrate > bitrate: 159 | bitrate = i.media[0].bitrate or 1 160 | add_items = [i] 161 | else: 162 | add_items = search_res[:1] 163 | return add_items 164 | 165 | 166 | if __name__ == '__main__': 167 | pm = PlexMusic() 168 | ml = pm.get_user_name() 169 | pm.get_playlists() 170 | pm.get_tracks_by_playlist('经典华语') 171 | res = pm.search_music(['雨蝶', ['刘君']]) 172 | print(res) 173 | -------------------------------------------------------------------------------- /plugins.v2/syncmusiclist/requirement.txt: -------------------------------------------------------------------------------- 1 | py-mini-racer==0.6.0 2 | diskcache==5.6.3 -------------------------------------------------------------------------------- /plugins.v2/syncmusiclist/requirements.txt: -------------------------------------------------------------------------------- 1 | py-mini-racer==0.6.0 2 | diskcache==5.6.3 -------------------------------------------------------------------------------- /plugins.v2/syncmusiclist/utils.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | def sub_str(text): 5 | return re.sub(r'\s*[\(\(\[【<《][^\)\)\]】>》]*[\)\)\]】>》]\s*', '', text) 6 | 7 | def contains_chinese(text): 8 | """判断字符串是否包含中文字符""" 9 | pattern = re.compile(r'[\u4e00-\u9fa5]') 10 | return bool(pattern.search(text)) 11 | 12 | def extract_chinese(text): 13 | """提取字符串中的中文字符""" 14 | pattern = re.compile(r'[\u4e00-\u9fa5]+') 15 | return pattern.findall(text)[0] 16 | 17 | def change_str(text): 18 | text = sub_str(text) 19 | if contains_chinese(text): 20 | text = extract_chinese(text) 21 | return text 22 | 23 | -------------------------------------------------------------------------------- /plugins/maoyanrank/__init__.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import json 3 | import random 4 | import re 5 | from threading import Event 6 | from typing import Tuple, List, Dict, Any 7 | 8 | import pytz 9 | from apscheduler.schedulers.background import BackgroundScheduler 10 | from apscheduler.triggers.cron import CronTrigger 11 | from lxml import etree 12 | from playwright.sync_api import sync_playwright 13 | 14 | from app.chain.download import DownloadChain 15 | from app.chain.subscribe import SubscribeChain 16 | from app.core.config import settings 17 | from app.core.context import MediaInfo 18 | from app.core.metainfo import MetaInfo 19 | from app.log import logger 20 | from app.plugins import _PluginBase 21 | from app.schemas import MediaType 22 | 23 | 24 | class MaoyanRank(_PluginBase): 25 | """ 26 | 获取猫眼的排行榜进行订阅,建议每天一次 27 | 电影获取的url: https://piaofang.maoyan.com/dashboard-ajax/movie 28 | 电视剧获取的url: https://piaofang.maoyan.com/dashboard/webHeatData?showDate=20240223&seriesType=0&platformType=0 29 | 参数 showDate: 时间具体到天 30 | 参数 seriesType: 代表类型 0: 电视剧 1: 网络剧 2: 综艺 不传递-1代表电视剧+网络剧 31 | 参数 platformType: 代表平台 0 全网 3 腾讯视频 2 爱奇艺 1 优酷 7 芒果 5 搜狐 4 乐视 6 PPTV 32 | 33 | 详情链接: 34 | https://piaofang.maoyan.com/dashboard/movie?movieId=1489349 35 | https://piaofang.maoyan.com/dashboard/web-heat?movieId=1484643 36 | 37 | """ 38 | # 插件名称 39 | plugin_name = "猫眼榜单订阅" 40 | # 插件描述 41 | plugin_desc = "监控猫眼数据,自动添加订阅。" 42 | # 插件图标 43 | plugin_icon = "https://raw.githubusercontent.com/baozaodetudou/MoviePilot-Plugins/main/icons/maoyan.jpg" 44 | # 插件版本 45 | plugin_version = "0.8" 46 | # 插件作者 47 | plugin_author = "逗猫" 48 | # 作者主页 49 | author_url = "https://github.com/baozaodetudou" 50 | # 插件配置项ID前缀 51 | plugin_config_prefix = "maoyanrank_" 52 | # 加载顺序 53 | plugin_order = 6 54 | # 可使用的用户级别 55 | auth_level = 2 56 | 57 | # 退出事件 58 | _event = Event() 59 | # 私有属性 60 | downloadchain: DownloadChain = None 61 | subscribechain: SubscribeChain = None 62 | _scheduler = None 63 | _enabled = False 64 | _onlyonce = False 65 | _cron = "" 66 | _clear = False 67 | _type = ['movie', 'web-heat'] 68 | _num = 10 69 | _seriesType = [0, 1, 2] 70 | _platform = 0 71 | 72 | def init_plugin(self, config: dict = None): 73 | self.downloadchain = DownloadChain() 74 | self.subscribechain = SubscribeChain() 75 | 76 | if config: 77 | self._enabled = config.get("enabled") 78 | self._cron = config.get("cron") 79 | self._clear = config.get("clear") 80 | self._onlyonce = config.get("onlyonce") 81 | 82 | self._type = config.get("type") 83 | self._num = config.get("num", 10) 84 | self._seriesType = config.get("seriesType") 85 | self._platform = config.get("platform", 0) 86 | 87 | # 停止现有任务 88 | self.stop_service() 89 | 90 | # 启动服务 91 | # 清理插件历史 92 | if self._clear: 93 | self.del_data(key="history") 94 | self._clear = False 95 | self.__update_config() 96 | logger.info("历史清理完成") 97 | 98 | if self._enabled or self._onlyonce: 99 | self._scheduler = BackgroundScheduler(timezone=settings.TZ) 100 | # 周期执行 101 | if self._cron: 102 | logger.info(f"猫眼榜单订阅服务启动,周期:{self._cron}") 103 | try: 104 | self._scheduler.add_job(func=self.__refresh_maoyan, 105 | trigger=CronTrigger.from_crontab(self._cron), 106 | name="猫眼榜单订阅") 107 | except Exception as e: 108 | logger.error(f"猫眼榜单订阅服务启动失败,错误信息:{str(e)}") 109 | self.systemmessage.put(f"猫眼榜单订阅服务启动失败,错误信息:{str(e)}") 110 | else: 111 | self._scheduler.add_job(func=self.__refresh_maoyan, trigger=CronTrigger.from_crontab("0 9 * * *"), 112 | name="猫眼榜单订阅") 113 | logger.info("猫眼榜单订阅服务启动,周期:每天 09:00") 114 | 115 | # 一次性执行 116 | if self._onlyonce: 117 | logger.info("猫眼榜单订阅服务启动,立即运行一次") 118 | self._scheduler.add_job(func=self.__refresh_maoyan, trigger='date', 119 | run_date=datetime.datetime.now( 120 | tz=pytz.timezone(settings.TZ)) + datetime.timedelta(seconds=3) 121 | ) 122 | # 关闭一次性开关 123 | self._onlyonce = False 124 | # 保存配置 125 | self.__update_config() 126 | 127 | if self._scheduler.get_jobs(): 128 | # 启动服务 129 | self._scheduler.print_jobs() 130 | self._scheduler.start() 131 | 132 | def get_state(self) -> bool: 133 | return self._enabled 134 | 135 | @staticmethod 136 | def get_command() -> List[Dict[str, Any]]: 137 | pass 138 | 139 | def get_api(self) -> List[Dict[str, Any]]: 140 | pass 141 | 142 | def get_form(self) -> Tuple[List[dict], Dict[str, Any]]: 143 | return [ 144 | { 145 | 'component': 'VForm', 146 | 'content': [ 147 | { 148 | 'component': 'VRow', 149 | 'content': [ 150 | { 151 | 'component': 'VCol', 152 | 'props': { 153 | 'cols': 12, 154 | 'md': 6 155 | }, 156 | 'content': [ 157 | { 158 | 'component': 'VSwitch', 159 | 'props': { 160 | 'model': 'enabled', 161 | 'label': '启用插件', 162 | } 163 | } 164 | ] 165 | }, 166 | { 167 | 'component': 'VCol', 168 | 'props': { 169 | 'cols': 12, 170 | 'md': 6 171 | }, 172 | 'content': [ 173 | { 174 | 'component': 'VSwitch', 175 | 'props': { 176 | 'model': 'onlyonce', 177 | 'label': '立即运行一次', 178 | } 179 | } 180 | ] 181 | } 182 | ] 183 | }, 184 | { 185 | 'component': 'VRow', 186 | 'content': [ 187 | { 188 | 'component': 'VCol', 189 | 'props': { 190 | 'cols': 12, 191 | 'md': 6 192 | }, 193 | 'content': [ 194 | { 195 | 'component': 'VTextField', 196 | 'props': { 197 | 'model': 'cron', 198 | 'label': '执行周期', 199 | 'placeholder': '5位cron表达式,留空自动' 200 | } 201 | } 202 | ] 203 | }, 204 | { 205 | 'component': 'VCol', 206 | 'props': { 207 | 'cols': 12, 208 | 'md': 6 209 | }, 210 | 'content': [ 211 | { 212 | 'component': 'VSwitch', 213 | 'props': { 214 | 'model': 'clear', 215 | 'label': '清理历史记录', 216 | } 217 | } 218 | ] 219 | } 220 | ] 221 | }, 222 | { 223 | 'component': 'VRow', 224 | 'content': [ 225 | { 226 | 'component': 'VCol', 227 | 'props': { 228 | 'cols': 12, 229 | 'md': 6 230 | }, 231 | 'content': [ 232 | { 233 | 'component': 'VSelect', 234 | 'props': { 235 | 'chips': True, 236 | 'multiple': True, 237 | 'model': 'type', 238 | 'label': '订阅类型', 239 | 'items': [ 240 | {'title': '电影票房榜单', 'value': 'movie'}, 241 | {'title': '网播热度榜单', 'value': 'web-heat'} 242 | ] 243 | } 244 | } 245 | ] 246 | }, 247 | { 248 | 'component': 'VCol', 249 | 'props': { 250 | 'cols': 12, 251 | 'md': 4 252 | }, 253 | 'content': [ 254 | { 255 | 'component': 'VSelect', 256 | 'props': { 257 | 'multiple': False, 258 | 'chips': True, 259 | 'model': 'num', 260 | 'label': '榜单条数', 261 | 'items': [ 262 | {'title': '3', 'value': 3}, 263 | {'title': '5', 'value': 5}, 264 | {'title': '10', 'value': 10} 265 | ] 266 | } 267 | } 268 | ] 269 | } 270 | ] 271 | }, 272 | { 273 | 'component': 'VRow', 274 | 'content': [ 275 | { 276 | 'component': 'VCol', 277 | 'props': { 278 | 'cols': 12, 279 | 'md': 6 280 | }, 281 | 'content': [ 282 | { 283 | 'component': 'VSelect', 284 | 'props': { 285 | 'chips': True, 286 | 'multiple': True, 287 | 'model': 'seriesType', 288 | 'label': '网播剧类型', 289 | 'items': [ 290 | {'title': '电视剧', 'value': 0}, 291 | {'title': '网络剧', 'value': 1}, 292 | {'title': '综艺', 'value': 2} 293 | ] 294 | } 295 | } 296 | ] 297 | }, 298 | { 299 | 'component': 'VCol', 300 | 'props': { 301 | 'cols': 12, 302 | 'md': 4 303 | }, 304 | 'content': [ 305 | { 306 | 'component': 'VSelect', 307 | 'props': { 308 | 'multiple': False, 309 | 'chips': True, 310 | 'model': 'platform', 311 | 'label': '流媒体平台', 312 | 'items': [ 313 | {'title': '全网', 'value': 0}, 314 | {'title': '优酷', 'value': 1}, 315 | {'title': '爱奇艺', 'value': 2}, 316 | {'title': '腾讯视频', 'value': 3}, 317 | {'title': '乐视', 'value': 4}, 318 | {'title': '搜狐', 'value': 5}, 319 | {'title': 'PPTV', 'value': 6}, 320 | {'title': '芒果', 'value': 7} 321 | ] 322 | } 323 | } 324 | ] 325 | } 326 | ] 327 | }, 328 | ] 329 | } 330 | ], { 331 | "enabled": False, 332 | "onlyonce": False, 333 | "cron": "", 334 | "clear": False, 335 | "type": ['movie', 'web-heat'], 336 | "num": 10, 337 | "seriesType": [0, 1, 2], 338 | "platform": 0, 339 | } 340 | 341 | def get_page(self) -> List[dict]: 342 | """ 343 | 拼装插件详情页面,需要返回页面配置,同时附带数据 344 | """ 345 | # 查询历史记录 346 | historys = self.get_data('history') 347 | if not historys: 348 | return [ 349 | { 350 | 'component': 'div', 351 | 'text': '暂无数据', 352 | 'props': { 353 | 'class': 'text-center', 354 | } 355 | } 356 | ] 357 | # 数据按时间降序排序 358 | historys = sorted(historys, key=lambda x: x.get('time'), reverse=True) 359 | # 拼装页面 360 | contents = [] 361 | for history in historys: 362 | title = history.get("title") 363 | poster = history.get("poster") 364 | mtype = history.get("type") 365 | time_str = history.get("time") 366 | tmdb_id = history.get("tmdbid") 367 | release_info = history.get("releaseInfo") 368 | platform = history.get("platformDesc") 369 | if mtype == MediaType.TV.value: 370 | href = f"https://www.themoviedb.org/tv/{tmdb_id}" 371 | else: 372 | href = f"https://www.themoviedb.org/movie/{tmdb_id}" 373 | contents.append( 374 | { 375 | 'component': 'VCard', 376 | 'content': [ 377 | { 378 | 'component': 'div', 379 | 'props': { 380 | 'class': 'd-flex justify-space-start flex-nowrap flex-row', 381 | }, 382 | 'content': [ 383 | { 384 | 'component': 'div', 385 | 'content': [ 386 | { 387 | 'component': 'VImg', 388 | 'props': { 389 | 'src': poster, 390 | 'height': 120, 391 | 'width': 80, 392 | 'aspect-ratio': '2/3', 393 | 'class': 'object-cover shadow ring-gray-500', 394 | 'cover': True 395 | } 396 | } 397 | ] 398 | }, 399 | { 400 | 'component': 'div', 401 | 'content': [ 402 | { 403 | 'component': 'VCardSubtitle', 404 | 'props': { 405 | 'class': 'pa-2 font-bold break-words whitespace-break-spaces' 406 | }, 407 | 'content': [ 408 | { 409 | 'component': 'a', 410 | 'props': { 411 | 'href': href, 412 | 'target': '_blank' 413 | }, 414 | 'text': title 415 | } 416 | ] 417 | }, 418 | { 419 | 'component': 'VCardText', 420 | 'props': { 421 | 'class': 'pa-0 px-2' 422 | }, 423 | 'text': f'{release_info}' 424 | }, 425 | { 426 | 'component': 'VCardText', 427 | 'props': { 428 | 'class': 'pa-0 px-2' 429 | }, 430 | 'text': f'平台:{platform}' 431 | }, 432 | { 433 | 'component': 'VCardText', 434 | 'props': { 435 | 'class': 'pa-0 px-2' 436 | }, 437 | 'text': f'类型:{mtype}' 438 | }, 439 | { 440 | 'component': 'VCardText', 441 | 'props': { 442 | 'class': 'pa-0 px-2' 443 | }, 444 | 'text': f'订阅时间:{time_str}' 445 | } 446 | ] 447 | } 448 | ] 449 | } 450 | ] 451 | } 452 | ) 453 | 454 | return [ 455 | { 456 | 'component': 'div', 457 | 'props': { 458 | 'class': 'grid gap-3 grid-info-card', 459 | }, 460 | 'content': contents 461 | } 462 | ] 463 | 464 | def stop_service(self): 465 | """ 466 | 停止服务 467 | """ 468 | try: 469 | if self._scheduler: 470 | self._scheduler.remove_all_jobs() 471 | if self._scheduler.running: 472 | self._event.set() 473 | self._scheduler.shutdown() 474 | self._event.clear() 475 | self._scheduler = None 476 | except Exception as e: 477 | print(str(e)) 478 | 479 | def __update_config(self): 480 | """ 481 | 列新配置 482 | """ 483 | 484 | self.update_config({ 485 | "enabled": self._enabled, 486 | "cron": self._cron, 487 | "clear": self._clear, 488 | "onlyonce": self._onlyonce, 489 | "type": self._type, 490 | "num": self._num, 491 | "seriesType": self._seriesType, 492 | "platform": self._platform, 493 | }) 494 | 495 | def __refresh_maoyan(self): 496 | """ 497 | 刷新猫眼榜单数据 498 | 电影获取的url: 499 | https://piaofang.maoyan.com/dashboard-ajax/movie 500 | 电视剧获取的url: 501 | https://piaofang.maoyan.com/dashboard/webHeatData?showDate=20240223&seriesType=0&platformType=0 502 | 参数 showDate: 时间具体到天 503 | 参数 seriesType: 代表类型 0: 电视剧 1: 网络剧 2: 综艺 不传递-1代表电视剧+网络剧 504 | 参数 platformType: 代表平台 0 全网 3 腾讯视频 2 爱奇艺 1 优酷 7 芒果 5 搜狐 4 乐视 6 PPTV 505 | """ 506 | logger.info(f"开始刷新猫眼榜单...") 507 | # 获取当前日期时间 508 | current_time = datetime.datetime.now() 509 | nums = self._num 510 | # 511 | history: List[dict] = self.get_data('history') or [] 512 | # 513 | movie_url = '' 514 | tv_urls = [] 515 | if 'movie' in self._type: 516 | movie_url = 'https://piaofang.maoyan.com/dashboard-ajax/movie' 517 | if 'web-heat' in self._type: 518 | # 获取当前日期时间格式化为字符串 519 | url_header = 'https://piaofang.maoyan.com/dashboard/webHeatData' 520 | format_date = current_time.strftime("%Y%m%d") 521 | if len(self._seriesType) == 3: 522 | tv_urls = [ 523 | f'{url_header}?showDate={format_date}&platformType={self._platform}', 524 | f'{url_header}?showDate={format_date}&seriesType=2&platformType={self._platform}', 525 | ] 526 | elif all(i in self._seriesType for i in [0, 1]): 527 | tv_urls = [ 528 | f'{url_header}?showDate={format_date}&platformType={self._platform}', 529 | ] 530 | else: 531 | for series in self._seriesType: 532 | tv_urls.append( 533 | f'{url_header}?showDate={format_date}&seriesType={series}&platformType={self._platform}', 534 | ) 535 | tv_list = [] 536 | movie_list = [] 537 | try: 538 | movie_list, tv_list = self.__get_url_info(movie_url, tv_urls, nums) 539 | except Exception as e: 540 | logger.warn(e) 541 | self.set_sub(movie_list, history, MediaType.MOVIE) 542 | self.set_sub(tv_list, history, MediaType.TV) 543 | # 保存历史记录 544 | self.save_data('history', history) 545 | logger.info(f"猫眼订阅刷新完成") 546 | 547 | def set_sub(self, addr_list, history, mtype): 548 | # 获取当前日期时间 549 | current_time = datetime.datetime.now() 550 | for addr in addr_list: 551 | try: 552 | title = addr.get('title') 553 | try: 554 | # 计算日期,获取年份信息 555 | subtract = int(''.join(re.findall(r'\d', addr.get('releaseInfo')))) 556 | target_time = current_time - datetime.timedelta(days=subtract) 557 | year = target_time.year 558 | except Exception as e: 559 | logger.warn(e) 560 | year = None 561 | # 元数据 562 | meta = MetaInfo(title) 563 | meta.year = year 564 | unique_flag = f"maoyanrank: {mtype}_{title}_{year}" 565 | # 检查是否已处理过 566 | if unique_flag in [h.get("unique") for h in history]: 567 | continue 568 | # 匹配媒体信息 569 | mediainfo: MediaInfo = self.chain.recognize_media(meta=meta, mtype=mtype, cache=False) 570 | if not mediainfo: 571 | logger.warn(f'未识别到媒体信息,标题:{title},年份:{year}') 572 | continue 573 | # 查询缺失的媒体信息 574 | exist_flag, _ = self.downloadchain.get_no_exists_info(meta=meta, mediainfo=mediainfo) 575 | if exist_flag: 576 | logger.info(f'{mediainfo.title_year} 媒体库中已存在') 577 | continue 578 | # 判断用户是否已经添加订阅 579 | if self.subscribechain.exists(mediainfo=mediainfo, meta=meta): 580 | logger.info(f'{mediainfo.title_year} 订阅已存在') 581 | continue 582 | # 添加订阅 583 | season = meta.begin_season if mtype == MediaType.TV else None 584 | self.subscribechain.add(title=mediainfo.title, 585 | year=mediainfo.year, 586 | mtype=mediainfo.type, 587 | tmdbid=mediainfo.tmdb_id, 588 | season=season, 589 | exist_ok=True, 590 | username="猫眼订阅") 591 | # 存储历史记录 592 | history.append({ 593 | "title": title, 594 | "releaseInfo": addr.get('releaseInfo'), 595 | "platformDesc": addr.get('platformDesc', '未知'), 596 | "type": mediainfo.type.value, 597 | "year": mediainfo.year, 598 | "poster": mediainfo.get_poster_image(), 599 | "overview": mediainfo.overview, 600 | "tmdbid": mediainfo.tmdb_id, 601 | "time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), 602 | "unique": unique_flag 603 | }) 604 | except Exception as e: 605 | logger.error(str(e)) 606 | 607 | def __get_url_info(self, movie_url, tv_urls, num=10): 608 | """ 609 | 根据url获取 610 | """ 611 | movies_list = [] 612 | tv_list = [] 613 | 614 | with sync_playwright() as p: 615 | browser = p.chromium.launch(headless=False) 616 | try: 617 | context = browser.new_context(user_agent=self.get_random_user_agent()) 618 | page1 = context.new_page() 619 | page2 = context.new_page() 620 | if movie_url: 621 | try: 622 | # 打开网页 623 | page1.goto(movie_url) 624 | # 获取页面内容 625 | html_text1 = page1.content() 626 | body = etree.HTML(html_text1) 627 | res = json.loads(str(body.xpath('//body//text()')[0])) 628 | data = res.get('movieList', {}).get('list', []) 629 | 630 | def info(movie): 631 | infos = movie.get('movieInfo') 632 | return { 633 | "title": infos.get('movieName'), 634 | "releaseInfo": infos.get('releaseInfo'), 635 | } 636 | 637 | movies_list = [info(i) for i in data][:num] 638 | except Exception as e: 639 | logger.error(f"获取网页源码失败: {str(e)}") 640 | if tv_urls: 641 | for tv_url in tv_urls: 642 | try: 643 | # 打开网页 644 | page2.goto(tv_url) 645 | # 获取页面内容 646 | html_text2 = page2.content() 647 | body = etree.HTML(html_text2) 648 | res = json.loads(str(body.xpath('//body//text()')[0])) 649 | data = res.get('dataList', {}).get('list', []) 650 | 651 | def tv_info(tv): 652 | infos = tv.get('seriesInfo') 653 | return { 654 | "title": infos.get('name'), 655 | "releaseInfo": infos.get('releaseInfo'), 656 | "platformDesc": infos.get('platformDesc'), 657 | } 658 | 659 | tv_list.extend([tv_info(i) for i in data][:num]) 660 | except Exception as e: 661 | logger.error(f"获取网页源码失败: {str(e)}") 662 | # 使用字典推导式和集合保持唯一性 663 | unique_dicts = {item['title']: item for item in tv_list}.values() 664 | # 转回列表形式 665 | tv_list = list(unique_dicts) 666 | except Exception as e: 667 | logger.error(f"获取网页源码失败: {str(e)}") 668 | finally: 669 | # 关闭页面 670 | browser.close() 671 | return movies_list, tv_list 672 | 673 | @staticmethod 674 | def get_random_user_agent(): 675 | user_agents = [ 676 | "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0", 677 | "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0", 678 | "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36", 679 | ] 680 | return random.choice(user_agents) 681 | -------------------------------------------------------------------------------- /plugins/syncmusiclist/QQmusic.py: -------------------------------------------------------------------------------- 1 | import re 2 | import json 3 | import uuid 4 | 5 | from app.plugins.syncmusiclist.utils import sub_str, change_str 6 | from app.utils.http import RequestUtils 7 | 8 | 9 | class QQMusicApi(object): 10 | """ 11 | QQ音乐获取信息的api 12 | """ 13 | def __init__(self): 14 | self.req = None 15 | self.cookie = "" 16 | self.headers = {} 17 | self.set_session() 18 | 19 | def set_cookie(self, cookie): 20 | self.cookie = cookie 21 | 22 | def set_headers(self): 23 | self.headers = { 24 | "authority": "u6.y.qq.com", 25 | "User-Agent": "QQ音乐/73222 CFNetwork/1406.0.2 Darwin/22.4.0".encode("utf-8"), 26 | "Accept": "*/*", 27 | "Accept-Language": "zh-CN,zh-Hans;q=0.9", 28 | "Referer": "http://y.qq.com", 29 | "Content-Type": "application/json; charset=UTF-8", 30 | "Cookie": self.cookie, 31 | } 32 | 33 | def set_session(self): 34 | self.set_headers() 35 | self.req = RequestUtils(headers=self.headers) 36 | return self.req 37 | 38 | def get_playlist_by_id(self, play_id): 39 | """ 40 | 通过歌单id获取歌单列表 41 | """ 42 | _uuid = uuid.uuid1().__str__() 43 | url = "https://u.y.qq.com/cgi-bin/musicu.fcg" 44 | payload = { 45 | "getMusicPlaylist": { 46 | "module": "music.srfDissInfo.aiDissInfo", 47 | "method": "uniform_get_Dissinfo", 48 | "param": { 49 | "disstid": int(play_id), 50 | "userinfo": 1, 51 | "tag": 1, 52 | "is_pc": 1, 53 | "guid": _uuid, 54 | }, 55 | }, 56 | "comm": { 57 | "g_tk": 0, 58 | "uin": "", 59 | "format": "json", 60 | "ct": 6, 61 | "cv": 80600, 62 | "platform": "wk_v17", 63 | "uid": "", 64 | "guid": _uuid, 65 | }, 66 | } 67 | data = json.dumps(payload, ensure_ascii=False) 68 | res_json = self.req.post(url=url, data=data).json() 69 | playlist = res_json.get("getMusicPlaylist") 70 | if playlist["code"] == 0: 71 | lst = playlist.get('data', {}).get('songlist', []) 72 | else: 73 | lst = [] 74 | list_clear = [] 75 | for i in lst: 76 | # 正则处理 77 | name = sub_str(i.get('name')) 78 | # 多歌手处理 79 | ars = [change_str(ar.get('name')) for ar in i.get('singer')] 80 | list_clear.append([name, ars]) 81 | return list_clear 82 | 83 | 84 | if __name__ == '__main__': 85 | qq = QQMusicApi() 86 | res = qq.get_playlist_by_id('7039481526') 87 | print(res) 88 | 89 | -------------------------------------------------------------------------------- /plugins/syncmusiclist/__init__.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | import pytz 4 | from datetime import datetime, timedelta 5 | from threading import Event 6 | from typing import List, Tuple, Dict, Any, Optional 7 | from apscheduler.schedulers.background import BackgroundScheduler 8 | from apscheduler.triggers.cron import CronTrigger 9 | 10 | from app.core.config import settings 11 | from app.plugins import _PluginBase 12 | from typing import Any, List, Dict, Tuple 13 | from app.log import logger 14 | from app.plugins.syncmusiclist.QQmusic import QQMusicApi 15 | from app.plugins.syncmusiclist.cloudmusic import CloudMusic 16 | from app.plugins.syncmusiclist.emby_music import EmbyMusic 17 | from app.plugins.syncmusiclist.plex_music import PlexMusic 18 | 19 | 20 | class SyncMusicList(_PluginBase): 21 | # 插件名称 22 | plugin_name = "歌单同步工具" 23 | # 插件描述 24 | plugin_desc = "同步QQ&网易云歌单到plex&emby。" 25 | # 插件图标 26 | plugin_icon = "https://raw.githubusercontent.com/baozaodetudou/MoviePilot-Plugins/main/icons/music.png" 27 | # 插件版本 28 | plugin_version = "7.1" 29 | # 插件作者 30 | plugin_author = "逗猫" 31 | # 作者主页 32 | author_url = "https://github.com/baozaodetudou" 33 | # 插件配置项ID前缀 34 | plugin_config_prefix = "music_" 35 | # 加载顺序 36 | plugin_order = 17 37 | # 可使用的用户级别 38 | auth_level = 2 39 | 40 | # 私有属性 41 | _scheduler: Optional[BackgroundScheduler] = None 42 | # 启动 43 | _enabled = False 44 | # 运行一次 45 | _onlyonce = False 46 | # 定时 47 | _cron = None 48 | # 媒体服务器 49 | _media_server = [] 50 | # 精准匹配开关 51 | _exact_match = True 52 | # 网易云登录设置, 同步自己歌单需要登录,不是自己不需要登录 53 | _wylogin_user = '' 54 | _wylogin_password = '' 55 | # 56 | _wy_daily_list = False 57 | _wy_daily_song = False 58 | 59 | # 同步列表 60 | _wymusic_paths = "" 61 | _qqmusic_paths = "" 62 | # 退出事件 63 | _event = Event() 64 | 65 | def init_plugin(self, config: dict = None): 66 | # docker用默认路径 67 | _path = self.get_data_path() 68 | self.cm = CloudMusic(_path) 69 | self._wylogin_capt = False 70 | self._wylogin_pass = False 71 | # 获取用户名信息 72 | self._username = self.cm.login_status() 73 | 74 | 75 | # 读取配置 76 | if config: 77 | self._enabled = config.get("enabled") 78 | self._onlyonce = config.get("onlyonce") 79 | self._cron = config.get("cron") 80 | self._media_server = config.get("media_server") or [] 81 | self._exact_match = config.get("exact_match") or True 82 | self._wylogin_user = config.get("wylogin_user") or "" 83 | self._wylogin_password = config.get("wylogin_password") or "" 84 | self._wymusic_paths = config.get("wymusic_paths") or "" 85 | self._qqmusic_paths = config.get("qqmusic_paths") or "" 86 | self._wy_daily_list = config.get("wy_daily_list") or False 87 | self._wy_daily_song = config.get("wy_daily_song") or False 88 | 89 | 90 | if self._username: 91 | self._wylogin_status = False 92 | self._wyy_text = f"当前网抑云账号{self._username}登录成功,可以使用用户相关功能" 93 | else: 94 | if self._wylogin_user and self._wylogin_password: 95 | self.cm.login(self._wylogin_user, self._wylogin_password) 96 | self._username = self.cm.login_status() 97 | if self._username: 98 | self._wylogin_status = False 99 | self._wyy_text = f"当前网抑云账号{self._username}登录成功,可以使用用户相关功能" 100 | else: 101 | self._wylogin_status = True 102 | self._wyy_text = f"当前未登录网抑云账号,部分功能受限,请点击下方登录" 103 | 104 | 105 | # 停止现有任务 106 | self.stop_service() 107 | 108 | # 启动定时任务 & 立即运行一次 109 | if self._enabled or self._onlyonce: 110 | self._scheduler = BackgroundScheduler(timezone=settings.TZ) 111 | if self._cron: 112 | logger.info(f"歌单同步服务启动,周期:{self._cron}") 113 | try: 114 | self._scheduler.add_job(func=self.__run_sync_paylist, 115 | trigger=CronTrigger.from_crontab(self._cron), 116 | name="歌单同步") 117 | except Exception as e: 118 | logger.error(f"歌单同步服务启动失败,原因:{str(e)}") 119 | self.systemmessage.put(f"歌单同步服务启动失败,原因:{str(e)}") 120 | else: 121 | logger.info(f"歌单同步服务启动,周期:每天七点执行") 122 | self._scheduler.add_job(func=self.__run_sync_paylist, 123 | trigger=CronTrigger.from_crontab("0 7 * * *"), 124 | name="歌单同步") 125 | if self._onlyonce: 126 | logger.info(f"歌单同步服务,立即运行一次") 127 | self._scheduler.add_job(func=self.__run_sync_paylist, trigger='date', 128 | run_date=datetime.now(tz=pytz.timezone(settings.TZ)) + timedelta(seconds=3), 129 | name="歌单同步") 130 | # 关闭一次性开关 131 | self._onlyonce = False 132 | self.update_config({ 133 | "onlyonce": False, 134 | "enabled": self._enabled, 135 | "cron": self._cron, 136 | "media_server": self._media_server, 137 | "exact_match": self._exact_match, 138 | "wylogin_user": self._wylogin_user, 139 | "wylogin_password": self._wylogin_password, 140 | "wymusic_paths": self._wymusic_paths, 141 | "qqmusic_paths": self._qqmusic_paths, 142 | "wy_daily_list": self._wy_daily_list, 143 | "wy_daily_song": self._wy_daily_song, 144 | }) 145 | if self._scheduler.get_jobs(): 146 | # 启动服务 147 | self._scheduler.print_jobs() 148 | self._scheduler.start() 149 | 150 | def get_state(self) -> bool: 151 | return self._enabled 152 | 153 | @staticmethod 154 | def get_command() -> List[Dict[str, Any]]: 155 | pass 156 | 157 | def get_api(self) -> List[Dict[str, Any]]: 158 | pass 159 | 160 | def get_form(self) -> Tuple[List[dict], Dict[str, Any]]: 161 | self._username = self.cm.login_status() 162 | if self._username: 163 | self._wylogin_status = False 164 | self._wyy_text = f"当前网抑云账号{self._username}登录成功,可以使用用户相关功能" 165 | else: 166 | self._wylogin_status = True 167 | self._wyy_text = f"当前未登录网抑云账号,部分功能受限,请选择对应方式登录" 168 | self._login_status = not self._wylogin_status 169 | return [ 170 | { 171 | 'component': 'VForm', 172 | 'content': [ 173 | { 174 | 'component': 'VRow', 175 | 'content': [ 176 | { 177 | 'component': 'VCol', 178 | 'props': { 179 | 'cols': 12, 180 | 'md': 6 181 | }, 182 | 'content': [ 183 | { 184 | 'component': 'VSwitch', 185 | 'props': { 186 | 'model': 'enabled', 187 | 'label': '启用插件', 188 | } 189 | } 190 | ] 191 | }, 192 | { 193 | 'component': 'VCol', 194 | 'props': { 195 | 'cols': 12, 196 | 'md': 6 197 | }, 198 | 'content': [ 199 | { 200 | 'component': 'VSwitch', 201 | 'props': { 202 | 'model': 'onlyonce', 203 | 'label': '立即运行一次', 204 | } 205 | } 206 | ] 207 | } 208 | ] 209 | }, 210 | { 211 | 'component': 'VRow', 212 | 'content': [ 213 | { 214 | 'component': 'VCol', 215 | 'props': { 216 | 'cols': 12, 217 | 'md': 6 218 | }, 219 | 'content': [ 220 | { 221 | 'component': 'VSelect', 222 | 'props': { 223 | 'chips': True, 224 | 'multiple': True, 225 | 'model': 'media_server', 226 | 'label': '媒体服务器', 227 | 'items': [ 228 | {'title': 'Plex', 'value': 'plex'}, 229 | {'title': 'Emby', 'value': 'emby'}, 230 | ] 231 | } 232 | } 233 | ], 234 | }, 235 | { 236 | 'component': 'VCol', 237 | 'props': { 238 | 'cols': 12, 239 | 'md': 6 240 | }, 241 | 'content': [ 242 | { 243 | 'component': 'VTextField', 244 | 'props': { 245 | 'model': 'cron', 246 | 'label': '执行周期', 247 | 'placeholder': '5位cron表达式,留空自动, 建议每天一次' 248 | } 249 | } 250 | ] 251 | }, 252 | { 253 | 'component': 'VCol', 254 | 'props': { 255 | 'cols': 12, 256 | 'md': 6 257 | }, 258 | 'content': [ 259 | { 260 | 'component': 'VSwitch', 261 | 'props': { 262 | 'model': 'exact_match', 263 | 'label': '精准匹配(同时匹配歌曲名称和歌手)', 264 | } 265 | } 266 | ] 267 | } 268 | ] 269 | }, 270 | { 271 | 'component': 'VRow', 272 | 'content': [ 273 | { 274 | 'component': 'VCol', 275 | 'props': { 276 | 'cols': 12 277 | }, 278 | 'content': [ 279 | { 280 | 'component': 'VTextarea', 281 | 'props': { 282 | 'model': 'qqmusic_paths', 283 | 'label': 'QQ音乐歌单同步设置', 284 | 'rows': 4, 285 | 'placeholder': 286 | '一行一个歌单配置留空不启用 \n' 287 | '默认格式:QQ音乐歌单id:plex/emby播放列表名称\n' 288 | 'eg: 2362260213:经典歌曲\n' 289 | 'emby多用户格式:QQ音乐歌单id:plex/emby播放列表名称:emby用户名 \n' 290 | 'eg: 2362260213:经典歌曲:doumao\n' 291 | 'emby多用户格式:QQ音乐歌单id:plex/emby播放列表名称:emby1,emby2 \n' 292 | 'eg: 2362260213:经典歌曲:doumao,tudou\n' 293 | } 294 | } 295 | ] 296 | } 297 | ] 298 | }, 299 | { 300 | 'component': 'VRow', 301 | 'content': [ 302 | { 303 | 'component': 'VCol', 304 | 'props': { 305 | 'cols': 12, 306 | }, 307 | 'content': [ 308 | { 309 | 'component': 'VAlert', 310 | 'props': { 311 | 'type': 'info', 312 | 'variant': 'tonal', 313 | 'title': '账号状态', 314 | 'text': self._wyy_text 315 | } 316 | } 317 | ] 318 | } 319 | ] 320 | }, 321 | { 322 | 'component': 'VRow', 323 | "props": { 324 | "model": "wylogin_status", 325 | }, 326 | 'content': [ 327 | { 328 | 'component': 'VCol', 329 | 'props': { 330 | 'cols': 12, 331 | 'md': 6 332 | }, 333 | 'content': [ 334 | { 335 | 'component': 'VCheckboxBtn', 336 | 'props': { 337 | 'model': 'wylogin_pass', 338 | 'label': '使用密码登录(适用邮箱或者手机号)' 339 | } 340 | } 341 | ] 342 | }, 343 | # { 344 | # 'component': 'VCol', 345 | # 'props': { 346 | # 'cols': 12, 347 | # 'md': 6 348 | # }, 349 | # 'content': [ 350 | # { 351 | # 'component': 'VCheckboxBtn', 352 | # 'props': { 353 | # 'model': 'wylogin_capt', 354 | # 'label': '使用验证码登录(适用手机号)' 355 | # } 356 | # } 357 | # ] 358 | # } 359 | ] 360 | }, 361 | { 362 | "component": "VDialog", 363 | "props": { 364 | "model": "wylogin_capt", 365 | "overlay-class": "v-dialog--scrollable", 366 | "content-class": "v-card v-card--density-default v-card--variant-elevated rounded-t", 367 | 'cols': 30, 368 | 'md': 12 369 | }, 370 | "content": [ 371 | { 372 | 'component': 'VRow', 373 | 'content': [ 374 | { 375 | 'component': 'VCol', 376 | 'props': { 377 | 'cols': 12, 378 | 'md': 4 379 | }, 380 | 'content': [ 381 | { 382 | 'component': 'VTextField', 383 | 'props': { 384 | 'model': 'wylogin_user', 385 | 'label': '手机号', 386 | 'placeholder': '', 387 | } 388 | } 389 | ] 390 | }, 391 | { 392 | 'component': 'VCol', 393 | 'props': { 394 | 'cols': 12, 395 | 'md': 4 396 | }, 397 | 'content': [ 398 | { 399 | 'component': 'VSwitch', 400 | 'props': { 401 | 'model': 'capt_swich', 402 | 'label': '获取验证码', 403 | } 404 | } 405 | ] 406 | }, 407 | ] 408 | }, 409 | { 410 | 'component': 'VRow', 411 | 'content': [ 412 | { 413 | 'component': 'VCol', 414 | 'props': { 415 | 'cols': 12, 416 | 'md': 4 417 | }, 418 | 'content': [ 419 | { 420 | 'component': 'VTextField', 421 | 'props': { 422 | 'model': 'wylogin_password', 423 | 'label': '验证码', 424 | 'placeholder': '', 425 | } 426 | } 427 | ] 428 | }, 429 | { 430 | 'component': 'VCol', 431 | 'props': { 432 | 'cols': 12, 433 | 'md': 4 434 | }, 435 | 'content': [ 436 | { 437 | 'component': 'VSwitch', 438 | 'props': { 439 | 'model': 'login_swich', 440 | 'label': '登录', 441 | } 442 | } 443 | ] 444 | }, 445 | ] 446 | }, 447 | ] 448 | }, 449 | { 450 | "component": "VDialog", 451 | "props": { 452 | "model": "wylogin_pass", 453 | "max-width": "65rem", 454 | "overlay-class": "v-dialog--scrollable", 455 | "content-class": "v-card v-card--density-default v-card--variant-elevated rounded-t", 456 | }, 457 | "content": [ 458 | { 459 | "component": "VCard", 460 | "props": { 461 | "title": "网抑云配置" 462 | }, 463 | 'content': [ 464 | { 465 | "component": "VDialogCloseBtn", 466 | "props": { 467 | "model": "wylogin_pass" 468 | } 469 | }, 470 | { 471 | "component": "VCardText", 472 | "props": {}, 473 | 'content': [ 474 | { 475 | 'component': 'VRow', 476 | 'content': [ 477 | { 478 | 'component': 'VCol', 479 | 'props': { 480 | 'cols': 12, 481 | 'md': 4 482 | }, 483 | 'content': [ 484 | { 485 | 'component': 'VTextField', 486 | 'props': { 487 | 'model': 'wylogin_user', 488 | 'label': '手机号/邮箱', 489 | 'placeholder': '', 490 | } 491 | } 492 | ] 493 | }, 494 | { 495 | 'component': 'VCol', 496 | 'props': { 497 | 'cols': 12, 498 | 'md': 4 499 | }, 500 | 'content': [ 501 | { 502 | 'component': 'VTextField', 503 | 'props': { 504 | 'model': 'wylogin_password', 505 | 'label': '密码', 506 | 'placeholder': '', 507 | 'type': 'password', 508 | } 509 | } 510 | ] 511 | } 512 | ] 513 | }, 514 | { 515 | 'component': 'VRow', 516 | 'content': [ 517 | { 518 | 'component': 'VCol', 519 | 'props': { 520 | 'cols': 12, 521 | }, 522 | 'content': [ 523 | { 524 | 'component': 'VAlert', 525 | 'props': { 526 | 'type': 'info', 527 | 'variant': 'tonal' 528 | }, 529 | 'content': [ 530 | { 531 | 'component': 'span', 532 | 'text': '注意:输入信息后关闭窗口点击保存生效' 533 | } 534 | ] 535 | } 536 | ] 537 | } 538 | ] 539 | } 540 | ] 541 | }, 542 | 543 | ] 544 | }, 545 | 546 | ] 547 | }, 548 | { 549 | 'component': 'VRow', 550 | "props": { 551 | "model": "login_status", 552 | }, 553 | 'content': [ 554 | { 555 | 'component': 'VCol', 556 | 'props': { 557 | 'cols': 12, 558 | 'md': 6 559 | }, 560 | 'content': [ 561 | { 562 | 'component': 'VSwitch', 563 | 'props': { 564 | 'model': 'wy_daily_song', 565 | 'label': '每日推荐歌曲', 566 | } 567 | } 568 | ] 569 | }, 570 | { 571 | 'component': 'VCol', 572 | 'props': { 573 | 'cols': 12, 574 | 'md': 6 575 | }, 576 | 'content': [ 577 | { 578 | 'component': 'VSwitch', 579 | 'props': { 580 | 'model': 'wy_daily_list', 581 | 'label': '每日推荐歌单', 582 | } 583 | } 584 | ] 585 | } 586 | ] 587 | }, 588 | { 589 | 'component': 'VRow', 590 | 'content': [ 591 | { 592 | 'component': 'VCol', 593 | 'props': { 594 | 'cols': 12 595 | }, 596 | 'content': [ 597 | { 598 | 'component': 'VTextarea', 599 | 'props': { 600 | 'model': 'wymusic_paths', 601 | 'label': '网易云歌单同步设置', 602 | 'rows': 4, 603 | 'placeholder': 604 | '一行一个歌单配置留空不启用 \n' 605 | '默认格式:QQ音乐歌单id:plex/emby播放列表名称\n' 606 | 'eg: 2362260213:经典歌曲\n' 607 | 'emby多用户格式:QQ音乐歌单id:plex/emby播放列表名称:emby用户名 \n' 608 | 'eg: 2362260213:经典歌曲:doumao\n' 609 | 'emby多用户格式:QQ音乐歌单id:plex/emby播放列表名称:emby1,emby2 \n' 610 | 'eg: 2362260213:经典歌曲:doumao,tudou\n' 611 | } 612 | } 613 | ] 614 | } 615 | ] 616 | }, 617 | 618 | { 619 | 'component': 'VRow', 620 | 'content': [ 621 | { 622 | 'component': 'VCol', 623 | 'props': { 624 | 'cols': 12, 625 | }, 626 | 'content': [ 627 | { 628 | 'component': 'VAlert', 629 | 'props': { 630 | 'type': 'info', 631 | 'variant': 'tonal', 632 | 'title': '使用说明:', 633 | 'text': 634 | '0. 耗时很长,建议每天一次即可,短时间重复运行会卡死; \n' 635 | '00. 网抑云登录后支持每日推荐歌单的递增; \n' 636 | '1. plex/emby服务器中存在音乐类型的库; \n' 637 | '2. plex/emby的播放列表需要提前创建好并且里边至少有一首歌曲; \n' 638 | '3. 如不存在会自动创建歌单, 如库中没符合的歌曲会创建失败; \n' 639 | '4. 歌单同步只会搜索已存在歌曲进行添加,不会自动下载; \n' 640 | '5. 歌曲匹配是模糊匹配只匹配曲名不匹配歌手; \n' 641 | '6. 精准匹配打开后先进行歌曲搜索然后通过歌手来进行过滤; \n' 642 | '7. emby支持多用户设置,plex自带分享无需创建; \n' 643 | } 644 | } 645 | ] 646 | } 647 | ] 648 | } 649 | ] 650 | } 651 | ], { 652 | "enabled": False, 653 | "cron": "0 0 */7 * *", 654 | "mode": "", 655 | "scraper_paths": "", 656 | "err_hosts": "" 657 | } 658 | 659 | def get_page(self) -> List[dict]: 660 | pass 661 | 662 | def __run_sync_paylist(self): 663 | """ 664 | 开始同步歌单 665 | """ 666 | global pm, em 667 | plex_on = False 668 | emby_on = False 669 | emby_users = [] 670 | if not self._wymusic_paths and not self._qqmusic_paths and not self._username: 671 | logger.info("同步配置为空,不进行处理。告退......") 672 | return 673 | if not self._media_server: 674 | logger.info("没有可用的媒体服务器,不进行处理。告退......") 675 | return 676 | if 'plex' in self._media_server: 677 | # plex 初始化 678 | pm = PlexMusic() 679 | pm.get_music_library() 680 | pm.get_playlists() 681 | plex_on = True 682 | logger.info('媒体服务器设置包含Plex服务器') 683 | if 'emby' in self._media_server: 684 | # emby 初始化 685 | em = EmbyMusic() 686 | emby_on = True 687 | emby_users = [em.default_user] 688 | logger.info('媒体服务器设置包含Emby服务器') 689 | # 获取同步列表信息 690 | if self._qqmusic_paths: 691 | qq = QQMusicApi() 692 | qqmusic_paths = self._qqmusic_paths.split("\n") 693 | for path in qqmusic_paths: 694 | data_list = path.split(':') 695 | if len(data_list) == 2: 696 | qq_play_id, media_playlist = data_list[0], data_list[1] 697 | elif len(data_list) == 3: 698 | qq_play_id, media_playlist, emby_users = data_list[0], data_list[1], data_list[2] 699 | emby_users = emby_users.split(',') 700 | else: 701 | logger.warn(f"QQ音乐歌单同步设置配置不规范,请认真检查修改") 702 | return 703 | logger.info(f"QQ歌单id: {qq_play_id}, 媒体库播放列表名称: {media_playlist}") 704 | if qq_play_id and media_playlist: 705 | qq_tracks = qq.get_playlist_by_id(qq_play_id) 706 | logger.info(f"QQ歌单 {qq_play_id} 获取歌曲[{len(qq_tracks)}]首,列表为: {qq_tracks}") 707 | if plex_on: 708 | self.__t_plex(pm, qq_tracks, media_playlist) 709 | if emby_on: 710 | logger.info( 711 | f"QQ歌单id: {qq_play_id}, 为Emby用户[{emby_users}]更新媒体库播放列表名称: {media_playlist}") 712 | self.__t_emby(em, qq_tracks, media_playlist, emby_users) 713 | 714 | else: 715 | logger.warn(f"QQ音乐歌单同步设置配置不规范,请认真检查修改") 716 | if self._wymusic_paths: 717 | wymusic_paths = self._wymusic_paths.split("\n") 718 | for path in wymusic_paths: 719 | data_list = path.split(':') 720 | if len(data_list) == 2: 721 | wy_play_id, media_playlist = data_list[0], data_list[1] 722 | elif len(data_list) == 3: 723 | wy_play_id, media_playlist, emby_users = data_list[0], data_list[1], data_list[2] 724 | emby_users = emby_users.split(',') 725 | else: 726 | logger.warn(f"网易云歌单同步设置配置不规范,请认真检查修改") 727 | return 728 | logger.info(f"网易云歌单id: {wy_play_id}, 媒体库播放列表名称: {media_playlist}") 729 | self.cm_emby_plex(wy_play_id, media_playlist, emby_users, plex_on, emby_on) 730 | if self._username: 731 | # 每日推荐歌单 732 | if self._wy_daily_list: 733 | try: 734 | datas = self.cm.get_list_days() 735 | for data in datas: 736 | wy_play_id, media_playlist = data[0], data[1] 737 | self.cm_emby_plex(wy_play_id, media_playlist, emby_users, plex_on, emby_on) 738 | except Exception as e: 739 | logger.error(e) 740 | logger.error(f"每日推荐歌单获取失败") 741 | # 每日歌曲推荐 742 | if self._wy_daily_song: 743 | try: 744 | wy_tracks = self.cm.get_song_daily() 745 | playlist = "每日歌曲推荐" 746 | logger.info(f"网易云歌单 {playlist} 获取歌曲[{len(wy_tracks)}]首,列表为: {wy_tracks}") 747 | if plex_on: 748 | self.__t_plex(pm, wy_tracks, playlist) 749 | if emby_on: 750 | logger.info( 751 | f"网易云歌单: {wy_tracks}, 为Emby用户{emby_users}更新媒体库播放列表名称: {playlist}") 752 | self.__t_emby(em, wy_tracks, playlist, emby_users) 753 | except Exception as e: 754 | logger.error(e) 755 | logger.error(f"每日推荐更新失败") 756 | return 757 | 758 | def cm_emby_plex(self, wy_play_id, media_playlist, emby_users, plex_on, emby_on): 759 | if wy_play_id and media_playlist: 760 | wy_tracks = self.cm.songofplaylist(wy_play_id) 761 | if not wy_tracks: 762 | logger.error("网易云歌单获取失败,请登录账号重试") 763 | else: 764 | logger.info(f"网易云歌单 {wy_play_id} 获取歌曲[{len(wy_tracks)}]首,列表为: {wy_tracks}") 765 | if plex_on: 766 | self.__t_plex(pm, wy_tracks, media_playlist) 767 | if emby_on: 768 | logger.info( 769 | f"网易云歌单: {wy_tracks}, 为Emby用户{emby_users}更新媒体库播放列表名称: {media_playlist}") 770 | self.__t_emby(em, wy_tracks, media_playlist, emby_users) 771 | else: 772 | logger.warn(f"网易云音乐歌单同步设置配置不规范,请认真检查修改") 773 | 774 | def __t_emby(self, em, t_tracks, media_playlist, emby_users=None): 775 | if emby_users is None: 776 | emby_users = [em.default_user] 777 | one_user = emby_users[0] 778 | other_users = emby_users[1:] 779 | em.user = em.get_user(one_user) 780 | em.get_music_library() 781 | logger.info("Emby开始同步歌单,涉及搜索时间较长请耐心等待.......") 782 | playlist_id, music_ids, music_names = em.get_tracks_by_playlist(media_playlist) 783 | logger.info(f"Emby歌单[{media_playlist}]现有歌曲[{len(music_names)}]首,列表为: {music_names}") 784 | if music_names: 785 | new_tracks = [i for i in t_tracks if i[0] not in music_names] 786 | else: 787 | new_tracks = t_tracks 788 | # new_tracks = list(set(i[0] for i in t_tracks) - set(music_names)) 789 | tracks = em.mul_search_music(new_tracks, self._exact_match) 790 | if playlist_id: 791 | ids = [i for i in tracks if i not in music_ids] 792 | em.set_tracks_to_playlist(playlist_id, ','.join(ids)) 793 | else: 794 | em.create_playlist(media_playlist, ','.join(tracks)) 795 | _, new_music_ids, _ = em.get_tracks_by_playlist(media_playlist) 796 | for user in other_users: 797 | em.user = em.get_user(user) 798 | em.get_music_library() 799 | user_playlist_id, user_music_ids, user_music_names = em.get_tracks_by_playlist(media_playlist) 800 | if user_playlist_id: 801 | new_ids = [i for i in new_music_ids if i not in user_music_ids] 802 | em.set_tracks_to_playlist(user_playlist_id, ','.join(new_ids), user) 803 | else: 804 | em.create_playlist(media_playlist, ','.join(new_music_ids), user) 805 | 806 | logger.info("Emby同步歌单完成,感谢耐心等待.......") 807 | logger.info("歌单同步完成,END") 808 | return 809 | 810 | def __t_plex(self, pm, t_tracks, media_playlist): 811 | logger.info("Plex开始同步歌单,涉及搜索时间较长请耐心等待.......") 812 | add_tracks = [] 813 | old_tracks = [] 814 | plex_tracks = pm.get_tracks_by_playlist(media_playlist) 815 | logger.debug(f"plex播放列表 [{media_playlist}] 已存在歌曲[{len(plex_tracks)}]首,列表为: {plex_tracks}") 816 | # 查找获取tracks 817 | for t_track in t_tracks: 818 | if t_track[0] in plex_tracks: 819 | old_tracks.append(t_track) 820 | continue 821 | try: 822 | tracks = pm.search_music(t_track, self._exact_match) 823 | except Exception as e: 824 | logger.error(f"搜索歌曲失败,err:{e}") 825 | tracks = [] 826 | add_tracks += tracks 827 | # 去重 828 | add_tracks = list(set(add_tracks)) 829 | no_list = list(set(i[0] for i in t_tracks) - set([i.title for i in add_tracks]) - set(i[0] for i in old_tracks)) 830 | logger.info(f"Plex库中未搜到歌曲[{len(no_list)}]首,列表为: {no_list}") 831 | # 有歌曲写入没有就跳过 832 | if len(add_tracks) > 0: 833 | if len(plex_tracks) < 1: 834 | try: 835 | # 创建如果存在创建失败就进行添加 836 | pm.create_playlist(media_playlist, add_tracks) 837 | logger.info(f"Plex创建播放列表[{media_playlist}]成功,并添加歌曲[{len(add_tracks)}]首,列表为: {[i.title for i in add_tracks]}") 838 | except Exception as err: 839 | logger.error(f"{err}") 840 | else: 841 | try: 842 | pm.set_tracks_to_playlist(media_playlist, add_tracks) 843 | logger.info(f"Plex向播放列表[{media_playlist}]添加歌曲[{len(add_tracks)}]首,列表为: {[i.title for i in add_tracks]}成功") 844 | except Exception as e: 845 | logger.error(f"{e}") 846 | else: 847 | if len(old_tracks) == len(t_tracks): 848 | logger.info(f"Plex歌单全部同步,无需再次同步") 849 | else: 850 | logger.info(f"Plex歌单同步完成,有部分歌曲没有查询到,请查看日志") 851 | logger.info("Plex同步歌单完成,感谢耐心等待.......") 852 | return 853 | 854 | 855 | def stop_service(self): 856 | """ 857 | 退出插件 858 | """ 859 | try: 860 | if self._scheduler: 861 | self._scheduler.remove_all_jobs() 862 | if self._scheduler.running: 863 | self._event.set() 864 | self._scheduler.shutdown() 865 | self._event.clear() 866 | self._scheduler = None 867 | except Exception as e: 868 | print(str(e)) 869 | 870 | 871 | 872 | 873 | 874 | -------------------------------------------------------------------------------- /plugins/syncmusiclist/cloudmusic.py: -------------------------------------------------------------------------------- 1 | 2 | import re 3 | import time 4 | 5 | 6 | from app.log import logger 7 | from app.plugins.syncmusiclist.netcloudmusic import NeteaseCloudMusicApi 8 | from app.plugins.syncmusiclist.utils import change_str, sub_str 9 | 10 | 11 | class CloudMusic(object): 12 | def __init__(self, path=None): 13 | self.music_api = NeteaseCloudMusicApi(path=path) # 初始化API 14 | version_result = self.music_api.request("inner_version") 15 | logger.info(f'当前使用NeteaseCloudMusicApi版本号:{version_result["NeteaseCloudMusicApi"]}\n' 16 | f'当前使用NeteaseCloudMusicApi_V8版本号:{version_result["NeteaseCloudMusicApi_V8"]}') 17 | 18 | def login_status(self): 19 | """账户登录状态""" 20 | try: 21 | if not self.music_api.cookie: 22 | return None 23 | response = self.music_api.request("/login/status") 24 | if response['data']['data']["code"] == 200: 25 | try: 26 | nickname = response["data"]["data"]["profile"]["nickname"] 27 | logger.info(f'当前登录账号:{nickname}') 28 | except: 29 | nickname = None 30 | return nickname 31 | else: 32 | return None 33 | except: 34 | return None 35 | 36 | def captcha_sent(self, _phone): 37 | """验证码""" 38 | response = self.music_api.request("/captcha/sent", {"phone": f"{_phone}"}) 39 | return response 40 | 41 | def login_cellphone(self, _phone, _captcha): 42 | """验证码登录""" 43 | response = self.music_api.request("/login/cellphone", {"phone": f"{_phone}", "captcha": f"{_captcha}"}) 44 | return response 45 | 46 | 47 | def login(self, username, password): 48 | """ 49 | 登陆到网易云音乐 50 | 调用登录接口后,会自动设置cookie,如果cookie失效,需要重新登录,登录过后api会在你的当前工作目录下创建cookie_storage文件保存你的cookie 51 | 在下次调用运行程序时,他会判断cookie是否过期,没有过期就自动读取cookie_storage文件中的cookie。 52 | 53 | 总的来说你不需要手动管理cookie,只需要调用登录接口,然后调用其他接口即可,cookie会自动设置,如果cookie过期,再次调用登录接口就好。 54 | 更好的办法是,在cookie还没有失效之前使用refresh_login接口刷新cookie,这样就不需要重新登录了(建议在你每次启动软件时都刷新,当然频繁重启调试的时候另算) 55 | 56 | 如果你想判断当前是否已经登录,if not netease_cloud_music_api.cookie 就可以了,或者调用/login/status接口 57 | 58 | """ 59 | # 登录 60 | if not self.music_api.cookie: 61 | if username.isdigit(): 62 | response = self.music_api.request("/login/cellphone", 63 | {"phone": f"{username}", "password": f"{password}"}) 64 | else: 65 | response = self.music_api.request("/login", 66 | {"email": f"{username}", "password": f"{password}"}) 67 | if response.get("code") == 200: 68 | logger.info("登录成功") 69 | if self.music_api.cookie: 70 | logger.info("cookie已缓存") 71 | else: 72 | logger.error("登录失败") 73 | 74 | def signin(self): 75 | """网易云签到""" 76 | res = self.music_api.request("/daily_signin") 77 | return res 78 | 79 | def get_list_days(self, nums=5): 80 | """每日推荐歌单""" 81 | res = self.music_api.request("/recommend/resource") 82 | recommend = res.get('data', {}).get('recommend', []) 83 | res = [[i.get("id"), i.get("name")] for i in recommend[:nums] if i.get("id")] 84 | return res 85 | 86 | def get_song_daily(self): 87 | """每日推荐歌曲""" 88 | res = self.music_api.request("/recommend/songs") 89 | dailySongs = res['data']['data']['dailySongs'] 90 | track_names = [] 91 | for i in dailySongs: 92 | # 正则处理 93 | name = sub_str(i.get('name')) 94 | # 多歌手处理 95 | ars = [change_str(ar.get('name')) for ar in i.get('ar')] 96 | track_names.append([name, ars]) 97 | return track_names 98 | 99 | 100 | def playlist(self, uid): 101 | """ 102 | 歌单 103 | Full request URI: http://music.163.com/api/playlist/detail?id=37880978&updateTime=-1 104 | GET http://music.163.com/api/playlist/detail 105 | 必要参数: 106 | id:歌单ID 107 | """ 108 | res = self.music_api.request(f"/playlist/track/all", {"id": f"{uid}"}) 109 | return res.get('data', {}).get('songs') 110 | 111 | def songofplaylist(self, uid): 112 | """ 113 | 获取歌单中歌曲 114 | """ 115 | tracks = [] 116 | # 循环进行重试 117 | # 设置最大重试次数 118 | max_retry_times = 5 119 | # 当前重试次数 120 | retry_times = 0 121 | while retry_times < max_retry_times: 122 | try: 123 | tracks = self.playlist(uid) 124 | break # 如果成功执行,跳出循环 125 | except Exception as e: 126 | logger.warn(f"第 {retry_times + 1} 次重试失败:获取歌单错误") 127 | retry_times += 1 128 | time.sleep(2) # 添加延时 129 | track_names = [] 130 | for i in tracks: 131 | # 正则处理 132 | name = sub_str(i.get('name')) 133 | # 多歌手处理 134 | ars = [change_str(ar.get('name')) for ar in i.get('ar')] 135 | track_names.append([name, ars]) 136 | return track_names 137 | 138 | 139 | if __name__ == '__main__': 140 | cm = CloudMusic() 141 | cm.signin() 142 | res_s = cm.get_song_daily() 143 | 144 | print(res_s) 145 | res_day = cm.get_list_days() 146 | 147 | res = cm.songofplaylist("365436873") 148 | print(res) 149 | 150 | 151 | -------------------------------------------------------------------------------- /plugins/syncmusiclist/emby_music.py: -------------------------------------------------------------------------------- 1 | from typing import List, Optional, Union, Dict, Generator, Tuple 2 | 3 | from app.log import logger 4 | from app.schemas import MediaType, MediaServerLibrary 5 | from app.modules.emby import Emby 6 | from app.utils.http import RequestUtils 7 | from app.core.config import settings 8 | 9 | 10 | class EmbyMusic(Emby): 11 | """API for Plex 12 | 继承根项目, 实现音乐库相关的api 13 | """ 14 | 15 | def __init__(self): 16 | Emby.__init__(self) 17 | self.default_user = self.get_default_user(settings.SUPERUSER) 18 | self.music_libraries = [] 19 | self.music_playlists = [] 20 | 21 | def get_default_user(self, user_name: str = None) -> Optional[Union[str, int]]: 22 | """ 23 | 获得管理员用户 24 | """ 25 | if not self._host or not self._apikey: 26 | return None 27 | req_url = "%sUsers?api_key=%s" % (self._host, self._apikey) 28 | try: 29 | res = RequestUtils().get_res(req_url) 30 | if res: 31 | users = res.json() 32 | # 先查询是否有与当前用户名称匹配的 33 | if user_name: 34 | for user in users: 35 | if user.get("Name") == user_name: 36 | return user.get("Name") 37 | # 查询管理员 38 | for user in users: 39 | if user.get("Policy", {}).get("IsAdministrator"): 40 | return user.get("Name") 41 | else: 42 | logger.error(f"Users 未获取到返回数据") 43 | except Exception as e: 44 | logger.error(f"连接Users出错:" + str(e)) 45 | return None 46 | 47 | def __get_emby_librarys(self) -> List[dict]: 48 | """ 49 | 获取Emby媒体库列表 50 | """ 51 | if not self._host or not self._apikey: 52 | return [] 53 | req_url = f"{self._host}emby/Users/{self.user}/Views?api_key={self._apikey}" 54 | try: 55 | res = RequestUtils().get_res(req_url) 56 | if res: 57 | return res.json().get("Items") 58 | else: 59 | logger.error(f"EmbyUser/Views 未获取到返回数据") 60 | return [] 61 | except Exception as e: 62 | logger.error(f"Emby连接User/Views 出错:" + str(e)) 63 | return [] 64 | 65 | def get_music_library(self): 66 | """ 67 | 获取媒体服务器所有音乐类型媒体库列表以及所有playlist 68 | """ 69 | if not self._host or not self._apikey: 70 | return [] 71 | emby_librarys = self.__get_emby_librarys() or [] 72 | self.music_playlists = [] 73 | self.music_libraries = [] 74 | for library in emby_librarys: 75 | if library.get("CollectionType") == 'music': 76 | self.music_libraries.append( 77 | MediaServerLibrary( 78 | server="emby", 79 | id=library.get("Id"), 80 | name=library.get("Name"), 81 | path=library.get("Path"), 82 | type=library.get("CollectionType") 83 | ) 84 | ) 85 | elif library.get("CollectionType") == 'playlists': 86 | url = f'{self._host}emby/Users/{self.user}/Items?ParentId={library.get("Id")}&api_key={self._apikey}' 87 | try: 88 | res = self.get_data(url) 89 | playlist = res.json().get("Items") 90 | except Exception as err: 91 | logger.error(f"Emby获取播放列表失败: {err}") 92 | playlist = [] 93 | self.music_playlists += playlist 94 | else: 95 | continue 96 | return self.music_libraries 97 | 98 | def get_tracks_by_playlist(self, playlist_title): 99 | """获取播放列表的详细歌单""" 100 | playlist_id = None 101 | for i in self.music_playlists: 102 | if playlist_title == i.get('Name'): 103 | playlist_id = i.get('Id') 104 | break 105 | if not playlist_id: 106 | logger.warn(f"Emby媒体库中播放列表为:[{[i.get('Name') for i in self.music_playlists]}]\n 不存在: [{playlist_title}], 稍后会自动创建,如果失败请手动创建") 107 | return '', [], [] 108 | url = f'{self._host}emby/Users/{self.user}/Items?ParentId={playlist_id}&api_key={self._apikey}' 109 | try: 110 | res = self.get_data(url) 111 | tracks = res.json().get("Items") 112 | except Exception as err: 113 | logger.error(f"Emby获取播放列表失败: {err}") 114 | tracks = [] 115 | music_ids = [i.get('Id') for i in tracks if i.get('Type') == 'Audio'] 116 | music_names = [i.get('Name') for i in tracks if i.get('Type') == 'Audio'] 117 | return playlist_id, music_ids, music_names 118 | 119 | def create_playlist(self, name, ids, user=settings.SUPERUSER): 120 | """创建播放列表""" 121 | if name in [i.get('Name') for i in self.music_playlists]: 122 | logger.info(f"Emby歌单: [{name}] 已经存在,跳过创建") 123 | # Playlists 124 | url = f'{self._host}emby/Playlists?api_key={self._apikey}&userId={self.user}&Name={name}&Ids={ids}' 125 | try: 126 | res = self.post_data( 127 | url, 128 | headers={"Content-Type": "application/json"} 129 | ) 130 | if res.status_code == 200: 131 | info = res.json() 132 | logger.info(f"Emby为用户{user}创建歌单成功:{info}") 133 | return True 134 | else: 135 | logger.error(f"Emby为用户{user}创建歌单失败:[{name}]") 136 | return False 137 | except Exception as e: 138 | logger.error(f"Emby为用户{user}创建歌单失败:[{name}]: {e}") 139 | return False 140 | 141 | def set_tracks_to_playlist(self, playlist_id, ids, user=settings.SUPERUSER): 142 | """添加歌曲到歌单中""" 143 | url = f'{self._host}emby/Playlists/{playlist_id}/Items?api_key={self._apikey}&userId={self.user}&Ids={ids}' 144 | try: 145 | res = self.post_data( 146 | url, 147 | headers={"Content-Type": "application/json"} 148 | ) 149 | if res.status_code == 200: 150 | info = res.json() 151 | logger.info(f"Emby为用户{user}的歌单添加歌曲成功:[{info}]") 152 | return True 153 | else: 154 | logger.error(f"Emby为用户{user}的歌单添加歌曲失败") 155 | return False 156 | except Exception as e: 157 | logger.error(e) 158 | return False 159 | 160 | def search_music(self, name_singer, exact_match=True): 161 | """通过歌曲名在库中进行搜索""" 162 | # /emby/Users/{}/Items?Recursive=true&SearchTerm={}&api_key={} 163 | name = name_singer[0] 164 | singers = name_singer[1] 165 | url = f'{self._host}emby/Users/{self.user}/Items?Recursive=true&SearchTerm={name}&api_key={self._apikey}' 166 | try: 167 | res = self.get_data(url) 168 | count = res.json().get("TotalRecordCount") 169 | if count > 0: 170 | items = res.json().get("Items") 171 | if exact_match: 172 | add_items = [] 173 | # 通过歌手过滤 174 | for i in items: 175 | arts = i.get("Artists", []) 176 | if len(set(arts) & set(singers)) > 0: 177 | # add 178 | add_items = [i] 179 | break 180 | else: 181 | str_arts = ' '.join(arts) 182 | for singer in singers: 183 | if singer in str_arts: 184 | # add 185 | add_items = [i] 186 | break 187 | if add_items: 188 | break 189 | else: 190 | add_items = items 191 | 192 | ids_list = [i.get('Id') for i in add_items if i.get('Type') == 'Audio'][:1] 193 | name_list = [i.get('Name') for i in add_items if i.get('Type') == 'Audio'][:1] 194 | else: 195 | ids_list = [] 196 | name_list = [] 197 | except Exception as err: 198 | logger.error(err) 199 | return [], [] 200 | return ids_list, name_list 201 | 202 | def mul_search_music(self, name_list, exact_match=True): 203 | logger.info(f"Emby中的播放列表为: {[i.get('Name') for i in self.music_playlists]}") 204 | all_list = [] 205 | lack_list = [] 206 | add_list = [] 207 | for names in name_list: 208 | ids_list, name_list = self.search_music(names, exact_match) 209 | if len(ids_list) == 0: 210 | lack_list.append(names) 211 | else: 212 | add_list += name_list 213 | all_list += ids_list 214 | logger.info(f"Emby搜索库中获取歌曲[{len(add_list)}]首,列表为: {add_list}") 215 | logger.info(f"Emby库中未搜到歌曲[{len(lack_list)}]首,列表为: {lack_list}") 216 | return all_list 217 | 218 | 219 | if __name__ == '__main__': 220 | em = EmbyMusic() 221 | emby_user = 'tzp' 222 | em.user = em.get_user(emby_user) 223 | em.get_music_library() 224 | media_playlist = "许嵩专版" 225 | t_tracks = [['通天大道宽又阔', ['崔京浩', '三叶草演唱组']], ['微微', ['傅如乔']], ['相思', ['毛阿敏']]] 226 | 227 | tracks = em.mul_search_music(t_tracks) 228 | playlist_id, music_ids, music_names = em.get_tracks_by_playlist(media_playlist) 229 | if playlist_id: 230 | ids = [i for i in tracks if i not in music_ids] 231 | em.set_tracks_to_playlist(playlist_id, ','.join(ids)) 232 | else: 233 | em.create_playlist(media_playlist, ','.join(tracks)) 234 | print(music_ids) 235 | 236 | 237 | -------------------------------------------------------------------------------- /plugins/syncmusiclist/netcloudmusic/__init__.py: -------------------------------------------------------------------------------- 1 | from .main import NeteaseCloudMusicApi 2 | from .help import api_help, api_list 3 | from .utils import format_cookie_str, prase_cookie_str 4 | 5 | __version__ = '0.1.7' 6 | -------------------------------------------------------------------------------- /plugins/syncmusiclist/netcloudmusic/help.py: -------------------------------------------------------------------------------- 1 | import json 2 | import pkg_resources 3 | 4 | # 载入配置 5 | resource_path = pkg_resources.resource_filename(__name__, 'config.json') 6 | 7 | # 不被支持的接口 8 | exclude = ["/request/reference", "/avatar/upload", "/cloud", "/playlist/cover/update", "/voice/upload", 9 | "/register/anonimous", "/verify/getQr"] 10 | 11 | with open(resource_path, 'r', encoding='utf-8') as f: 12 | config = json.loads(f.read()) 13 | 14 | 15 | def api_help(name: str = None) -> str: 16 | """ 17 | 获取接口帮助 18 | :param name: 接口名称 19 | :return: 20 | """ 21 | if name is None: 22 | result_str = ("from NeteaseCloudMusic import NeteaseCloudMusicApi, api_help, api_list\n\n" 23 | "netease_cloud_music_api = NeteaseCloudMusicApi() # 初始化API\n" 24 | "netease_cloud_music_api.cookie = YOUR_COOKIE # 设置cookie\n" 25 | "response = netease_cloud_music_api.request(apiName, queryDict) # 调用接口\n\n" 26 | "# Use ”help(apiName)“ to view detailed information about the interface\n" 27 | "# Use ”api_list()“ to view the interface list") 28 | elif name in api_list(): 29 | result_str = f'name: {name}\n {config[name]["name"]}\n {config[name]["explain"]}\n\n' 30 | 31 | result_str += "query example: \n" 32 | for example in config[name]["example"]: 33 | index = config[name]["example"].index(example) 34 | result_str += f'{json.dumps(config[name]["example"][index]["query"], indent=2, ensure_ascii=False)}\n\n' 35 | else: 36 | result_str = f'apiName: {name} not found,please use ”api_list()“ to view the interface list' 37 | 38 | return result_str 39 | 40 | 41 | def api_list(): 42 | """ 43 | 获取接口列表 44 | :return: 45 | """ 46 | return [item for item in list(config.keys()) if item not in exclude] 47 | -------------------------------------------------------------------------------- /plugins/syncmusiclist/netcloudmusic/main.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os.path 3 | import socket 4 | import time 5 | from pprint import pprint 6 | import http.cookies 7 | import datetime 8 | from diskcache import Cache 9 | 10 | import pkg_resources 11 | import requests 12 | from py_mini_racer import py_mini_racer 13 | from .help import api_list 14 | from .utils import format_cookie_str, prase_cookie_str 15 | import urllib.parse 16 | 17 | 18 | class NeteaseCloudMusicApi: 19 | __cookie = None 20 | __ip = None 21 | 22 | 23 | # cache = TTLCache(maxsize=100, ttl=120) # 设置缓存大小为100,缓存项的生存时间为120秒 24 | 25 | def __init__(self, debug=False, cach=False, path=None): 26 | self.path = path 27 | if path: 28 | self.cache = Cache(str(self.path), timeout=120) # 设置缓存目录和过期时间 29 | else: 30 | self.cache = Cache('cache', timeout=120) # 设置缓存目录和过期时间 31 | 32 | self.DEBUG = debug # 是否开启调试模式 33 | self.CACHE = cach # 是否开启缓存 34 | 35 | self.special_api = {"/playlist/track/all": self.playlist_track_all, 36 | "/login/cellphone": self.login_cellphone, 37 | "/inner/version": self.inner_version, 38 | "/login/refresh": self.login_refresh} 39 | 40 | # 载入js代码 41 | resource_path = pkg_resources.resource_filename(__name__, 'NeteaseCloudMusicApi.js') 42 | 43 | with open(resource_path, 'r', encoding='utf-8') as file: 44 | js_code = file.read() 45 | self.ctx = py_mini_racer.MiniRacer() 46 | self.ctx.eval(js_code) 47 | 48 | def request(self, name: str, query: dict = None) -> dict: 49 | """ 50 | 调用接口 51 | 接口文档地址: https://docs.neteasecloudmusicapi.binaryify.com 52 | :param name: api名称 例如: song_url_v1, /song/url/v1 53 | :param query: 请求参数 54 | :return: 请求结果 示例:{"code": 200, "data": {}, "msg": "success"} 55 | """ 56 | 57 | special = { 58 | 'daily_signin': '/daily_signin', 59 | 'fm_trash': '/fm_trash', 60 | 'personal_fm': '/personal_fm', 61 | } 62 | 63 | yubei_special = {'/yunbei/tasks/receipt': '/yunbei/receipt', 64 | '/yunbei/tasks/expense': '/yunbei/expense'} # 这俩个接口准换的路由莫名奇妙 65 | 66 | # 测试name是否合法 67 | name.replace("\\", "/") 68 | if not name.startswith("/"): 69 | if name in special.keys(): 70 | name = special[name] 71 | else: 72 | name = "/" + name 73 | name = name.replace("_", "/") 74 | 75 | # 处理俩个云贝接口名称转换问题 76 | if name in yubei_special.keys(): 77 | name = yubei_special[name] 78 | # print("转换了个麻烦的路由", name) 79 | 80 | if name not in api_list(): 81 | if name not in yubei_special.values(): 82 | raise Exception(f"apiName: {name} not found,please use ”api_list()“ to view the interface list") 83 | 84 | # 生成一个唯一的键,用于在缓存中查找结果 85 | cache_key = (name, frozenset(query.items()) if query else None) 86 | 87 | if self.CACHE: 88 | # 检查缓存中是否已经有了结果 89 | if self.cache.get(cache_key): 90 | return self.cache.get(cache_key) 91 | 92 | if query is None: 93 | query = {} 94 | else: 95 | # 如果存在timestamp参数,那么删除它 96 | if query.get("timestamp"): 97 | del query["timestamp"] 98 | 99 | if query.get("cookie") is None: 100 | query["cookie"] = self.cookie 101 | 102 | if query.get("realIP") is None: 103 | query["realIP"] = self.ip 104 | else: 105 | query["realIP"] = query.get("realIP") 106 | 107 | # 特殊api处理 108 | if name in self.special_api.keys(): 109 | result = self.special_api[name](query) 110 | else: 111 | result = self.call_api(name, query) 112 | 113 | if self.CACHE: 114 | # 将结果存入缓存 115 | self.cache.set(cache_key, result) 116 | 117 | return result 118 | 119 | @staticmethod 120 | def get_local_ip(): 121 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 122 | try: 123 | # doesn't even have to be reachable 124 | s.connect(('10.255.255.255', 1)) 125 | IP = s.getsockname()[0] 126 | except Exception: 127 | print("get local ip error") 128 | IP = "116.25.146.177" 129 | finally: 130 | s.close() 131 | return IP 132 | 133 | @property 134 | def cookie(self): 135 | if self.__cookie is None: 136 | 137 | cookie_path = str(self.path / "cookie_storage") if self.path else "cookie_storage" 138 | if os.path.isfile(cookie_path): 139 | with open(cookie_path, "r", encoding='utf-8') as f: 140 | content = f.read() 141 | try: 142 | cookie_storage = json.loads(content) 143 | # 验证cookie是否过期 144 | create_time_stamp = cookie_storage['create_time_stamp'] 145 | 146 | if time.time() - create_time_stamp > 1296010: 147 | # cookie过期了 148 | self.__cookie = "" 149 | else: 150 | # 判断cookie生成时间是否超过1天 151 | if time.time() - create_time_stamp > 86400: 152 | # 更新cookie 153 | # Todo login_refresh接口返回cookie好像少一些值 154 | # self.request("/login/refresh", {"cookie": cookie_storage['cookie'], "timestamp": time.time()}) 155 | self.cookie = cookie_storage['cookie'] 156 | else: 157 | self.__cookie = cookie_storage['cookie'] 158 | except json.JSONDecodeError and KeyError: 159 | self.__cookie = "" 160 | else: 161 | self.__cookie = "" # 如果没有cookie文件,就设置为空 162 | 163 | return self.__cookie 164 | 165 | @cookie.setter 166 | def cookie(self, value): 167 | if value is None: 168 | self.__cookie = "" 169 | return 170 | 171 | "判断cookie是否合法, 简单检查一下关键的键" 172 | necessary_keys = ["__csrf", "MUSIC_A_T", "MUSIC_R_T"] 173 | cookie_dict = prase_cookie_str(value) 174 | for key in necessary_keys: 175 | if cookie_dict.get(key) is None: 176 | raise Exception(f"cookie is illegal, missing key: {key}.") 177 | 178 | self.__cookie = value 179 | cookie_path = str(self.path / "cookie_storage") if self.path else "cookie_storage" 180 | with open(cookie_path, "w+", encoding='utf-8') as f: 181 | f.write(json.dumps({"cookie": value, "create_time_stamp": time.time()}, indent=2, ensure_ascii=False)) 182 | 183 | @property 184 | def ip(self): 185 | if self.__ip is None: 186 | self.__ip = self.get_local_ip() 187 | return self.__ip 188 | 189 | def call_api(self, name, query): 190 | request_param = self.ctx.call('NeteaseCloudMusicApi.beforeRequest', name, query) # 拿到请求头和请求参数 191 | 192 | # Todo 了解 py_mini_racer 返回没有自动编码 而 node可以 193 | param_data = {} 194 | if request_param["data"] != "": 195 | for item in request_param["data"].split("&"): 196 | # param_data[item.split("=")[0]] = urllib.parse.quote(item.split("=")[1], safe='') # 不需要编码后反而出错 197 | param_data[item.split("=")[0]] = item.split("=")[1] 198 | 199 | if request_param.get("method") == "GET": 200 | response = requests.get(request_param["url"], params=param_data, headers=request_param["headers"]) 201 | else: 202 | response = requests.post(request_param["url"], data=param_data, headers=request_param["headers"]) 203 | 204 | try: 205 | data = json.loads(response.text) 206 | except json.JSONDecodeError: 207 | data = response.text 208 | 209 | response_result = { 210 | "headers": dict(response.headers), 211 | "data": data, 212 | "status": response.status_code, 213 | } 214 | 215 | result = self.ctx.call('NeteaseCloudMusicApi.afterRequest', 216 | json.dumps(response_result), 217 | request_param.get('crypto', None), 218 | request_param['apiName']) # 拿到请求结果 219 | 220 | return result 221 | 222 | def playlist_track_all(self, query): 223 | """ 224 | 获取歌单全部歌曲 225 | :param query: 226 | :return: 227 | """ 228 | 229 | detail_query = {"id": query.get("id"), "cookie": query.get("cookie"), "realIP": query.get("realIP")} 230 | 231 | result = self.call_api("/playlist/detail", detail_query) 232 | 233 | track_all_query = {"detail_result": json.dumps(result), "cookie": query.get("cookie"), 234 | "realIP": query.get("realIP")} 235 | if query.get("limit"): 236 | track_all_query["limit"] = query.get("limit") 237 | if query.get("offset"): 238 | track_all_query["offset"] = query.get("offset") 239 | 240 | result = self.call_api("/playlist/track/all", track_all_query) 241 | return result 242 | 243 | def inner_version(self, query): 244 | """ 245 | 获取所使用的 NeteaseCloudMusicApi 和 NeteaseCloudMusicApi_V8 版本号 246 | :param query: 247 | :return: 248 | """ 249 | result = self.ctx.call('NeteaseCloudMusicApi.inner_version') 250 | return result 251 | 252 | def login_cellphone(self, query): 253 | """ 254 | 手机号登录 255 | :param query: 256 | :return: 257 | """ 258 | result = self.call_api("/login/cellphone", query) 259 | 260 | # 自动 更新cookie 261 | if result["code"] == 200: 262 | if result.get("data").get("cookie"): 263 | # cookie_str = format_cookie_str(result.get("data").get("cookie")) 264 | cookie_str = result.get("data").get("cookie") 265 | result["data"]["cookie"] = cookie_str 266 | self.cookie = cookie_str 267 | return result 268 | 269 | def login_refresh(self, query): 270 | """ 271 | 刷新登录状态 272 | :param query: 273 | :return: 274 | """ 275 | result = self.call_api("/login/refresh", query) 276 | 277 | # 自动 更新cookie 278 | # if result["code"] == 200: 279 | # if result.get("data").get("cookie"): 280 | # # cookie_str = format_cookie_str(result.get("data").get("cookie")) 281 | # cookie_str = result.get("data").get("cookie") 282 | # result["data"]["cookie"] = cookie_str 283 | # pprint(cookie_str) 284 | # self.cookie = cookie_str 285 | return result 286 | -------------------------------------------------------------------------------- /plugins/syncmusiclist/netcloudmusic/utils.py: -------------------------------------------------------------------------------- 1 | from pprint import pprint 2 | 3 | 4 | def format_cookie_str(cookie_str: str) -> str: 5 | """ 6 | 格式化cookie字符串 7 | 功能 8 | 处理以逗号分割的cookie字符串 9 | 删除max-age为0的cookie 10 | 注意: 11 | 传入cookie字符串必须是以 逗号+空格 或 分号+空格 分割的规范cookie字符串 12 | :param cookie_str: 13 | :return: 格式化后的cookie str 14 | """ 15 | 16 | if not cookie_str: 17 | return "" 18 | 19 | # 解析cookie字符串 20 | cookie_dict = prase_cookie_str(cookie_str) 21 | 22 | cookie_valid_dict = {} 23 | # 删除max-age为0的cookie 24 | for item in cookie_dict.keys(): 25 | max_age = cookie_dict[item].get("Max-Age") 26 | if max_age: 27 | max_age = int(max_age) 28 | if max_age != 0: 29 | cookie_valid_dict[item] = cookie_dict[item] 30 | 31 | # 重新拼接cookie字符串 32 | cookie = "" 33 | for item in cookie_valid_dict.keys(): 34 | cookie += item + "=" + cookie_valid_dict[item]["value"] + "; " 35 | for key in cookie_valid_dict[item].keys(): 36 | if key != "value": 37 | cookie += key + "=" + cookie_valid_dict[item][key] + "; " 38 | 39 | return cookie[: -2] 40 | 41 | 42 | def prase_cookie_str(cookie_str: str) -> dict: 43 | """ 44 | 解析cookie字符串 45 | 功能 46 | 处理以逗号分割的cookie字符串 47 | 注意: 48 | 传入cookie字符串必须是以 逗号+空格 或 分号+空格 分割的规范cookie字符串 49 | :param cookie_str: 50 | :return: cookie dict 51 | """ 52 | if not cookie_str: 53 | return {} 54 | 55 | # 解决用逗号分割的问题 56 | cookie_part = [] 57 | for item in cookie_str.split(", "): 58 | cookie_part.extend(item.split("; ")) 59 | 60 | cookies = [] 61 | for item in cookie_part: 62 | if "=" not in item: 63 | # 属于上一个cookie的一部分 64 | cookies[-1] = cookies[-1] + item 65 | else: 66 | cookies.append(item) 67 | 68 | cookie_dict = {} 69 | 70 | current_name = "" 71 | for cookie in cookies: 72 | # print(cookie) 73 | if cookie[-1] == "=": 74 | name = cookie[:-1] 75 | value = "" 76 | else: 77 | part = cookie.split("=") 78 | name = part[0] 79 | value = part[1] 80 | 81 | if name in ["Max-Age", "Expires", "Path", "Domain"]: 82 | cookie_dict[current_name][name] = value 83 | else: 84 | cookie_dict[name] = {"value": value} 85 | current_name = name 86 | 87 | return cookie_dict 88 | 89 | 90 | if __name__ == '__main__': 91 | cookie = ("MUSIC_R_T=1579622000495; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; " 92 | "Path=/openapi/clientlog; Domain=.music.163.com, MUSIC_A_T=1579621885297; Max-Age=2147483647; Expires=Wed, " 93 | "02 Jan 2092 11:39:38 GMT; Path=/wapi/feedback; Domain=.music.163.com, __remember_me=true; " 94 | "Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; Path=/; Domain=.music.163.com, " 95 | "MUSIC_A_T=1579621885297; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; Path=/api/feedback; " 96 | "Domain=.music.163.com, MUSIC_A_T=1579621885297; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; " 97 | "Path=/eapi/clientlog; Domain=.music.163.com, MUSIC_A_T=1579621885297; Max-Age=2147483647; Expires=Wed, " 98 | "02 Jan 2092 11:39:38 GMT; Path=/api/clientlog; Domain=.music.163.com, MUSIC_R_T=1579622000495; " 99 | "Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; Path=/wapi/feedback; Domain=.music.163.com, " 100 | "MUSIC_A_T=1579621885297; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; Path=/weapi/clientlog; " 101 | "Domain=.music.163.com, MUSIC_R_T=1579622000495; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; " 102 | "Path=/neapi/feedback; Domain=.music.163.com, MUSIC_R_T=1579622000495; Max-Age=2147483647; Expires=Wed, " 103 | "02 Jan 2092 11:39:38 GMT; Path=/eapi/clientlog; Domain=.music.163.com, MUSIC_R_T=1579622000495; " 104 | "Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; Path=/api/feedback; Domain=.music.163.com, " 105 | "MUSIC_A_T=1579621885297; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; Path=/weapi/feedback; " 106 | "Domain=.music.163.com, MUSIC_R_T=1579622000495; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; " 107 | "Path=/eapi/feedback; Domain=.music.163.com, MUSIC_A_T=1579621885297; Max-Age=2147483647; Expires=Wed, " 108 | "02 Jan 2092 11:39:38 GMT; Path=/neapi/clientlog; Domain=.music.163.com, MUSIC_R_T=1579622000495; " 109 | "Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; Path=/wapi/clientlog; Domain=.music.163.com, " 110 | "MUSIC_A_T=1579621885297; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; Path=/wapi/clientlog; " 111 | "Domain=.music.163.com, MUSIC_R_T=1579622000495; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; " 112 | "Path=/weapi/feedback; Domain=.music.163.com, NMTID=00OLqRn-wykrFFXdElLpZA3_-aaQtIAAAGMbJSp9A; " 113 | "Max-Age=315360000; Expires=Mon, 12 Dec 2033 08:25:31 GMT; Path=/; Domain=music.163.com, " 114 | "__csrf=4d5e515015723fd3d7edaa5b05f35b4d; Max-Age=1296010; Expires=Sat, 30 Dec 2023 08:25:41 GMT; Path=/; " 115 | "Domain=.music.163.com, MUSIC_R_T=1579622000495; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; " 116 | "Path=/neapi/clientlog; Domain=.music.163.com, MUSIC_A_T=1579621885297; Max-Age=2147483647; Expires=Wed, " 117 | "02 Jan 2092 11:39:38 GMT; Path=/openapi/clientlog; Domain=.music.163.com, MUSIC_A_T=1579621885297; " 118 | "Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; Path=/eapi/feedback; Domain=.music.163.com, " 119 | "MUSIC_R_T=1579622000495; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; Path=/weapi/clientlog; " 120 | "Domain=.music.163.com, MUSIC_R_T=1579622000495; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; " 121 | "Path=/api/clientlog; Domain=.music.163.com, MUSIC_SNS=; Max-Age=0; Expires=Fri, 15 Dec 2023 08:25:31 GMT; " 122 | "Path=/, " 123 | "MUSIC_U=00CCEEF2F7A9825637C9869A455B5CA8E009D905415134A7EDAC2E404A940B2D58BFF7129A413193E9A8FD6D1D497E1E8E9023611BA91D2CB28FA94B53DBE4C42699A30FF1448C8EFAF5B00E73ADD353C52F2E004C094AEAC4BA4D83C6FFBB4CD532DEEAEA8D5584E69AC78110BBA682829C263DA72F5AA290AD826A47F640CA3903AC652E4DDE946ACC4EB8A63E5853FA695B480A919CF84498B7084C5CA9A91297F2CF5AF45C2D545AC0D5C03A1641306BAC0FB6FFD57BC653A91F2483FB52BFE85DE39280B012BC036DF244883D9700480E5FDDCD5A417C60241AE08CD6AA84BFC1C8890AE4A08286144D9D1146E33C67CF7797CDB5A961C85DB5AC492B232601D80D4DB07E4F170F635ABC01E080B4D32408FA0698DAD95AD80CDB99F2F672638048F5116214319175B596BF68B2A7A0269746EABFD919D62C165353725E6B1253A7C5D6774D453DDDCC28524D3378; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; Path=/; Domain=.music.163.com, MUSIC_A_T=1579621885297; Max-Age=2147483647; Expires=Wed, 02 Jan 2092 11:39:38 GMT; Path=/neapi/feedback; Domain=.music.163.com") 124 | pprint(prase_cookie_str(cookie)) 125 | -------------------------------------------------------------------------------- /plugins/syncmusiclist/plex_music.py: -------------------------------------------------------------------------------- 1 | from urllib.parse import urlencode 2 | 3 | from app.log import logger 4 | from app.schemas import MediaServerLibrary 5 | from app.modules.plex import Plex 6 | from plexapi.myplex import MyPlexAccount 7 | from plexapi.library import Hub 8 | 9 | 10 | class PlexMusic(Plex): 11 | """API for Plex 12 | 继承根项目, 实现音乐库相关的api 13 | """ 14 | 15 | def __init__(self): 16 | Plex.__init__(self) 17 | self.music_libraries = [] 18 | self.music_playlists = [] 19 | self.music_names = [] 20 | 21 | def get_user_name(self): 22 | account = MyPlexAccount(self._token) 23 | return account.username 24 | 25 | def get_music_library(self): 26 | """ 27 | 获取媒体服务器所有音乐类型媒体库列表 28 | """ 29 | if not self._plex: 30 | return [] 31 | try: 32 | _libraries = self._plex.library.sections() 33 | except Exception as err: 34 | logger.error(f"Plex获取媒体服务器所有媒体库列表出错:{str(err)}") 35 | return [] 36 | for library in _libraries: 37 | match library.type: 38 | case "artist": 39 | library_type = '音乐' 40 | case _: 41 | continue 42 | self.music_names.append(library.title) 43 | self.music_libraries.append( 44 | MediaServerLibrary( 45 | id=library.key, 46 | name=library.title, 47 | path=library.locations, 48 | type=library_type 49 | ) 50 | ) 51 | return self.music_libraries 52 | 53 | def get_playlists(self): 54 | """获取播放列表""" 55 | playlists = self._plex.playlists() 56 | for playlist in playlists: 57 | if playlist.isAudio: 58 | # music_playlists.append( 59 | # { 60 | # "name": playlist.title, 61 | # "id": playlist.ratingKey, 62 | # "url": playlist.thumbUrl, 63 | # } 64 | # ) 65 | self.music_playlists.append(playlist.title) 66 | return self.music_playlists 67 | 68 | def get_tracks_by_playlist(self, playlist_title): 69 | """获取播放列表的详细歌单""" 70 | if playlist_title not in self.music_playlists: 71 | logger.warn(f"Plex媒体库中播放列表为:{self.music_playlists}\n 不存在: {playlist_title}, 稍后会自动创建,如果失败请手动创建") 72 | return [] 73 | playlist = self._plex.playlist(playlist_title) 74 | # 获取歌单中的歌曲 75 | tracks = playlist.items() 76 | music_names = [i.title for i in tracks] 77 | return music_names 78 | 79 | def create_playlist(self, title, items): 80 | """创建播放列表""" 81 | self._plex.createPlaylist(title=title, items=items, libtype='track') 82 | 83 | def set_tracks_to_playlist(self, playlist_title, tracks): 84 | """添加歌曲到歌单中""" 85 | playlist = self._plex.playlist(playlist_title) 86 | playlist.addItems(tracks) 87 | 88 | def search(self, query, mediatype=None, limit=None, sectionId=None): 89 | """ Returns a list of media items or filter categories from the resulting 90 | `Hub Search `_ 91 | against all items in your Plex library. This searches genres, actors, directors, 92 | playlists, as well as all the obvious media titles. It performs spell-checking 93 | against your search terms (because KUROSAWA is hard to spell). It also provides 94 | contextual search results. So for example, if you search for 'Pernice', it’ll 95 | return 'Pernice Brothers' as the artist result, but we’ll also go ahead and 96 | return your most-listened to albums and tracks from the artist. If you type 97 | 'Arnold' you’ll get a result for the actor, but also the most recently added 98 | movies he’s in. 99 | 100 | Parameters: 101 | query (str): Query to use when searching your library. 102 | mediatype (str, optional): Limit your search to the specified media type. 103 | actor, album, artist, autotag, collection, director, episode, game, genre, 104 | movie, photo, photoalbum, place, playlist, shared, show, tag, track 105 | limit (int, optional): Limit to the specified number of results per Hub. 106 | sectionId (int, optional): The section ID (key) of the library to search within. 107 | """ 108 | results = [] 109 | params = { 110 | 'query': query, 111 | 'X-Plex-Token': self._token, 112 | 'includeCollections': 1, 113 | 'includeExternalMedia': 1} 114 | if limit: 115 | params['limit'] = limit 116 | if sectionId: 117 | params['sectionId'] = sectionId 118 | 119 | 120 | key = f'/hubs/search?{urlencode(params)}' 121 | for hub in self._plex.fetchItems(key, Hub): 122 | if mediatype: 123 | if hub.type == mediatype: 124 | return hub.items 125 | else: 126 | results += hub.items 127 | return results 128 | 129 | def search_music(self, name_singer, exact_match=True): 130 | """通过歌曲名在库中进行搜索""" 131 | name = name_singer[0] 132 | singers = name_singer[1] 133 | if len(self.music_libraries) == 1: 134 | search_res = self.search(name, mediatype='track', limit=20, sectionId=int(self.music_libraries[0].id)) 135 | else: 136 | search_res = self.search(name, mediatype='track', limit=20) 137 | add_items = [] 138 | if len(search_res) > 1: 139 | if exact_match: 140 | add_items = [] 141 | bitrate = 0 142 | # 通过歌手过滤 143 | for i in search_res: 144 | if i.grandparentTitle or i.grandparentTitle in singers: 145 | # add 146 | if i.media[0].bitrate or 1 > bitrate: 147 | bitrate = i.media[0].bitrate or 1 148 | add_items = [i] 149 | else: 150 | str_arts = i.originalTitle or i.grandparentTitle 151 | for singer in singers: 152 | if singer in str_arts: 153 | # add 154 | if i.media[0].bitrate > bitrate: 155 | bitrate = i.media[0].bitrate or 1 156 | add_items = [i] 157 | else: 158 | add_items = search_res[:1] 159 | return add_items 160 | 161 | 162 | if __name__ == '__main__': 163 | pm = PlexMusic() 164 | ml = pm.get_user_name() 165 | pm.get_playlists() 166 | pm.get_tracks_by_playlist('经典华语') 167 | res = pm.search_music(['雨蝶', ['刘君']]) 168 | print(res) 169 | -------------------------------------------------------------------------------- /plugins/syncmusiclist/requirement.txt: -------------------------------------------------------------------------------- 1 | py-mini-racer==0.6.0 2 | diskcache==5.6.3 -------------------------------------------------------------------------------- /plugins/syncmusiclist/requirements.txt: -------------------------------------------------------------------------------- 1 | py-mini-racer==0.6.0 2 | diskcache==5.6.3 -------------------------------------------------------------------------------- /plugins/syncmusiclist/utils.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | def sub_str(text): 5 | return re.sub(r'\s*[\(\(\[【<《][^\)\)\]】>》]*[\)\)\]】>》]\s*', '', text) 6 | 7 | def contains_chinese(text): 8 | """判断字符串是否包含中文字符""" 9 | pattern = re.compile(r'[\u4e00-\u9fa5]') 10 | return bool(pattern.search(text)) 11 | 12 | def extract_chinese(text): 13 | """提取字符串中的中文字符""" 14 | pattern = re.compile(r'[\u4e00-\u9fa5]+') 15 | return pattern.findall(text)[0] 16 | 17 | def change_str(text): 18 | text = sub_str(text) 19 | if contains_chinese(text): 20 | text = extract_chinese(text) 21 | return text 22 | 23 | --------------------------------------------------------------------------------