diff --git a/COPYING b/COPYING new file mode 100755 index 00000000..f288702d --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/approot/admin-database.xml b/approot/admin-database.xml index e2d504a1..4e01c81b 100644 --- a/approot/admin-database.xml +++ b/approot/admin-database.xml @@ -6,62 +6,64 @@
- ${tr:Lms.Admin.Database.database} -
-
- -
- ${media-directory} - ${media-directory-info class="help-block"} +
+ ${tr:Lms.Admin.Database.database} +
+
+ +
+ ${media-directory} + ${media-directory-info class="help-block"} +
+
+
+ +
+ ${update-period} + ${update-period-info class="help-block"} +
+
+
+ +
+ ${update-start-time} + ${update-start-time-info class="help-block"} +
+
+
+ ${tr:Lms.Admin.Database.scan-options} +
+
+ +
+ ${recommendation-engine-type} + ${recommendation-engine-type-info class="help-block"} +
+
+
+ +
+ ${tags} + ${tags-info class="help-block"} +
- -
- ${update-period} - ${update-period-info class="help-block"} +
+ ${apply-btn class="btn-primary"} ${discard-btn} ${immediate-scan-btn class="btn-info"}
-
- -
- ${update-start-time} - ${update-start-time-info class="help-block"} -
-
-
- ${tr:Lms.Admin.Database.scan-options} -
-
- -
- ${recommendation-engine-type} - ${recommendation-engine-type-info class="help-block"} -
-
-
- -
- ${tags} - ${tags-info class="help-block"} -
-
-
-
-
- ${apply-btn class="btn-primary"} ${discard-btn} ${immediate-scan-btn class="btn-info"} -
-
+

diff --git a/approot/admin-initwizard.xml b/approot/admin-initwizard.xml index d58c2bb7..d9ca837a 100644 --- a/approot/admin-initwizard.xml +++ b/approot/admin-initwizard.xml @@ -9,42 +9,44 @@ -
-
- -
- ${admin-login} - ${admin-login-info class="help-block"} +
+
+
+ +
+ ${admin-login} + ${admin-login-info class="help-block"} +
-
-
- -
- ${password} - ${password-info class="help-block"} +
+ +
+ ${password} + ${password-info class="help-block"} +
-
-
- -
- ${password-confirm} - ${password-confirm-info class="help-block"} +
+ +
+ ${password-confirm} + ${password-confirm-info class="help-block"} +
+
+
+
+ ${create-btn class="btn-primary"} +
-
-
- ${create-btn class="btn-primary"} -
-
-
+
diff --git a/approot/admin-user.xml b/approot/admin-user.xml index 9ce8c4f4..c3adc97a 100644 --- a/approot/admin-user.xml +++ b/approot/admin-user.xml @@ -5,8 +5,9 @@
${title} -
- ${} +
+
+ ${}
${} - ${} + ${}
${} -
- -
- ${password} - ${password-info class="help-block"} +
+ +
+ ${password} + ${password-info class="help-block"} +
-
- ${} + ${}
@@ -48,12 +49,13 @@
${} -
-
- ${save-btn class="btn-primary"} +
+
+ ${save-btn class="btn-primary"} +
-
+
diff --git a/approot/login.xml b/approot/login.xml index 175b7df8..7dab178c 100644 --- a/approot/login.xml +++ b/approot/login.xml @@ -4,50 +4,51 @@
- -
-
- -
- ${login-name} -
-
- ${login-name-info} -
+ +
+
+
+ +
+ ${login-name} +
+
+ ${login-name-info} +
+
-
- -
- ${password} -
-
- ${password-info} -
-
+
+ +
+ ${password} +
+
+ ${password-info} +
+
-
- -
-
+
+ +
+
+
+
+
+
+ ${login-btn class="btn-primary"} +
+
-
-
-
- ${login-btn class="btn-primary"} -
-
-
+
- diff --git a/approot/settings.xml b/approot/settings.xml index 239b745e..6b52ee30 100644 --- a/approot/settings.xml +++ b/approot/settings.xml @@ -6,168 +6,170 @@
- ${tr:Lms.Settings.appearance} -
-
-
-
- - ${dark-mode-info clas="help-block"} +
+ ${tr:Lms.Settings.appearance} +
+
+
+
+ + ${dark-mode-info clas="help-block"} +
-
- ${tr:Lms.Settings.audio} -
- ${tr:Lms.Settings.audio-settings-are-local} -
-
-
- -
- ${transcode-mode} - ${transcode-mode-info class="help-block"} -
+ ${tr:Lms.Settings.audio} +
+ ${tr:Lms.Settings.audio-settings-are-local}
-
- -
- ${transcode-format} - ${transcode-format-info class="help-block"} -
-
-
- -
-
- ${transcode-bitrate} - kbps +
+
+ +
+ ${transcode-mode} + ${transcode-mode-info class="help-block"} +
+
+
+ +
+ ${transcode-format} + ${transcode-format-info class="help-block"} +
+
+
+ +
+
+ ${transcode-bitrate} + kbps +
+ ${transcode-bitrate-info class="help-block"}
- ${transcode-bitrate-info class="help-block"}
-
-
- -
- ${replaygain-mode} - ${replaygain-mode-info class="help-block"} -
-
-
- -
-
- ${replaygain-preamp} - dB +
+ +
+ ${replaygain-mode} + ${replaygain-mode-info class="help-block"}
- ${replaygain-preamp-info class="help-block"}
-
-
- -
-
- ${replaygain-preamp-no-rg-info} - dB +
+ +
+
+ ${replaygain-preamp} + dB +
+ ${replaygain-preamp-info class="help-block"}
- ${replaygain-preamp-no-rg-info-info class="help-block"}
-
-
- ${} - ${tr:Lms.Settings.subsonic-api} -
-
-
-
- - ${subsonic-transcode-enable-info class="help-block"} +
+ +
+
+ ${replaygain-preamp-no-rg-info} + dB +
+ ${replaygain-preamp-no-rg-info-info class="help-block"}
-
- -
- ${subsonic-transcode-format} - ${subsonic-transcode-format-info class="help-block"} -
-
-
- -
-
- ${subsonic-transcode-bitrate} - kbps + ${} + ${tr:Lms.Settings.subsonic-api} +
+
+
+
+ + ${subsonic-transcode-enable-info class="help-block"} +
+
+
+
+ +
+ ${subsonic-transcode-format} + ${subsonic-transcode-format-info class="help-block"} +
+
+
+ +
+
+ ${subsonic-transcode-bitrate} + kbps +
+ ${subsonic-transcode-bitrate-info class="help-block"} +
+
+
+ +
+ ${subsonic-artist-list-mode} + ${subsonic-artist-list-mode-info class="help-block"}
- ${subsonic-transcode-bitrate-info class="help-block"}
-
- -
- ${subsonic-artist-list-mode} - ${subsonic-artist-list-mode-info class="help-block"} + ${} + ${tr:Lms.Settings.change-password} +
+ ${} +
+ +
+ ${password-old} + ${password-old-info class="help-block"} +
-
-
- ${} - ${tr:Lms.Settings.change-password} -
- ${} -
- -
- ${password-old} - ${password-old-info class="help-block"} + ${} +
+ +
+ ${password} + ${password-info class="help-block"} +
-
- ${} -
- -
- ${password} - ${password-info class="help-block"} +
+ +
+ ${password-confirm} + ${password-confirm-info class="help-block"} +
-
-
- -
- ${password-confirm} - ${password-confirm-info class="help-block"} -
-
-
-
- ${apply-btn class="btn-primary"} ${discard-btn} +
+
+ ${apply-btn class="btn-primary"} ${discard-btn} +
-
+
diff --git a/docroot/css/S6u8w4BMUTPHjxsAUi-qJCY.woff2 b/docroot/css/S6u8w4BMUTPHjxsAUi-qJCY.woff2 new file mode 100755 index 00000000..69af6c08 Binary files /dev/null and b/docroot/css/S6u8w4BMUTPHjxsAUi-qJCY.woff2 differ diff --git a/docroot/css/S6u8w4BMUTPHjxsAXC-q.woff2 b/docroot/css/S6u8w4BMUTPHjxsAXC-q.woff2 new file mode 100755 index 00000000..3246c128 Binary files /dev/null and b/docroot/css/S6u8w4BMUTPHjxsAXC-q.woff2 differ diff --git a/docroot/css/S6u9w4BMUTPHh6UVSwaPGR_p.woff2 b/docroot/css/S6u9w4BMUTPHh6UVSwaPGR_p.woff2 new file mode 100755 index 00000000..c5d944d2 Binary files /dev/null and b/docroot/css/S6u9w4BMUTPHh6UVSwaPGR_p.woff2 differ diff --git a/docroot/css/S6u9w4BMUTPHh6UVSwiPGQ.woff2 b/docroot/css/S6u9w4BMUTPHh6UVSwiPGQ.woff2 new file mode 100755 index 00000000..f8c37ecd Binary files /dev/null and b/docroot/css/S6u9w4BMUTPHh6UVSwiPGQ.woff2 differ diff --git a/docroot/css/S6uyw4BMUTPHjx4wXg.woff2 b/docroot/css/S6uyw4BMUTPHjx4wXg.woff2 new file mode 100755 index 00000000..6904b664 Binary files /dev/null and b/docroot/css/S6uyw4BMUTPHjx4wXg.woff2 differ diff --git a/docroot/css/S6uyw4BMUTPHjxAwXjeu.woff2 b/docroot/css/S6uyw4BMUTPHjxAwXjeu.woff2 new file mode 100755 index 00000000..0a0ee5ea Binary files /dev/null and b/docroot/css/S6uyw4BMUTPHjxAwXjeu.woff2 differ diff --git a/docroot/css/bootstrap-darkly.min.css b/docroot/css/bootstrap-darkly.min.css index 68048ef2..afed1509 100755 --- a/docroot/css/bootstrap-darkly.min.css +++ b/docroot/css/bootstrap-darkly.min.css @@ -1,4 +1,4 @@ -@import url("https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=swap");/*! +/*! * bootswatch v3.4.1 * Homepage: http://bootswatch.com * Copyright 2012-2019 Thomas Park diff --git a/docroot/css/bootstrap-flatly.min.css b/docroot/css/bootstrap-flatly.min.css index 7d99e1b6..14ea2fc1 100755 --- a/docroot/css/bootstrap-flatly.min.css +++ b/docroot/css/bootstrap-flatly.min.css @@ -1,4 +1,4 @@ -@import url("https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=swap");/*! +/*! * bootswatch v3.4.1 * Homepage: http://bootswatch.com * Copyright 2012-2019 Thomas Park diff --git a/docroot/css/fonts.css b/docroot/css/fonts.css new file mode 100755 index 00000000..f2f53989 --- /dev/null +++ b/docroot/css/fonts.css @@ -0,0 +1,54 @@ +/* latin-ext */ +@font-face { + font-family: 'Lato'; + font-style: italic; + font-weight: 400; + font-display: swap; + src: local('Lato Italic'), local('Lato-Italic'), url(S6u8w4BMUTPHjxsAUi-qJCY.woff2) format('woff2'); + unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Lato'; + font-style: italic; + font-weight: 400; + font-display: swap; + src: local('Lato Italic'), local('Lato-Italic'), url(S6u8w4BMUTPHjxsAXC-q.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +/* latin-ext */ +@font-face { + font-family: 'Lato'; + font-style: normal; + font-weight: 400; + font-display: swap; + src: local('Lato Regular'), local('Lato-Regular'), url(S6uyw4BMUTPHjxAwXjeu.woff2) format('woff2'); + unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Lato'; + font-style: normal; + font-weight: 400; + font-display: swap; + src: local('Lato Regular'), local('Lato-Regular'), url(S6uyw4BMUTPHjx4wXg.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +/* latin-ext */ +@font-face { + font-family: 'Lato'; + font-style: normal; + font-weight: 700; + font-display: swap; + src: local('Lato Bold'), local('Lato-Bold'), url(S6u9w4BMUTPHh6UVSwaPGR_p.woff2) format('woff2'); + unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Lato'; + font-style: normal; + font-weight: 700; + font-display: swap; + src: local('Lato Bold'), local('Lato-Bold'), url(S6u9w4BMUTPHh6UVSwiPGQ.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} diff --git a/docroot/js/mediaplayer.js b/docroot/js/mediaplayer.js index 9022e786..a5c553f1 100644 --- a/docroot/js/mediaplayer.js +++ b/docroot/js/mediaplayer.js @@ -163,6 +163,7 @@ LMS.mediaplayer = function () { _requestNextTrack(); }); _elems.seek.addEventListener("change", function() { + _audioCtx.resume(); let mode = _getAudioMode(); if (!mode) return; diff --git a/src/libs/av/impl/AvInfo.cpp b/src/libs/av/impl/AvInfo.cpp index b8fc392a..ff4d010d 100644 --- a/src/libs/av/impl/AvInfo.cpp +++ b/src/libs/av/impl/AvInfo.cpp @@ -215,7 +215,7 @@ MediaFile::getAttachedPictures(std::size_t nbMaxPictures) const LMS_LOG(AV, ERROR) << "CODEC ID " << avstream->codecpar->codec_id << " not handled in mime type conversion"; } - AVPacket pkt = avstream->attached_pic; + const AVPacket& pkt {avstream->attached_pic}; std::copy(pkt.data, pkt.data + pkt.size, std::back_inserter(picture.data)); diff --git a/src/libs/cover/impl/CoverArtGrabber.cpp b/src/libs/cover/impl/CoverArtGrabber.cpp index efd1c73c..64387d5a 100644 --- a/src/libs/cover/impl/CoverArtGrabber.cpp +++ b/src/libs/cover/impl/CoverArtGrabber.cpp @@ -78,30 +78,59 @@ getFromAvMediaFile(const Av::MediaFile& input) } std::optional -Grabber::getFromDirectory(const std::filesystem::path& p) const +Grabber::getFromDirectory(const std::filesystem::path& p, std::string_view preferredFileName) const { - for (auto coverPath : getCoverPaths(p)) - { - Image image; + const std::multimap coverPaths {getCoverPaths(p)}; - if (image.load(coverPath)) + auto tryLoadImage = [](const std::filesystem::path& p, Image& image) + { + if (!image.load(p)) + { + LMS_LOG(COVER, ERROR) << "Cannot load image in file '" << p.string() << "'"; + return false; + } + + return true; + }; + + auto tryLoadImageFromFilename = [&](std::string_view fileName, Image& image) + { + auto range {coverPaths.equal_range(std::string {fileName})}; + for (auto it {range.first}; it != range.second; ++it) + { + if (tryLoadImage(it->second, image)) + return true; + } + return false; + }; + + Image image; + + if (!preferredFileName.empty() && tryLoadImageFromFilename(preferredFileName, image)) + return image; + + for (std::string_view filename : _preferredFileNames) + { + if (tryLoadImageFromFilename(filename, image)) + return image; + } + + // Just pick one + for (const auto& [filename, coverPath] : coverPaths) + { + if (tryLoadImage(coverPath, image)) return image; - else - LMS_LOG(COVER, ERROR) << "Cannot load image in file '" << coverPath.string() << "'"; } - LMS_LOG(COVER, DEBUG) << "No cover found in directory '" << p.string() << "'"; return std::nullopt; } -std::vector +std::multimap Grabber::getCoverPaths(const std::filesystem::path& directoryPath) const { - std::vector res; + std::multimap res; std::error_code ec; - // TODO handle preferred file names - std::filesystem::directory_iterator itPath(directoryPath, ec); std::filesystem::directory_iterator itEnd; while (!ec && itPath != itEnd) @@ -121,7 +150,7 @@ Grabber::getCoverPaths(const std::filesystem::path& directoryPath) const continue; } - res.push_back(path); + res.emplace(std::filesystem::path{path}.filename().replace_extension("").string(), path); } return res; @@ -177,12 +206,12 @@ Grabber::getFromTrack(Database::Session& dbSession, Database::IdType trackId, st cover = getFromTrack(trackPath); if (!cover) - cover = getFromDirectory(trackPath.parent_path()); + cover = getFromDirectory(trackPath.parent_path(), trackPath.filename().replace_extension("").string()); if (!cover && isMultiDisc) { if (trackPath.parent_path().has_parent_path()) - cover = getFromDirectory(trackPath.parent_path().parent_path()); + cover = getFromDirectory(trackPath.parent_path().parent_path(), {}); } if (!cover) diff --git a/src/libs/cover/impl/CoverArtGrabber.hpp b/src/libs/cover/impl/CoverArtGrabber.hpp index a153b8b4..25eac8cc 100644 --- a/src/libs/cover/impl/CoverArtGrabber.hpp +++ b/src/libs/cover/impl/CoverArtGrabber.hpp @@ -20,10 +20,12 @@ #pragma once #include -#include +#include #include -#include +#include +#include #include +#include #include "cover/ICoverArtGrabber.hpp" #include "database/Types.hpp" @@ -101,8 +103,8 @@ namespace CoverArt Image getFromRelease(Database::Session& dbSession, Database::IdType releaseId, std::size_t size); std::optional getFromTrack(const std::filesystem::path& path) const; - std::vector getCoverPaths(const std::filesystem::path& directoryPath) const; - std::optional getFromDirectory(const std::filesystem::path& path) const; + std::multimap getCoverPaths(const std::filesystem::path& directoryPath) const; + std::optional getFromDirectory(const std::filesystem::path& path, std::string_view preferredFileName) const; std::unique_ptr _defaultCover; // unique_ptr to defer initializing @@ -117,7 +119,7 @@ namespace CoverArt static inline constexpr std::size_t _maxCacheEntries {1000}; static inline const std::vector _fileExtensions {".jpg", ".jpeg", ".png", ".bmp"}; // TODO parametrize static inline constexpr std::size_t _maxFileSize {10000000}; - static inline const std::vector _preferredFileNames {"cover", "front"}; // TODO parametrize + static inline const std::vector _preferredFileNames {"cover", "front"}; // TODO parametrize }; } // namespace CoverArt diff --git a/src/libs/database/impl/Artist.cpp b/src/libs/database/impl/Artist.cpp index 7f2302f7..267c0eee 100644 --- a/src/libs/database/impl/Artist.cpp +++ b/src/libs/database/impl/Artist.cpp @@ -464,7 +464,7 @@ Artist::getSimilarArtists(std::optional offset, std::optionalid()) .bind(self()->id()) .groupBy("a.id") - .orderBy("COUNT(*) DESC") + .orderBy("COUNT(*) DESC, RANDOM()") .limit(count ? static_cast(*count) : -1) .offset(offset ? static_cast(*offset) : -1)}; diff --git a/src/libs/database/impl/Release.cpp b/src/libs/database/impl/Release.cpp index 23646eaa..a50262ae 100644 --- a/src/libs/database/impl/Release.cpp +++ b/src/libs/database/impl/Release.cpp @@ -426,7 +426,7 @@ Release::getSimilarReleases(std::optional offset, std::optionalid()) .bind(self()->id()) .groupBy("r.id") - .orderBy("COUNT(*) DESC") + .orderBy("COUNT(*) DESC, RANDOM()") .limit(count ? static_cast(*count) : -1) .offset(offset ? static_cast(*offset) : -1)}; diff --git a/src/libs/database/impl/Session.cpp b/src/libs/database/impl/Session.cpp index 7cb92cbe..7cf91fcf 100644 --- a/src/libs/database/impl/Session.cpp +++ b/src/libs/database/impl/Session.cpp @@ -40,7 +40,7 @@ namespace Database { -#define LMS_DATABASE_VERSION 23 +#define LMS_DATABASE_VERSION 24 using Version = std::size_t; @@ -261,6 +261,12 @@ CREATE TABLE "user_backup" ( // Just increment the scan version of the settings to make the next scheduled scan rescan everything ScanSettings::get(*this).modify()->incScanVersion(); } + else if (version == 23) + { + // Better cover detection + // Just increment the scan version of the settings to make the next scheduled scan rescan everything + ScanSettings::get(*this).modify()->incScanVersion(); + } else { LMS_LOG(DB, ERROR) << "Database version " << version << " cannot be handled using migration"; diff --git a/src/libs/database/impl/Track.cpp b/src/libs/database/impl/Track.cpp index 26dcc37f..04a16f1f 100644 --- a/src/libs/database/impl/Track.cpp +++ b/src/libs/database/impl/Track.cpp @@ -341,7 +341,7 @@ Track::getSimilarTracks(Session& session, " AND t_c.cluster_id IN (SELECT c.id FROM cluster c INNER JOIN track_cluster t_c ON t_c.cluster_id = c.id WHERE t_c.track_id IN (" + oss.str() + "))" " AND t.id NOT IN (" + oss.str() + ")") .groupBy("t.id") - .orderBy("COUNT(*) DESC") + .orderBy("COUNT(*) DESC, RANDOM()") .limit(size ? static_cast(*size) : -1) .offset(offset ? static_cast(*offset) : -1)}; diff --git a/src/libs/database/impl/TrackList.cpp b/src/libs/database/impl/TrackList.cpp index 47fb5a22..03a20d97 100644 --- a/src/libs/database/impl/TrackList.cpp +++ b/src/libs/database/impl/TrackList.cpp @@ -382,7 +382,7 @@ TrackList::getSimilarTracks(std::optional offset, std::optionalid()) .bind(self()->id()) .groupBy("t.id") - .orderBy("COUNT(*) DESC") + .orderBy("COUNT(*) DESC, RANDOM()") .limit(size ? static_cast(*size) : -1) .offset(offset ? static_cast(*offset) : -1)}; diff --git a/src/libs/metadata/impl/TagLibParser.cpp b/src/libs/metadata/impl/TagLibParser.cpp index 5fa1bfea..2a83651a 100644 --- a/src/libs/metadata/impl/TagLibParser.cpp +++ b/src/libs/metadata/impl/TagLibParser.cpp @@ -26,8 +26,10 @@ #include #include #include +#include #include #include +#include #include #include "utils/Logger.hpp" @@ -399,6 +401,16 @@ TagLibParser::parse(const std::filesystem::path& p, bool debug) if (!flacFile->pictureList().isEmpty()) track.hasCover = true; } + else if (TagLib::Ogg::Vorbis::File* vorbisFile {dynamic_cast(f.file())}) + { + if (!vorbisFile->tag()->pictureList().isEmpty()) + track.hasCover = true; + } + else if (TagLib::Ogg::Opus::File* opusFile {dynamic_cast(f.file())}) + { + if (!opusFile->tag()->pictureList().isEmpty()) + track.hasCover = true; + } for (const auto& property : properties) { diff --git a/src/libs/scanner/impl/MediaScanner.cpp b/src/libs/scanner/impl/MediaScanner.cpp index 36a3e659..0529ff4a 100644 --- a/src/libs/scanner/impl/MediaScanner.cpp +++ b/src/libs/scanner/impl/MediaScanner.cpp @@ -65,7 +65,9 @@ getNextFirstOfMonth(Wt::WDate current) bool isFileSupported(const std::filesystem::path& file, const std::unordered_set& extensions) { - return (extensions.find(file.extension()) != extensions.end()); + const std::filesystem::path extension {StringUtils::stringToLower(file.extension().string())}; + + return (extensions.find(extension) != extensions.end()); } bool @@ -310,7 +312,7 @@ MediaScanner::getStatus() { Status res; - std::unique_lock lock {_statusMutex}; + std::shared_lock lock {_statusMutex}; res.currentState = _curState; res.nextScheduledScan = _nextScheduledScan; @@ -367,7 +369,7 @@ MediaScanner::scheduleNextScan() } { - std::unique_lock lock {_statusMutex}; + std::unique_lock lock {_statusMutex}; _curState = nextScanDateTime.isValid() ? State::Scheduled : State::NotScheduled; _nextScheduledScan = nextScanDateTime; } @@ -421,8 +423,10 @@ MediaScanner::scan(boost::system::error_code err) if (err) return; + scanStarted().emit(); + { - std::unique_lock lock {_statusMutex}; + std::unique_lock lock {_statusMutex}; _curState = State::InProgress; _nextScheduledScan = {}; } @@ -464,7 +468,7 @@ MediaScanner::scan(boost::system::error_code err) { stats.stopTime = Wt::WLocalDateTime::currentDateTime().toUTC(); { - std::unique_lock lock {_statusMutex}; + std::unique_lock lock {_statusMutex}; _lastCompleteScanStats = std::move(stats); _inProgressScanStats.reset(); @@ -476,7 +480,7 @@ MediaScanner::scan(boost::system::error_code err) } else { - std::unique_lock lock {_statusMutex}; + std::unique_lock lock {_statusMutex}; _curState = State::NotScheduled; _inProgressScanStats.reset(); @@ -566,7 +570,12 @@ MediaScanner::refreshScanSettings() _startTime = scanSettings->getUpdateStartTime(); _updatePeriod = scanSettings->getUpdatePeriod(); - _fileExtensions = scanSettings->getAudioFileExtensions(); + { + const auto fileExtensions {scanSettings->getAudioFileExtensions()}; + _fileExtensions.clear(); + std::transform(std::cbegin(fileExtensions), std::end(fileExtensions), std::inserter(_fileExtensions, std::begin(_fileExtensions)), + [](const std::filesystem::path& extension) { return std::filesystem::path{ StringUtils::stringToLower(extension.string()) }; }); + } _mediaDirectory = scanSettings->getMediaDirectory(); _recommendationEngineType = scanSettings->getRecommendationEngineType(); @@ -584,13 +593,15 @@ MediaScanner::refreshScanSettings() void MediaScanner::notifyInProgress(const ScanStats& stats) { + const ScanProgressStats progressStats {stats.toProgressStats()}; + { - std::unique_lock lock {_statusMutex}; - _inProgressScanStats = stats.toProgressStats(); + std::unique_lock lock {_statusMutex}; + _inProgressScanStats = progressStats; } - std::chrono::system_clock::time_point now {std::chrono::system_clock::now()}; - _sigScanInProgress(*_inProgressScanStats); + const std::chrono::system_clock::time_point now {std::chrono::system_clock::now()}; + _sigScanInProgress(progressStats); _lastScanInProgressEmit = now; } diff --git a/src/libs/scanner/impl/MediaScanner.hpp b/src/libs/scanner/impl/MediaScanner.hpp index a04ceb39..8c19defb 100644 --- a/src/libs/scanner/impl/MediaScanner.hpp +++ b/src/libs/scanner/impl/MediaScanner.hpp @@ -20,7 +20,7 @@ #pragma once #include -#include +#include #include #include @@ -59,6 +59,7 @@ class MediaScanner : public IMediaScanner Status getStatus() override; + Wt::Signal<>& scanStarted() override { return _sigScanStarted; } Wt::Signal<>& scanComplete() override { return _sigScanComplete; } Wt::Signal& scanInProgress() override { return _sigScanInProgress; } Wt::Signal& scheduled() override { return _sigScheduled; } @@ -88,21 +89,22 @@ class MediaScanner : public IMediaScanner void notifyInProgressIfNeeded(const ScanStats& stats); void notifyInProgress(const ScanStats& stats); - bool _running {}; - Wt::WIOService _ioService; - boost::asio::system_timer _scheduleTimer {_ioService}; - Wt::Signal<> _sigScanComplete; - Wt::Signal _sigScanInProgress; + bool _running {}; + Wt::WIOService _ioService; + boost::asio::system_timer _scheduleTimer {_ioService}; + Wt::Signal<> _sigScanStarted; + Wt::Signal<> _sigScanComplete; + Wt::Signal _sigScanInProgress; std::chrono::system_clock::time_point _lastScanInProgressEmit {}; - Wt::Signal _sigScheduled; - Database::Session _dbSession; - std::unique_ptr _metadataParser; + Wt::Signal _sigScheduled; + Database::Session _dbSession; + std::unique_ptr _metadataParser; - std::mutex _statusMutex; - State _curState {State::NotScheduled}; - std::optional _lastCompleteScanStats; + std::shared_mutex _statusMutex; + State _curState {State::NotScheduled}; + std::optional _lastCompleteScanStats; std::optional _inProgressScanStats; - Wt::WDateTime _nextScheduledScan; + Wt::WDateTime _nextScheduledScan; // Current scan settings std::size_t _scanVersion {}; diff --git a/src/libs/scanner/include/scanner/IMediaScanner.hpp b/src/libs/scanner/include/scanner/IMediaScanner.hpp index e50be005..1c0d3fdc 100644 --- a/src/libs/scanner/include/scanner/IMediaScanner.hpp +++ b/src/libs/scanner/include/scanner/IMediaScanner.hpp @@ -64,6 +64,9 @@ class IMediaScanner virtual Status getStatus() = 0; + // Called just after scan start + virtual Wt::Signal<>& scanStarted() = 0; + // Called just after scan complete virtual Wt::Signal<>& scanComplete() = 0; diff --git a/src/libs/subsonic/CMakeLists.txt b/src/libs/subsonic/CMakeLists.txt index 34d3d68d..439e6289 100644 --- a/src/libs/subsonic/CMakeLists.txt +++ b/src/libs/subsonic/CMakeLists.txt @@ -1,6 +1,7 @@ add_library(lmssubsonic SHARED impl/ParameterParsing.cpp + impl/Scan.cpp impl/Stream.cpp impl/SubsonicId.cpp impl/SubsonicResource.cpp @@ -26,6 +27,7 @@ target_link_libraries(lmssubsonic PRIVATE target_link_libraries(lmssubsonic PUBLIC lmsdatabase + lmsscanner wt ) diff --git a/src/libs/subsonic/impl/RequestContext.hpp b/src/libs/subsonic/impl/RequestContext.hpp index ec10a226..cd41100b 100644 --- a/src/libs/subsonic/impl/RequestContext.hpp +++ b/src/libs/subsonic/impl/RequestContext.hpp @@ -38,6 +38,7 @@ namespace API::Subsonic const Wt::Http::ParameterMap& parameters; Database::Session& dbSession; std::string userName; + std::string clientName; }; } diff --git a/src/libs/subsonic/impl/Scan.cpp b/src/libs/subsonic/impl/Scan.cpp new file mode 100644 index 00000000..42716069 --- /dev/null +++ b/src/libs/subsonic/impl/Scan.cpp @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2020 Emeric Poupon + * + * This file is part of LMS. + * + * LMS is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * LMS is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with LMS. If not, see . + */ + +#include "Scan.hpp" + +#include "scanner/IMediaScanner.hpp" +#include "utils/Service.hpp" + +namespace API::Subsonic::Scan +{ + using namespace Scanner; + + static + Response::Node + createStatusResponseNode() + { + Response::Node statusResponse; + + const IMediaScanner::Status scanStatus {ServiceProvider::get()->getStatus()}; + + statusResponse.setAttribute("scanning", scanStatus.currentState == IMediaScanner::State::InProgress ? "true" : "false"); + if (scanStatus.currentState == IMediaScanner::State::InProgress && scanStatus.inProgressScanStats) + statusResponse.setAttribute("count", scanStatus.inProgressScanStats->processedFiles); + + return statusResponse; + } + + + Response + handleGetScanStatus(RequestContext& context) + { + Response response {Response::createOkResponse(context)}; + response.addNode("scanStatus", createStatusResponseNode()); + + return response; + } + + Response + handleStartScan(RequestContext& context) + { + ServiceProvider::get()->requestImmediateScan(); + + Response response {Response::createOkResponse(context)}; + response.addNode("scanStatus", createStatusResponseNode()); + + return response; + } +} + diff --git a/src/libs/subsonic/impl/Scan.hpp b/src/libs/subsonic/impl/Scan.hpp new file mode 100644 index 00000000..3074a7b5 --- /dev/null +++ b/src/libs/subsonic/impl/Scan.hpp @@ -0,0 +1,30 @@ +/* + * Copyright (C) 2020 Emeric Poupon + * + * This file is part of LMS. + * + * LMS is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * LMS is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with LMS. If not, see . + */ + +#pragma once + +#include "RequestContext.hpp" +#include "SubsonicResponse.hpp" + +namespace API::Subsonic::Scan +{ + Response handleGetScanStatus(RequestContext& context); + Response handleStartScan(RequestContext& context); +} + diff --git a/src/libs/subsonic/impl/SubsonicResource.cpp b/src/libs/subsonic/impl/SubsonicResource.cpp index a78d028a..6d793f20 100644 --- a/src/libs/subsonic/impl/SubsonicResource.cpp +++ b/src/libs/subsonic/impl/SubsonicResource.cpp @@ -42,6 +42,7 @@ #include "utils/Utils.hpp" #include "ParameterParsing.hpp" #include "RequestContext.hpp" +#include "Scan.hpp" #include "Stream.hpp" #include "SubsonicResponse.hpp" @@ -140,15 +141,15 @@ getClientInfo(const Wt::Http::ParameterMap& parameters) ClientInfo res; // Mandatory parameters + res.name = getMandatoryParameterAs(parameters, "c"); res.version = getMandatoryParameterAs(parameters, "v"); if (res.version.major > API_VERSION_MAJOR) throw ServerMustUpgradeError {}; if (res.version.major < API_VERSION_MAJOR) throw ClientMustUpgradeError {}; - if (res.version.minor > API_VERSION_MINOR) + if (res.version.minor > Response::getAPIMinorVersion(res.name)) throw ServerMustUpgradeError {}; - res.name = getMandatoryParameterAs(parameters, "c"); res.user = getMandatoryParameterAs(parameters, "u"); res.password = decodePasswordIfNeeded(getMandatoryParameterAs(parameters, "p")); @@ -289,18 +290,18 @@ trackToResponseNode(const Track::pointer& track, Session& dbSession, const User: trackResponse.setAttribute("isDir", "false"); trackResponse.setAttribute("title", track->getName()); if (track->getTrackNumber()) - trackResponse.setAttribute("track", std::to_string(*track->getTrackNumber())); + trackResponse.setAttribute("track", *track->getTrackNumber()); if (track->getDiscNumber()) - trackResponse.setAttribute("discNumber", std::to_string(*track->getDiscNumber())); + trackResponse.setAttribute("discNumber", *track->getDiscNumber()); if (track->getYear()) - trackResponse.setAttribute("year", std::to_string(*track->getYear())); + trackResponse.setAttribute("year", *track->getYear()); trackResponse.setAttribute("path", getTrackPath(track)); { std::error_code ec; const auto fileSize {std::filesystem::file_size(track->getPath(), ec)}; if (!ec) - trackResponse.setAttribute("size", std::to_string(fileSize)); + trackResponse.setAttribute("size", fileSize); } if (track->getPath().has_extension()) @@ -330,7 +331,7 @@ trackToResponseNode(const Track::pointer& track, Session& dbSession, const User: trackResponse.setAttribute("parent", IdToString({Id::Type::Release, track->getRelease().id()})); } - trackResponse.setAttribute("duration", std::to_string(std::chrono::duration_cast(track->getDuration()).count())); + trackResponse.setAttribute("duration", std::chrono::duration_cast(track->getDuration()).count()); trackResponse.setAttribute("type", "music"); if (user->hasStarredTrack(track)) @@ -354,7 +355,7 @@ trackBookmarkToResponseNode(const TrackBookmark::pointer& trackBookmark) { Response::Node trackBookmarkNode; - trackBookmarkNode.setAttribute("position", std::to_string(trackBookmark->getOffset().count())); + trackBookmarkNode.setAttribute("position", trackBookmark->getOffset().count()); if (!trackBookmark->getComment().empty()) trackBookmarkNode.setAttribute("comment", trackBookmark->getComment()); trackBookmarkNode.setAttribute("created", reportedCreatedBookmarkDate); @@ -373,7 +374,7 @@ releaseToResponseNode(const Release::pointer& release, Session& dbSession, const if (id3) { albumNode.setAttribute("name", release->getName()); - albumNode.setAttribute("songCount", std::to_string(release->getTracksCount())); + albumNode.setAttribute("songCount", release->getTracksCount()); albumNode.setAttribute("duration", std::to_string(std::chrono::duration_cast(release->getDuration()).count())); } else @@ -386,7 +387,7 @@ releaseToResponseNode(const Release::pointer& release, Session& dbSession, const albumNode.setAttribute("coverArt", IdToString({Id::Type::Release, release.id()})); auto releaseYear {release->getReleaseYear()}; if (releaseYear) - albumNode.setAttribute("year", std::to_string(*releaseYear)); + albumNode.setAttribute("year", *releaseYear); auto artists {release->getReleaseArtists()}; if (artists.empty()) @@ -442,7 +443,7 @@ artistToResponseNode(const User::pointer& user, const Artist::pointer& artist, b artistNode.setAttribute("name", artist->getName()); if (id3) - artistNode.setAttribute("albumCount", std::to_string(artist->getReleaseCount())); + artistNode.setAttribute("albumCount", artist->getReleaseCount()); if (user->hasStarredArtist(artist)) artistNode.setAttribute("starred", reportedStarredDate); @@ -457,8 +458,8 @@ clusterToResponseNode(const Cluster::pointer& cluster) Response::Node clusterNode; clusterNode.setValue(cluster->getName()); - clusterNode.setAttribute("songCount", std::to_string(cluster->getTracksCount())); - clusterNode.setAttribute("albumCount", std::to_string(cluster->getReleasesCount())); + clusterNode.setAttribute("songCount", cluster->getTracksCount()); + clusterNode.setAttribute("albumCount", cluster->getReleasesCount()); return clusterNode; } @@ -492,9 +493,9 @@ userToResponseNode(const User::pointer& user) static Response -handlePingRequest(RequestContext&) +handlePingRequest(RequestContext& context) { - return Response::createOkResponse(); + return Response::createOkResponse(context); } static @@ -520,7 +521,7 @@ handleChangePassword(RequestContext& context) user.modify()->setPasswordHash(hash); user.modify()->clearAuthTokens(); - return Response::createOkResponse(); + return Response::createOkResponse(context); } static @@ -575,7 +576,7 @@ handleCreatePlaylistRequest(RequestContext& context) TrackListEntry::create(context.dbSession, track, tracklist ); } - return Response::createOkResponse(); + return Response::createOkResponse(context); } static @@ -598,7 +599,7 @@ handleCreateUserRequest(RequestContext& context) User::pointer user {User::create(context.dbSession, username, hash)}; - return Response::createOkResponse(); + return Response::createOkResponse(context); } static @@ -625,7 +626,7 @@ handleDeletePlaylistRequest(RequestContext& context) tracklist.remove(); - return Response::createOkResponse(); + return Response::createOkResponse(context); } static @@ -646,14 +647,14 @@ handleDeleteUserRequest(RequestContext& context) user.remove(); - return Response::createOkResponse(); + return Response::createOkResponse(context); } static Response -handleGetLicenseRequest(RequestContext&) +handleGetLicenseRequest(RequestContext& context) { - Response response {Response::createOkResponse()}; + Response response {Response::createOkResponse(context)}; Response::Node& licenseNode {response.createNode("license")}; licenseNode.setAttribute("licenseExpires", "2025-09-03T14:46:43"); @@ -679,7 +680,7 @@ handleGetRandomSongsRequest(RequestContext& context) auto tracks {Track::getAllRandom(context.dbSession, {}, size)}; - Response response {Response::createOkResponse()}; + Response response {Response::createOkResponse(context)}; Response::Node& randomSongsNode {response.createNode("randomSongs")}; for (const Track::pointer& track : tracks) @@ -756,7 +757,7 @@ handleGetAlbumListRequestCommon(const RequestContext& context, bool id3) else throw NotImplementedGenericError {}; - Response response {Response::createOkResponse()}; + Response response {Response::createOkResponse(context)}; Response::Node& albumListNode {response.createNode(id3 ? "albumList2" : "albumList")}; for (const Release::pointer& release : releases) @@ -799,7 +800,7 @@ handleGetAlbumRequest(RequestContext& context) if (!user) throw UserNotAuthorizedError {}; - Response response {Response::createOkResponse()}; + Response response {Response::createOkResponse(context)}; Response::Node releaseNode {releaseToResponseNode(release, context.dbSession, user, true /* id3 */)}; auto tracks {release->getTracks()}; @@ -831,7 +832,7 @@ handleGetArtistRequest(RequestContext& context) if (!user) throw UserNotAuthorizedError {}; - Response response {Response::createOkResponse()}; + Response response {Response::createOkResponse(context)}; Response::Node artistNode {artistToResponseNode(user, artist, true /* id3 */)}; auto releases {artist->getReleases()}; @@ -855,7 +856,7 @@ handleGetArtistInfoRequestCommon(RequestContext& context, bool id3) // Optional params std::size_t count {getParameterAs(context.parameters, "count").value_or(20)}; - Response response {Response::createOkResponse()}; + Response response {Response::createOkResponse(context)}; Response::Node& artistInfoNode {response.createNode(id3 ? "artistInfo2" : "artistInfo")}; { @@ -908,7 +909,7 @@ static Response handleGetArtistsRequest(RequestContext& context) { - Response response {Response::createOkResponse()}; + Response response {Response::createOkResponse(context)}; Response::Node& artistsNode {response.createNode("artists")}; Response::Node& indexNode {artistsNode.createArrayChild("index")}; @@ -950,7 +951,7 @@ handleGetMusicDirectoryRequest(RequestContext& context) // Mandatory params Id id {getMandatoryParameterAs(context.parameters, "id")}; - Response response {Response::createOkResponse()}; + Response response {Response::createOkResponse(context)}; Response::Node& directoryNode {response.createNode("directory")}; directoryNode.setAttribute("id", IdToString(id)); @@ -1014,9 +1015,9 @@ handleGetMusicDirectoryRequest(RequestContext& context) static Response -handleGetMusicFoldersRequest(RequestContext&) +handleGetMusicFoldersRequest(RequestContext& context) { - Response response {Response::createOkResponse()}; + Response response {Response::createOkResponse(context)}; Response::Node& musicFoldersNode {response.createNode("musicFolders")}; Response::Node& musicFolderNode {musicFoldersNode.createArrayChild("musicFolder")}; @@ -1030,7 +1031,7 @@ static Response handleGetGenresRequest(RequestContext& context) { - Response response {Response::createOkResponse()}; + Response response {Response::createOkResponse(context)}; Response::Node& genresNode {response.createNode("genres")}; @@ -1052,7 +1053,7 @@ static Response handleGetIndexesRequest(RequestContext& context) { - Response response {Response::createOkResponse()}; + Response response {Response::createOkResponse(context)}; Response::Node& artistsNode {response.createNode("indexes")}; Response::Node& indexNode {artistsNode.createArrayChild("index")}; @@ -1128,7 +1129,7 @@ handleGetSimilarSongsRequestCommon(RequestContext& context, bool id3) Random::shuffleContainer(tracks); - Response response {Response::createOkResponse()}; + Response response {Response::createOkResponse(context)}; Response::Node& similarSongsNode {response.createNode(id3 ? "similarSongs2" : "similarSongs")}; for (const Track::pointer& track : tracks) similarSongsNode.addArrayChild("song", trackToResponseNode(track, context.dbSession, user)); @@ -1160,7 +1161,7 @@ handleGetStarredRequestCommon(RequestContext& context, bool id3) if (!user) throw UserNotAuthorizedError {}; - Response response {Response::createOkResponse()}; + Response response {Response::createOkResponse(context)}; Response::Node& starredNode {response.createNode(id3 ? "starred2" : "starred")}; { @@ -1207,8 +1208,8 @@ tracklistToResponseNode(const TrackList::pointer& tracklist, Session&) playlistNode.setAttribute("id", IdToString({Id::Type::Playlist, tracklist.id()})); playlistNode.setAttribute("name", tracklist->getName()); - playlistNode.setAttribute("songCount", std::to_string(tracklist->getCount())); - playlistNode.setAttribute("duration", std::to_string(std::chrono::duration_cast(tracklist->getDuration()).count())); + playlistNode.setAttribute("songCount", tracklist->getCount()); + playlistNode.setAttribute("duration", std::chrono::duration_cast(tracklist->getDuration()).count()); playlistNode.setAttribute("public", tracklist->isPublic() ? "true" : "false"); playlistNode.setAttribute("created", ""); playlistNode.setAttribute("owner", tracklist->getUser()->getLoginName()); @@ -1235,7 +1236,7 @@ handleGetPlaylistRequest(RequestContext& context) if (!tracklist) throw RequestedDataNotFoundError {}; - Response response {Response::createOkResponse()}; + Response response {Response::createOkResponse(context)}; Response::Node playlistNode {tracklistToResponseNode(tracklist, context.dbSession)}; auto entries {tracklist->getEntries()}; @@ -1257,7 +1258,7 @@ handleGetPlaylistsRequest(RequestContext& context) if (!user) throw UserNotAuthorizedError {}; - Response response {Response::createOkResponse()}; + Response response {Response::createOkResponse(context)}; Response::Node& playlistsNode {response.createNode("playlists")}; auto tracklists {TrackList::getAll(context.dbSession, user, TrackList::Type::Playlist)}; @@ -1294,7 +1295,7 @@ handleGetSongsByGenreRequest(RequestContext& context) if (!user) throw UserNotAuthorizedError {}; - Response response {Response::createOkResponse()}; + Response response {Response::createOkResponse(context)}; Response::Node& songsByGenreNode {response.createNode("songsByGenre")}; bool more; @@ -1319,7 +1320,7 @@ handleGetUserRequest(RequestContext& context) if (!user) throw RequestedDataNotFoundError {}; - Response response {Response::createOkResponse()}; + Response response {Response::createOkResponse(context)}; response.addNode("user", userToResponseNode(user)); return response; @@ -1331,7 +1332,7 @@ handleGetUsersRequest(RequestContext& context) { auto transaction {context.dbSession.createSharedTransaction()}; - Response response {Response::createOkResponse()}; + Response response {Response::createOkResponse(context)}; Response::Node& usersNode {response.createNode("users")}; const auto users {User::getAll(context.dbSession)}; @@ -1364,7 +1365,7 @@ handleSearchRequestCommon(RequestContext& context, bool id3) if (!user) throw UserNotAuthorizedError {}; - Response response {Response::createOkResponse()}; + Response response {Response::createOkResponse(context)}; Response::Node& searchResult2Node {response.createNode(id3 ? "searchResult3" : "searchResult2")}; bool more; @@ -1473,7 +1474,7 @@ handleStarRequest(RequestContext& context) user.modify()->starTrack(track); } - return Response::createOkResponse(); + return Response::createOkResponse(context); } static @@ -1530,7 +1531,7 @@ handleUnstarRequest(RequestContext& context) } - return Response::createOkResponse(); + return Response::createOkResponse(context); } static @@ -1562,7 +1563,7 @@ handleUpdateUserRequest(RequestContext& context) user.modify()->clearAuthTokens(); } - return Response::createOkResponse(); + return Response::createOkResponse(context); } static @@ -1626,7 +1627,7 @@ handleUpdatePlaylistRequest(RequestContext& context) TrackListEntry::create(context.dbSession, track, tracklist ); } - return Response::createOkResponse(); + return Response::createOkResponse(context); } static @@ -1641,7 +1642,7 @@ handleGetBookmarks(RequestContext& context) const auto bookmarks {TrackBookmark::getByUser(context.dbSession, user)}; - Response response {Response::createOkResponse()}; + Response response {Response::createOkResponse(context)}; Response::Node& bookmarksNode {response.createNode("bookmarks")}; for (const TrackBookmark::pointer& bookmark : bookmarks) @@ -1686,7 +1687,7 @@ handleCreateBookmark(RequestContext& context) if (comment) bookmark.modify()->setComment(*comment); - return Response::createOkResponse(); + return Response::createOkResponse(context); } static @@ -1714,7 +1715,7 @@ handleDeleteBookmark(RequestContext& context) bookmark.remove(); - return Response::createOkResponse(); + return Response::createOkResponse(context); } static @@ -1860,8 +1861,8 @@ static std::unordered_map requestEntryPoints {"savePlayQueue", {handleNotImplemented, false}}, // Media library scanning - {"getScanStatus", {handleNotImplemented, true}}, - {"startScan", {handleNotImplemented, true}}, + {"getScanStatus", {Scan::handleGetScanStatus, true}}, + {"startScan", {Scan::handleStartScan, true}}, }; using MediaRetrievalHandlerFunc = std::function; @@ -1890,12 +1891,15 @@ SubsonicResource::handleRequest(const Wt::Http::Request &request, Wt::Http::Resp // Optional parameters const ResponseFormat format {getParameterAs(parameters, "f").value_or("xml") == "json" ? ResponseFormat::json : ResponseFormat::xml}; + std::string clientName; + try { - // Mandatory parameters const ClientInfo clientInfo {getClientInfo(parameters)}; + clientName = clientInfo.name; + SessionPool::ScopedSession dbSession {_sessionPool}; switch (ServiceProvider::get()->checkUserPassword(dbSession.get(), @@ -1910,7 +1914,7 @@ SubsonicResource::handleRequest(const Wt::Http::Request &request, Wt::Http::Resp throw LoginThrottledGenericError {}; } - RequestContext requestContext {parameters, dbSession.get(), clientInfo.user}; + RequestContext requestContext {parameters, dbSession.get(), clientInfo.user, clientInfo.name}; auto itEntryPoint {requestEntryPoints.find(requestPath)}; if (itEntryPoint != requestEntryPoints.end()) @@ -1944,21 +1948,12 @@ SubsonicResource::handleRequest(const Wt::Http::Request &request, Wt::Http::Resp LMS_LOG(API_SUBSONIC, ERROR) << "Unhandled command '" << requestPath << "'"; throw UnknownEntryPointGenericError {}; } - catch (const NotImplementedGenericError& e) - { - LMS_LOG(API_SUBSONIC, INFO) << "Command '" << requestPath << "'" - << ", params = [" << parameterMapToDebugString(request.getParameterMap()) << "]" - << ", code = " << static_cast(e.getCode()) << ", msg = '" << static_cast(e).getMessage() << "'"; - Response resp {Response::createFailedResponse(e)}; - resp.write(response.out(), format); - response.setMimeType(ResponseFormatToMimeType(format)); - } catch (const Error& e) { LMS_LOG(API_SUBSONIC, ERROR) << "Error while processing request '" << requestPath << "'" << ", params = [" << parameterMapToDebugString(request.getParameterMap()) << "]" << ", code = " << static_cast(e.getCode()) << ", msg = '" << e.getMessage() << "'"; - Response resp {Response::createFailedResponse(e)}; + Response resp {Response::createFailedResponse(clientName, e)}; resp.write(response.out(), format); response.setMimeType(ResponseFormatToMimeType(format)); } diff --git a/src/libs/subsonic/impl/SubsonicResponse.cpp b/src/libs/subsonic/impl/SubsonicResponse.cpp index b6b2431d..9572d18e 100644 --- a/src/libs/subsonic/impl/SubsonicResponse.cpp +++ b/src/libs/subsonic/impl/SubsonicResponse.cpp @@ -28,6 +28,7 @@ #include #include "utils/Exception.hpp" +#include "utils/String.hpp" namespace API::Subsonic { @@ -46,6 +47,15 @@ ResponseFormatToMimeType(ResponseFormat format) void Response::Node::setValue(std::string_view value) +{ + if (!_children.empty() || !_childrenArrays.empty()) + throw LmsException {"Node already has children"}; + + _value = std::string {value}; +} + +void +Response::Node::setValue(long long value) { if (!_children.empty() || !_childrenArrays.empty()) throw LmsException {"Node already has children"}; @@ -55,6 +65,12 @@ Response::Node::setValue(std::string_view value) void Response::Node::setAttribute(std::string_view key, std::string_view value) +{ + _attributes[std::string {key}] = std::string {value}; +} + +void +Response::Node::setAttribute(std::string_view key, long long value) { _attributes[std::string {key}] = value; } @@ -62,7 +78,7 @@ Response::Node::setAttribute(std::string_view key, std::string_view value) void Response::Node::addChild(const std::string& key, Node node) { - if (!_value.empty()) + if (_value.valueless_by_exception()) throw LmsException {"Node already has a value"}; _children[key].emplace_back(std::move(node)); @@ -71,7 +87,7 @@ Response::Node::addChild(const std::string& key, Node node) void Response::Node::addArrayChild(const std::string& key, Node node) { - if (!_value.empty()) + if (_value.valueless_by_exception()) throw LmsException {"Node already has a value"}; _childrenArrays[key].emplace_back(std::move(node)); @@ -93,25 +109,25 @@ Response::Node::createArrayChild(const std::string& key) } Response -Response::createOkResponse() +Response::createOkResponse(const RequestContext& context) { Response response; Node& responseNode {response._root.createChild("subsonic-response")}; responseNode.setAttribute("status", "ok"); - responseNode.setAttribute("version", API_VERSION_STR); + responseNode.setAttribute("version", std::string {QUOTEME(API_VERSION_MAJOR) "."} + std::to_string(getAPIMinorVersion(context.clientName)) + ".0"); return response; } Response -Response::createFailedResponse(const Error& error) +Response::createFailedResponse(std::string_view clientName, const Error& error) { Response response; Node& responseNode {response._root.createChild("subsonic-response")}; responseNode.setAttribute("status", "failed"); - responseNode.setAttribute("version", API_VERSION_STR); + responseNode.setAttribute("version", std::string {QUOTEME(API_VERSION_MAJOR) "."} + std::to_string(getAPIMinorVersion(clientName)) + ".0"); Node& errorNode {responseNode.createChild("error")}; errorNode.setAttribute("code", std::to_string(static_cast(error.getCode()))); @@ -160,11 +176,19 @@ Response::writeXML(std::ostream& os) boost::property_tree::ptree res; for (auto itAttribute : node._attributes) - res.put("." + itAttribute.first, itAttribute.second); - - if (!node._value.empty()) { - res.put_value(node._value); + if (std::holds_alternative(itAttribute.second)) + res.put("." + itAttribute.first, std::get(itAttribute.second)); + else if (std::holds_alternative(itAttribute.second)) + res.put("." + itAttribute.first, std::get(itAttribute.second)); + } + + if (node._value.valueless_by_exception()) + { + if (std::holds_alternative(node._value)) + res.put_value(std::get(node._value)); + else if (std::holds_alternative(node._value)) + res.put_value(std::get(node._value)); } else { @@ -190,6 +214,16 @@ Response::writeXML(std::ostream& os) boost::property_tree::write_xml(os, root); } +unsigned +Response::getAPIMinorVersion(std::string_view clientName) +{ + // Audinaut does not lower its client API version in plain text authentication mode + if (clientName == "Audinaut") + return 13; + else + return 12; +} + void Response::writeJSON(std::ostream& os) { @@ -200,11 +234,19 @@ Response::writeJSON(std::ostream& os) Json::Object res; for (auto itAttribute : node._attributes) - res[itAttribute.first] = Json::Value {itAttribute.second}; - - if (!node._value.empty()) { - res["value"] = Json::Value {node._value}; + if (std::holds_alternative(itAttribute.second)) + res[itAttribute.first] = Json::Value {std::get(itAttribute.second)}; + else if (std::holds_alternative(itAttribute.second)) + res[itAttribute.first] = Json::Value {std::get(itAttribute.second)}; + } + + if (node._value.valueless_by_exception()) + { + if (std::holds_alternative(node._value)) + res["value"] = Json::Value {std::get(node._value)}; + else if (std::holds_alternative(node._value)) + res["value"] = Json::Value {std::get(node._value)}; } else { diff --git a/src/libs/subsonic/impl/SubsonicResponse.hpp b/src/libs/subsonic/impl/SubsonicResponse.hpp index a88217ad..811d22c9 100644 --- a/src/libs/subsonic/impl/SubsonicResponse.hpp +++ b/src/libs/subsonic/impl/SubsonicResponse.hpp @@ -21,17 +21,16 @@ #include #include #include +#include #include +#include "RequestContext.hpp" + +#define API_VERSION_MAJOR 1 namespace API::Subsonic { -#define API_VERSION_MAJOR 1 -#define API_VERSION_MINOR 12 -#define API_VERSION_PATCH 0 -#define API_VERSION_STR "1.12.0" - enum class ResponseFormat { xml, @@ -181,9 +180,11 @@ class Response { public: void setAttribute(std::string_view key, std::string_view value); + void setAttribute(std::string_view key, long long value); // A Node has either a value or some children void setValue(std::string_view value); + void setValue(long long value); Node& createChild(const std::string& key); Node& createArrayChild(const std::string& key); @@ -192,14 +193,14 @@ class Response private: friend class Response; - std::map _attributes; - std::string _value; + std::map> _attributes; + std::variant _value; std::map> _children; std::map> _childrenArrays; }; - static Response createOkResponse(); - static Response createFailedResponse(const Error& error); + static Response createOkResponse(const RequestContext& context); + static Response createFailedResponse(std::string_view clientName, const Error& error); virtual ~Response() {} Response(const Response&) = delete; @@ -212,6 +213,8 @@ class Response Node& createArrayNode(const std::string& key); void write(std::ostream& os, ResponseFormat format); + + static unsigned getAPIMinorVersion(std::string_view clientName); private: void writeJSON(std::ostream& os); diff --git a/src/libs/utils/impl/String.cpp b/src/libs/utils/impl/String.cpp index dbcb82d2..edef6744 100644 --- a/src/libs/utils/impl/String.cpp +++ b/src/libs/utils/impl/String.cpp @@ -104,11 +104,17 @@ stringToLower(std::string_view str) std::string res; res.reserve(str.size()); - std::transform(std::cbegin(str), std::cend(str), std::back_inserter(res), [](char c) { return std::tolower(c);}); + std::transform(std::cbegin(str), std::cend(str), std::back_inserter(res), [](unsigned char c) { return std::tolower(c);}); return res; } +void +stringToLower(std::string& str) +{ + std::transform(std::cbegin(str), std::cend(str), std::begin(str), [](unsigned char c) { return std::tolower(c);}); +} + std::string stringToUpper(const std::string& str) { diff --git a/src/libs/utils/include/utils/String.hpp b/src/libs/utils/include/utils/String.hpp index 62d6fba4..d4655931 100644 --- a/src/libs/utils/include/utils/String.hpp +++ b/src/libs/utils/include/utils/String.hpp @@ -25,8 +25,10 @@ #include #include -namespace StringUtils { +#define QUOTEME(x) QUOTEME_1(x) +#define QUOTEME_1(x) #x +namespace StringUtils { std::vector splitString(const std::string& string, const std::string& separators); @@ -43,6 +45,9 @@ stringTrimEnd(const std::string& str, const std::string& whitespaces = " \t"); std::string stringToLower(std::string_view str); +void +stringToLower(std::string& str); + std::string stringToUpper(const std::string& str); diff --git a/src/lms/ui/Auth.cpp b/src/lms/ui/Auth.cpp index d450b0c7..cae9ee16 100644 --- a/src/lms/ui/Auth.cpp +++ b/src/lms/ui/Auth.cpp @@ -181,12 +181,15 @@ Auth::Auth() }; // LoginName - setFormWidget(AuthModel::LoginNameField, std::make_unique()); + auto loginName {std::make_unique()}; + loginName->setAttributeValue("autocomplete", "username"); + setFormWidget(AuthModel::LoginNameField, std::move(loginName)); // Password auto password = std::make_unique(); password->setEchoMode(Wt::EchoMode::Password); password->enterPressed().connect(this, processAuth); + password->setAttributeValue("autocomplete", "current-password"); setFormWidget(AuthModel::PasswordField, std::move(password)); // Remember me diff --git a/src/lms/ui/LmsApplication.cpp b/src/lms/ui/LmsApplication.cpp index 89cebb24..86fc7a15 100644 --- a/src/lms/ui/LmsApplication.cpp +++ b/src/lms/ui/LmsApplication.cpp @@ -523,6 +523,16 @@ LmsApplication::createHome() // Events from MediaScanner { const std::string sessionId {LmsApp->sessionId()}; + + ServiceProvider::get()->scanStarted().connect(this, [=] () + { + Wt::WServer::instance()->post(sessionId, [=] + { + _events.dbScanStarted.emit(); + triggerUpdate(); + }); + }); + ServiceProvider::get()->scanComplete().connect(this, [=] () { Wt::WServer::instance()->post(sessionId, [=] diff --git a/src/lms/ui/LmsApplication.hpp b/src/lms/ui/LmsApplication.hpp index 20cac9b7..2b3b4534 100644 --- a/src/lms/ui/LmsApplication.hpp +++ b/src/lms/ui/LmsApplication.hpp @@ -55,6 +55,7 @@ struct Events Wt::Signal appClosed; // Database events + Wt::Signal<> dbScanStarted; Wt::Signal<> dbScanned; Wt::Signal dbScanInProgress; Wt::Signal dbScanScheduled; diff --git a/src/lms/ui/LmsTheme.cpp b/src/lms/ui/LmsTheme.cpp index 6c6c97a2..d56cbe5a 100644 --- a/src/lms/ui/LmsTheme.cpp +++ b/src/lms/ui/LmsTheme.cpp @@ -66,6 +66,7 @@ LmsTheme::getStyleSheets(Database::User::UITheme theme) case Database::User::UITheme::Dark: return { + {"css/fonts.css"}, {"css/bootstrap-darkly.min.css"}, {"resources/themes/bootstrap/3/wt.css"}, {"css/lms.css"}, @@ -75,6 +76,7 @@ LmsTheme::getStyleSheets(Database::User::UITheme theme) case Database::User::UITheme::Light: return { + {"css/fonts.css"}, {"css/bootstrap-flatly.min.css"}, {"resources/themes/bootstrap/3/wt.css"}, {"css/lms.css"}, diff --git a/src/lms/ui/SettingsView.cpp b/src/lms/ui/SettingsView.cpp index 30d8a401..33cfd766 100644 --- a/src/lms/ui/SettingsView.cpp +++ b/src/lms/ui/SettingsView.cpp @@ -387,17 +387,20 @@ SettingsView::refreshView() auto oldPassword {std::make_unique()}; oldPassword->setEchoMode(Wt::EchoMode::Password); + oldPassword->setAttributeValue("autocomplete", "current-password"); t->setFormWidget(SettingsModel::PasswordOldField, std::move(oldPassword)); } // Password auto password {std::make_unique()}; password->setEchoMode(Wt::EchoMode::Password); + password->setAttributeValue("autocomplete", "new-password"); t->setFormWidget(SettingsModel::PasswordField, std::move(password)); // Password confirm auto passwordConfirm {std::make_unique()}; passwordConfirm->setEchoMode(Wt::EchoMode::Password); + passwordConfirm->setAttributeValue("autocomplete", "new-password"); t->setFormWidget(SettingsModel::PasswordConfirmField, std::move(passwordConfirm)); // Audio diff --git a/src/lms/ui/admin/DatabaseSettingsView.cpp b/src/lms/ui/admin/DatabaseSettingsView.cpp index 323dfa7c..5b612ff6 100644 --- a/src/lms/ui/admin/DatabaseSettingsView.cpp +++ b/src/lms/ui/admin/DatabaseSettingsView.cpp @@ -248,7 +248,6 @@ DatabaseSettingsView::refreshView() immScanBtn->clicked().connect([=] () { ServiceProvider::get()->requestImmediateScan(); - LmsApp->notifyMsg(MsgType::Info, Wt::WString::tr("Lms.Admin.Database.scan-launched")); }); t->updateView(model.get()); diff --git a/src/lms/ui/admin/DatabaseStatus.cpp b/src/lms/ui/admin/DatabaseStatus.cpp index 34133e01..1030c452 100644 --- a/src/lms/ui/admin/DatabaseStatus.cpp +++ b/src/lms/ui/admin/DatabaseStatus.cpp @@ -121,6 +121,10 @@ DatabaseStatus::DatabaseStatus() auto onDbEvent = [&]() { refreshContents(); }; + LmsApp->getEvents().dbScanStarted.connect(this, []() + { + LmsApp->notifyMsg(MsgType::Info, Wt::WString::tr("Lms.Admin.Database.scan-launched")); + }); LmsApp->getEvents().dbScanned.connect(this, onDbEvent); LmsApp->getEvents().dbScanInProgress.connect(this, onDbEvent); LmsApp->getEvents().dbScanScheduled.connect(this, onDbEvent); diff --git a/src/lms/ui/admin/InitWizardView.cpp b/src/lms/ui/admin/InitWizardView.cpp index 34d7c5fb..e62820b0 100644 --- a/src/lms/ui/admin/InitWizardView.cpp +++ b/src/lms/ui/admin/InitWizardView.cpp @@ -113,17 +113,27 @@ InitWizardView::InitWizardView() auto model = std::make_shared(); // AdminLogin - setFormWidget(InitWizardModel::AdminLoginField, std::make_unique()); + { + auto adminLogin {std::make_unique()}; + adminLogin->setAttributeValue("autocomplete", "username"); + setFormWidget(InitWizardModel::AdminLoginField, std::move(adminLogin)); + } // Password - auto passwordEdit = std::make_unique(); - passwordEdit->setEchoMode(Wt::EchoMode::Password); - setFormWidget(InitWizardModel::PasswordField, std::move(passwordEdit) ); + { + auto passwordEdit = std::make_unique(); + passwordEdit->setEchoMode(Wt::EchoMode::Password); + passwordEdit->setAttributeValue("autocomplete", "current-password"); + setFormWidget(InitWizardModel::PasswordField, std::move(passwordEdit) ); + } // Password confirmation - auto passwordConfirmEdit = std::make_unique(); - passwordConfirmEdit->setEchoMode(Wt::EchoMode::Password); - setFormWidget(InitWizardModel::PasswordConfirmField, std::move(passwordConfirmEdit)); + { + auto passwordConfirmEdit = std::make_unique(); + passwordConfirmEdit->setEchoMode(Wt::EchoMode::Password); + passwordConfirmEdit->setAttributeValue("autocomplete", "current-password"); + setFormWidget(InitWizardModel::PasswordConfirmField, std::move(passwordConfirmEdit)); + } Wt::WPushButton* saveButton = bindNew("create-btn", Wt::WString::tr("Lms.create")); saveButton->clicked().connect([=] diff --git a/src/lms/ui/admin/UserView.cpp b/src/lms/ui/admin/UserView.cpp index 3bb52e6d..53c27e82 100644 --- a/src/lms/ui/admin/UserView.cpp +++ b/src/lms/ui/admin/UserView.cpp @@ -227,6 +227,7 @@ UserView::refreshView() // Password auto passwordEdit = std::make_unique(); passwordEdit->setEchoMode(Wt::EchoMode::Password); + passwordEdit->setAttributeValue("autocomplete", "off"); t->setFormWidget(UserModel::PasswordField, std::move(passwordEdit)); // Demo account diff --git a/src/test/database/DatabaseTest.cpp b/src/test/database/DatabaseTest.cpp index b23a19a1..c5edcc1f 100644 --- a/src/test/database/DatabaseTest.cpp +++ b/src/test/database/DatabaseTest.cpp @@ -811,7 +811,13 @@ testMultipleTracksSingleClusterSimilarity(Session& session) const auto similarTracks {Track::getSimilarTracks(session, {tracks.front().getId()})}; CHECK(similarTracks.size() == tracks.size() - 1); for (auto similarTrack : similarTracks) - CHECK(std::find_if(std::next(std::cbegin(tracks), 1), std::cend(tracks), [&](const ScopedTrack& track) { return similarTrack.id() == track.getId(); }) != std::cend(tracks)); + { + CHECK(std::find_if(std::next(std::cbegin(tracks), 1), std::cend(tracks), + [&](const ScopedTrack& track) + { + return similarTrack.id() == track.getId(); + }) != std::cend(tracks)); + } } }