commit 555ca0bba9f59176f0dc065bcc95e54471204b42 Author: Storm Dragon Date: Mon Dec 15 04:09:55 2025 -0500 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..56c1f22 --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +__pycache__/ +*.py[cod] +*.log + +# Virtual environments +.venv/ +venv/ +env/ +.env +.env.* + +# Build and packaging +build/ +dist/ +*.egg-info/ +.eggs/ +pip-wheel-metadata/ + +# Tooling caches +.pytest_cache/ +.mypy_cache/ +.coverage + +# IDE/editor settings +.vscode/ +.idea/ + +# Local AI/config helpers +/.claude diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..cba6e27 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,34 @@ +# Repository Guidelines + +## Project Structure & Module Organization +- `navipy.py` boots the PySide6 desktop client, wires logging, and discovers modules under `src/`. +- `src/api/` holds the Subsonic client, auth helpers, and data models that talk to your Navidrome server. +- `src/accessibility/` and `src/widgets/` contain custom Qt widgets and dialogs with accessibility metadata; `src/main_window.py` composes them. +- `src/config/settings.py` manages XDG-compliant config/data/cache dirs and persists `settings.json` and `servers.json`. +- `sounds/` ships UI audio assets; runtime logs land in `~/.local/share/navipy/navipy.log`. + +## Build, Test, and Development Commands +- `python3 -m venv .venv && source .venv/bin/activate` — set up an isolated environment. +- `pip install -r requirements.txt` — install PySide6 and other runtime deps. +- `python3 navipy.py` — launch the app with logging to the data dir; exit cleanly with Ctrl+C. +- `pytest` — placeholder for future tests; add a `tests/` folder with `test_*.py` as you grow coverage. + +## Coding Style & Naming Conventions +- Follow PEP 8: 4-space indentation, snake_case modules/functions, and descriptive class names for Qt widgets/actions. +- Keep accessibility in mind: set `setAccessibleName` on interactive widgets, and keep shortcuts consistent with existing ones in `MainWindow`. +- Prefer type hints for public APIs in `api/` and configuration helpers; keep JSON keys predictable and lowercase. + +## Testing Guidelines +- No automated suite exists yet; add `pytest` cases for API client authentication, settings persistence (XDG paths), and any audio/control logic. +- Name files `tests/test_.py`; use fixtures to stub Navidrome endpoints instead of hitting real servers. +- Manual checks still matter: verify keyboard-only navigation, high-DPI rendering, and that logs/config are written under the XDG directories. + +## Commit & Pull Request Guidelines +- Write imperative, scoped commit subjects (e.g., "Add server dialog validation"), keep to ~72 chars, and describe user-facing impact in the body when needed. +- PRs should list the change summary, test results or manual checks, linked issues, and UI screenshots/GIFs for visible tweaks. +- Call out accessibility-affecting changes, config migrations, or new dependencies so reviewers can double-check regressions. + +## Security & Configuration Tips +- Never log server credentials; `servers.json` under `~/.config/navipy/` stores secrets—treat it as sensitive and avoid committing it. +- Respect `XDG_*` overrides in tests and scripts to avoid polluting real user data; prefer temporary dirs when experimenting. +- Keep error messages informative but redacted; sanitize Navidrome responses before logging. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..15db5aa --- /dev/null +++ b/README.md @@ -0,0 +1,57 @@ +# NaviPy + +Accessible Navidrome desktop client built with PySide6. Keyboard-first controls, live region announcements, and XDG-compliant configuration keep the app friendly for screen readers and shared systems. + +## Features +- Browse artists, albums, playlists, and genres from your Navidrome server +- Keyboard-driven playback controls with live announcements +- Queue management (play now, next/previous, clear/remove) +- Track-change announcements (toggle in View → Announce Track Changes) +- Desktop integrations via MPRIS (playback control, metadata, notifications) +- Config, data, and cache saved under XDG paths (`~/.config/stormux/navipy`, etc.) +- Does not log credentials; server secrets live in `servers.json` + +## Requirements +- Python 3.9+ (PySide6) +- Qt multimedia runtime for audio playback (e.g., `qt6-multimedia` package when using system Qt) +- Navidrome server credentials + +## Setup +```bash +python3 -m venv .venv +source .venv/bin/activate +pip install -r requirements.txt +``` + +## Run +```bash +python3 navipy.py +``` +Logs are written to `~/.local/share/stormux/navipy/navipy.log`. + +## Configuration and Data Paths +- Config: `~/.config/stormux/navipy/settings.json` and `servers.json` + Honors `$XDG_CONFIG_HOME`. Reads legacy `~/.config/navipy` if present. +- Data (logs, runtime files): `~/.local/share/stormux/navipy/` (`$XDG_DATA_HOME` respected) +- Cache: `~/.cache/stormux/navipy/` (`$XDG_CACHE_HOME` respected) + +## Keyboard Shortcuts +- Playback: `Space` play/pause, `X` play/resume, `C` toggle pause, `V` stop +- Navigation: `Z` previous, `B` next, `Ctrl+Left/Right` previous/next, `Alt+S` shuffle, `Alt+R` repeat +- Announcements: `Alt+C` announce current track (live region), `Ctrl+T` announce track (dialog), `Ctrl+P` announce position +- Volume: `Ctrl+Up/Down` or `0/9` to adjust +- Library/Search: `Ctrl+O` connect, `F5` refresh, `Ctrl+F` search + +## Playback Persistence +- Volume, shuffle, and repeat preferences persist in `settings.json` +- Repeat defaults to off; shuffle retains your last choice across launches + +## Accessibility Notes +- Live region announcements for status updates and explicit announce commands +- Accessible names/descriptions on interactive widgets +- Keyboard-only navigation throughout the UI + +## Development Tips +- Keep secrets out of logs; `servers.json` stores credentials and is not tracked +- Respect XDG env vars in scripts/tests to avoid polluting real user data +- Placeholder tests can be added under `tests/` with `pytest` diff --git a/navipy.py b/navipy.py new file mode 100755 index 0000000..67c3711 --- /dev/null +++ b/navipy.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +""" +NaviPy - Accessible Navidrome Client + +An accessible music player for Navidrome servers, built with PySide6 +for full keyboard navigation and screen reader compatibility. +""" + +import sys +import signal +import logging +from pathlib import Path + +from PySide6.QtWidgets import QApplication +from PySide6.QtCore import Qt + +# Add src to path for imports +srcPath = Path(__file__).parent / 'src' +sys.path.insert(0, str(srcPath.parent)) + +from src.main_window import MainWindow +from src.config.settings import getDataDir + + +def setupLogging(): + """Setup logging configuration""" + logDir = getDataDir() + logFile = logDir / 'navipy.log' + + logging.basicConfig( + level=logging.INFO, + format='%(message)s [%(asctime)s]', + datefmt='%a %b %d %I:%M:%S %p %Z %Y', + handlers=[ + logging.FileHandler(logFile, encoding='utf-8'), + logging.StreamHandler(sys.stdout) + ] + ) + + return logging.getLogger('navipy') + + +def signalHandler(sig, frame): + """Handle interrupt signals for clean shutdown""" + logging.info("Received shutdown signal") + QApplication.quit() + + +def main(): + """Main entry point""" + logger = setupLogging() + logger.info("NaviPy starting") + + # Setup signal handlers for clean shutdown + signal.signal(signal.SIGINT, signalHandler) + signal.signal(signal.SIGTERM, signalHandler) + + # Create application + app = QApplication(sys.argv) + app.setApplicationName("NaviPy") + app.setApplicationVersion("0.1.0") + app.setOrganizationName("NaviPy") + + # Enable accessibility + app.setAttribute(Qt.AA_UseHighDpiPixmaps) + + # Create and show main window + window = MainWindow() + window.show() + + logger.info("NaviPy started successfully") + + # Run the application + exitCode = app.exec() + + logger.info("NaviPy shutting down") + sys.exit(exitCode) + + +if __name__ == "__main__": + main() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..72aa3a4 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +PySide6>=6.0.0 +requests>=2.25.0 +dbus-python; sys_platform == "linux" +PyGObject; sys_platform == "linux" diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000..bb50242 --- /dev/null +++ b/src/__init__.py @@ -0,0 +1 @@ +"""NaviPy - Accessible Navidrome Client""" diff --git a/src/accessibility/__init__.py b/src/accessibility/__init__.py new file mode 100644 index 0000000..90b4ead --- /dev/null +++ b/src/accessibility/__init__.py @@ -0,0 +1 @@ +"""Accessibility widgets module""" diff --git a/src/accessibility/accessible_combo.py b/src/accessibility/accessible_combo.py new file mode 100644 index 0000000..5af4ed9 --- /dev/null +++ b/src/accessibility/accessible_combo.py @@ -0,0 +1,76 @@ +""" +Accessible combo box with enhanced keyboard navigation +Based on the implementation from Bifrost/Doom Launcher +""" + +from PySide6.QtWidgets import QComboBox +from PySide6.QtCore import Qt +from PySide6.QtGui import QKeyEvent + + +class AccessibleComboBox(QComboBox): + """ComboBox with enhanced keyboard navigation for accessibility""" + + def __init__(self, parent=None): + super().__init__(parent) + self.setEditable(True) + self.lineEdit().setReadOnly(True) + self.pageStep = 5 # Number of items to jump for page up/down + + def keyPressEvent(self, event: QKeyEvent): + """Handle keyboard navigation with accessibility enhancements""" + currentIndex = self.currentIndex() + itemCount = self.count() + + if event.key() == Qt.Key_PageUp: + # Jump up by pageStep items + newIndex = max(0, currentIndex - self.pageStep) + self.setCurrentIndex(newIndex) + + elif event.key() == Qt.Key_PageDown: + # Jump down by pageStep items + newIndex = min(itemCount - 1, currentIndex + self.pageStep) + self.setCurrentIndex(newIndex) + + elif event.key() == Qt.Key_Home: + # Go to first item + self.setCurrentIndex(0) + # Force update and focus events + self.setFocus() + self.currentIndexChanged.emit(0) + self.activated.emit(0) + + elif event.key() == Qt.Key_End: + # Go to last item + lastIndex = itemCount - 1 + self.setCurrentIndex(lastIndex) + # Force update and focus events + self.setFocus() + self.currentIndexChanged.emit(lastIndex) + self.activated.emit(lastIndex) + + else: + # Use default behavior for other keys + super().keyPressEvent(event) + + def wheelEvent(self, event): + """Handle mouse wheel events with moderation""" + # Only change selection if the widget has focus + if self.hasFocus(): + super().wheelEvent(event) + else: + # Ignore wheel events when not focused to prevent accidental changes + event.ignore() + + def setAccessibleName(self, name: str): + """Set accessible name and ensure it's properly applied""" + super().setAccessibleName(name) + # Also set it on the line edit for better screen reader support + if self.lineEdit(): + self.lineEdit().setAccessibleName(name) + + def setAccessibleDescription(self, description: str): + """Set accessible description""" + super().setAccessibleDescription(description) + if self.lineEdit(): + self.lineEdit().setAccessibleDescription(description) diff --git a/src/accessibility/accessible_tree.py b/src/accessibility/accessible_tree.py new file mode 100644 index 0000000..7c1618d --- /dev/null +++ b/src/accessibility/accessible_tree.py @@ -0,0 +1,340 @@ +""" +Accessible tree widget for hierarchical navigation +Based on the implementation from Bifrost +""" + +import re +from PySide6.QtWidgets import QTreeWidget, QTreeWidgetItem +from PySide6.QtCore import Qt, Signal +from PySide6.QtGui import QKeyEvent + + +class AccessibleTreeWidget(QTreeWidget): + """Tree widget with enhanced accessibility for hierarchical content""" + + itemStateChanged = Signal(QTreeWidgetItem, str) # item, state_description + + def __init__(self, parent=None): + super().__init__(parent) + self.pageStep = 5 # Number of items to jump for page up/down + self.setupAccessibility() + + def setupAccessibility(self): + """Set up accessibility features""" + self.setFocusPolicy(Qt.StrongFocus) + self.itemExpanded.connect(self.onItemExpanded) + self.itemCollapsed.connect(self.onItemCollapsed) + + def keyPressEvent(self, event: QKeyEvent): + """Handle keyboard navigation with accessibility enhancements""" + key = event.key() + current = self.currentItem() + + # Handle context menu key (Menu key or Shift+F10) + if key == Qt.Key_Menu or (key == Qt.Key_F10 and event.modifiers() & Qt.ShiftModifier): + if current: + # Get the position of the current item + rect = self.visualItemRect(current) + center = rect.center() + # Emit context menu signal + self.customContextMenuRequested.emit(center) + return + + if not current: + super().keyPressEvent(event) + return + + # Handle Enter key for item activation + if key == Qt.Key_Return or key == Qt.Key_Enter: + self.itemActivated.emit(current, 0) + return + + # Handle copy to clipboard shortcut + if key == Qt.Key_C and event.modifiers() & Qt.ControlModifier: + if hasattr(self.parent(), 'copyToClipboard'): + self.parent().copyToClipboard() + return + + # Check for Shift modifier + hasShift = event.modifiers() & Qt.ShiftModifier + + if key == Qt.Key_Right: + # Right Arrow: Expand node or move to first child + if current.childCount() > 0: + if not current.isExpanded(): + self.expandItem(current) + self.updateChildAccessibility(current, True) + return + # If already expanded and no shift, move to first child + elif not hasShift: + firstChild = current.child(0) + if firstChild and self.isItemNavigable(firstChild): + self.setCurrentItem(firstChild) + self.scrollToItem(firstChild) + return + + elif key == Qt.Key_Left: + if hasShift: + # Shift+Left: Navigate to root parent + rootParent = self.getRootParent(current) + if rootParent and rootParent != current: + self.setCurrentItem(rootParent) + self.scrollToItem(rootParent) + return + else: + # Plain Left: Collapse current item if expanded, otherwise move to parent + if current.childCount() > 0 and current.isExpanded(): + self.collapseItem(current) + self.updateChildAccessibility(current, False) + self.repaint() + self.update() + return + elif current.parent(): + parentItem = current.parent() + self.setCurrentItem(parentItem) + self.scrollToItem(parentItem) + return + + elif key == Qt.Key_Down: + # Move to next visible item + nextItem = self.getNextVisibleItem(current) + if nextItem: + self.setCurrentItem(nextItem) + self.scrollToItem(nextItem) + return + + elif key == Qt.Key_Up: + # Move to previous visible item + prevItem = self.getPreviousVisibleItem(current) + if prevItem: + self.setCurrentItem(prevItem) + self.scrollToItem(prevItem) + return + + elif key == Qt.Key_PageDown: + # Jump down by pageStep items + target = current + for _ in range(self.pageStep): + nextItem = self.getNextVisibleItem(target) + if nextItem: + target = nextItem + else: + break + self.setCurrentItem(target) + self.scrollToItem(target) + return + + elif key == Qt.Key_PageUp: + # Jump up by pageStep items + target = current + for _ in range(self.pageStep): + prevItem = self.getPreviousVisibleItem(target) + if prevItem: + target = prevItem + else: + break + self.setCurrentItem(target) + self.scrollToItem(target) + return + + elif key == Qt.Key_Home: + # Go to first item + firstItem = self.topLevelItem(0) + if firstItem: + self.setCurrentItem(firstItem) + self.scrollToItem(firstItem) + return + + elif key == Qt.Key_End: + # Go to last visible item + lastItem = self.getLastVisibleItem() + if lastItem: + self.setCurrentItem(lastItem) + self.scrollToItem(lastItem) + return + + # Only fall back to default behavior if we didn't handle the key + if key not in [Qt.Key_Left, Qt.Key_Right, Qt.Key_Up, Qt.Key_Down, + Qt.Key_PageUp, Qt.Key_PageDown, Qt.Key_Home, Qt.Key_End]: + super().keyPressEvent(event) + + def getNextVisibleItem(self, item: QTreeWidgetItem) -> QTreeWidgetItem: + """Get the next visible item in the tree""" + if not item: + return None + + # If item has children, check if first child is navigable + if item.childCount() > 0: + firstChild = item.child(0) + if firstChild and self.isItemNavigable(firstChild): + return firstChild + + # Otherwise, find next sibling or ancestor's sibling + current = item + while current: + parent = current.parent() + if parent: + # Find next sibling + index = parent.indexOfChild(current) + if index + 1 < parent.childCount(): + nextSibling = parent.child(index + 1) + if nextSibling and self.isItemNavigable(nextSibling): + return nextSibling + # No more siblings, go up to parent + current = parent + else: + # Top-level item, find next top-level item + index = self.indexOfTopLevelItem(current) + if index + 1 < self.topLevelItemCount(): + nextItem = self.topLevelItem(index + 1) + if nextItem and self.isItemNavigable(nextItem): + return nextItem + # No more items + return None + return None + + def getPreviousVisibleItem(self, item: QTreeWidgetItem) -> QTreeWidgetItem: + """Get the previous visible item in the tree""" + if not item: + return None + + parent = item.parent() + + if parent: + # Find previous sibling + index = parent.indexOfChild(item) + if index > 0: + # Get previous sibling and its last visible descendant + prevSibling = parent.child(index - 1) + if prevSibling and self.isItemNavigable(prevSibling): + return self.getLastVisibleDescendant(prevSibling) + else: + # No previous sibling, go to parent + if self.isItemNavigable(parent): + return parent + else: + # Top-level item + index = self.indexOfTopLevelItem(item) + if index > 0: + # Get previous top-level item and its last visible descendant + prevItem = self.topLevelItem(index - 1) + if prevItem and self.isItemNavigable(prevItem): + return self.getLastVisibleDescendant(prevItem) + return None + + def getLastVisibleDescendant(self, item: QTreeWidgetItem) -> QTreeWidgetItem: + """Get the last visible descendant of an item""" + if not item or not self.isItemNavigable(item): + return None + + # Check if any children are navigable + if item.childCount() > 0: + # Get the last child and check if it's navigable + lastChild = item.child(item.childCount() - 1) + if lastChild and self.isItemNavigable(lastChild): + result = self.getLastVisibleDescendant(lastChild) + return result if result else item + return item + + def getLastVisibleItem(self) -> QTreeWidgetItem: + """Get the last visible item in the tree""" + if self.topLevelItemCount() == 0: + return None + lastTopLevel = self.topLevelItem(self.topLevelItemCount() - 1) + return self.getLastVisibleDescendant(lastTopLevel) + + def onItemExpanded(self, item: QTreeWidgetItem): + """Handle item expansion""" + self.announceItemState(item, "expanded") + # Make child items accessible + self.updateChildAccessibility(item, True) + + def onItemCollapsed(self, item: QTreeWidgetItem): + """Handle item collapse""" + self.announceItemState(item, "collapsed") + # Hide child items from screen readers + self.updateChildAccessibility(item, False) + + def updateChildAccessibility(self, item: QTreeWidgetItem, visible: bool): + """Update accessibility properties of child items""" + for i in range(item.childCount()): + child = item.child(i) + if visible: + # Make child accessible and ensure proper selection + child.setFlags(child.flags() | Qt.ItemIsEnabled | Qt.ItemIsSelectable) + child.setData(0, Qt.AccessibleDescriptionRole, "") # Clear hidden marker + # Recursively handle nested children + self.updateChildAccessibility(child, child.isExpanded()) + else: + # Hide from screen readers and navigation + child.setData(0, Qt.AccessibleDescriptionRole, "hidden") + # Remove selectable flag - collapsed items should not be navigable + child.setFlags((child.flags() | Qt.ItemIsEnabled) & ~Qt.ItemIsSelectable) + # Hide all nested children too + self.updateChildAccessibility(child, False) + + def announceItemState(self, item: QTreeWidgetItem, state: str): + """Announce item state change for screen readers""" + # Update accessible text to include state + if item.childCount() > 0: + originalText = item.text(0) + childCount = item.childCount() + + # Remove any existing state information to prevent duplication + cleanText = re.sub(r' \(\d+ items?, (?:collapsed|expanded)\)$', '', originalText) + + accessibleText = f"{cleanText} ({childCount} items, {state})" + item.setData(0, Qt.AccessibleTextRole, accessibleText) + + # Emit signal for potential sound feedback + self.itemStateChanged.emit(item, state) + + def getItemDescription(self, item: QTreeWidgetItem) -> str: + """Get a full description of an item for screen readers""" + if not item: + return "No item selected" + + text = item.text(0) + + # Determine item type and context + if item.parent() is None: + # Top-level item + if item.childCount() > 0: + state = "expanded" if item.isExpanded() else "collapsed" + return f"{text} ({item.childCount()} items, {state})" + else: + return text + else: + # Child item + depth = self.getItemDepth(item) + if depth == 1: + return f"Item: {text}" + else: + return f"Level {depth}: {text}" + + def getItemDepth(self, item: QTreeWidgetItem) -> int: + """Get the nesting depth of an item""" + depth = 0 + current = item + while current.parent(): + depth += 1 + current = current.parent() + return depth + + def getRootParent(self, item: QTreeWidgetItem) -> QTreeWidgetItem: + """Get the root parent (top-level item) of any item""" + current = item + while current.parent(): + current = current.parent() + return current + + def isItemNavigable(self, item: QTreeWidgetItem) -> bool: + """Check if an item is safe to navigate to""" + if not item: + return False + # Check if item is enabled and selectable, and not hidden + flags = item.flags() + isHidden = item.data(0, Qt.AccessibleDescriptionRole) == "hidden" + isEnabled = bool(flags & Qt.ItemIsEnabled) + isSelectable = bool(flags & Qt.ItemIsSelectable) + return isEnabled and isSelectable and not isHidden diff --git a/src/api/__init__.py b/src/api/__init__.py new file mode 100644 index 0000000..4fca35a --- /dev/null +++ b/src/api/__init__.py @@ -0,0 +1 @@ +"""Subsonic API client module""" diff --git a/src/api/auth.py b/src/api/auth.py new file mode 100644 index 0000000..9fb60fc --- /dev/null +++ b/src/api/auth.py @@ -0,0 +1,23 @@ +""" +Subsonic API authentication utilities +""" + +import hashlib +import random +import string + + +class SubsonicAuth: + """Subsonic authentication handler using token + salt method""" + + @staticmethod + def generateSalt(length: int = 16) -> str: + """Generate random salt string""" + chars = string.ascii_letters + string.digits + return ''.join(random.choice(chars) for _ in range(length)) + + @staticmethod + def generateToken(password: str, salt: str) -> str: + """Generate MD5 token from password and salt""" + toHash = password + salt + return hashlib.md5(toHash.encode('utf-8')).hexdigest() diff --git a/src/api/client.py b/src/api/client.py new file mode 100644 index 0000000..b45e6e5 --- /dev/null +++ b/src/api/client.py @@ -0,0 +1,562 @@ +""" +Subsonic API client for Navidrome communication +""" + +from typing import Optional, List, Dict, Any +from urllib.parse import urlencode +import requests + +from .auth import SubsonicAuth +from .models import Artist, Album, Song, Playlist, Genre + + +class SubsonicError(Exception): + """Subsonic API error""" + + ERROR_CODES = { + 0: "Generic error", + 10: "Required parameter missing", + 20: "Incompatible client version", + 30: "Incompatible server version", + 40: "Wrong username or password", + 41: "Token authentication not supported", + 50: "User not authorized", + 60: "Trial expired", + 70: "Data not found" + } + + def __init__(self, code: int, message: str): + self.code = code + self.message = message + super().__init__(f"[{code}] {message}") + + +class SubsonicClient: + """Subsonic API client for Navidrome communication""" + + API_VERSION = '1.16.1' + CLIENT_NAME = 'NaviPy' + + def __init__(self, serverUrl: str, username: str, password: str): + """ + Initialize the Subsonic client + + Args: + serverUrl: Base URL of the Navidrome server (e.g., https://music.example.com) + username: Navidrome username + password: Navidrome password + """ + self.serverUrl = serverUrl.rstrip('/') + self.username = username + self.password = password + self.session = requests.Session() + self.session.headers.update({ + 'User-Agent': f'{self.CLIENT_NAME}/1.0' + }) + + def _makeRequest(self, endpoint: str, params: dict = None) -> dict: + """ + Make authenticated API request + + Args: + endpoint: API endpoint (e.g., 'ping', 'getArtists') + params: Additional parameters for the request + + Returns: + dict: Parsed API response + + Raises: + SubsonicError: If the API returns an error + requests.RequestException: If the network request fails + """ + salt = SubsonicAuth.generateSalt() + token = SubsonicAuth.generateToken(self.password, salt) + + baseParams = { + 'u': self.username, + 't': token, + 's': salt, + 'v': self.API_VERSION, + 'c': self.CLIENT_NAME, + 'f': 'json' + } + + if params: + baseParams.update(params) + + url = f"{self.serverUrl}/rest/{endpoint}" + response = self.session.get(url, params=baseParams, timeout=30) + response.raise_for_status() + + data = response.json() + + # Subsonic wraps responses in 'subsonic-response' + subsonicResponse = data.get('subsonic-response', {}) + + if subsonicResponse.get('status') == 'failed': + error = subsonicResponse.get('error', {}) + raise SubsonicError( + code=error.get('code', 0), + message=error.get('message', 'Unknown error') + ) + + return subsonicResponse + + def ping(self) -> bool: + """ + Test connection to the server + + Returns: + bool: True if connection successful + """ + response = self._makeRequest('ping') + return response.get('status') == 'ok' + + def getStreamUrl(self, songId: str, format: str = None, maxBitRate: int = None) -> str: + """ + Generate streaming URL for a song + + Args: + songId: ID of the song to stream + format: Optional transcoding format (mp3, opus, etc.) + maxBitRate: Optional max bitrate for transcoding + + Returns: + str: Full streaming URL with authentication + """ + salt = SubsonicAuth.generateSalt() + token = SubsonicAuth.generateToken(self.password, salt) + + params = { + 'u': self.username, + 't': token, + 's': salt, + 'v': self.API_VERSION, + 'c': self.CLIENT_NAME, + 'id': songId + } + + if format: + params['format'] = format + if maxBitRate: + params['maxBitRate'] = maxBitRate + + return f"{self.serverUrl}/rest/stream?{urlencode(params)}" + + def getCoverArtUrl(self, coverId: str, size: int = None) -> str: + """ + Generate cover art URL + + Args: + coverId: Cover art ID + size: Optional size in pixels + + Returns: + str: Full cover art URL with authentication + """ + salt = SubsonicAuth.generateSalt() + token = SubsonicAuth.generateToken(self.password, salt) + + params = { + 'u': self.username, + 't': token, + 's': salt, + 'v': self.API_VERSION, + 'c': self.CLIENT_NAME, + 'id': coverId + } + + if size: + params['size'] = size + + return f"{self.serverUrl}/rest/getCoverArt?{urlencode(params)}" + + # ==================== Browsing ==================== + + def getArtists(self, musicFolderId: str = None) -> List[Artist]: + """ + Get all artists + + Args: + musicFolderId: Optional music folder to filter by + + Returns: + List of Artist objects + """ + params = {} + if musicFolderId: + params['musicFolderId'] = musicFolderId + + response = self._makeRequest('getArtists', params) + artists = [] + + artistsData = response.get('artists', {}) + for index in artistsData.get('index', []): + for artistData in index.get('artist', []): + artists.append(Artist.fromDict(artistData)) + + return artists + + def getArtist(self, artistId: str) -> Dict[str, Any]: + """ + Get artist details including albums + + Args: + artistId: ID of the artist + + Returns: + dict with 'artist' (Artist) and 'albums' (List[Album]) + """ + response = self._makeRequest('getArtist', {'id': artistId}) + artistData = response.get('artist', {}) + + artist = Artist.fromDict(artistData) + albums = [Album.fromDict(a) for a in artistData.get('album', [])] + + return {'artist': artist, 'albums': albums} + + def getAlbum(self, albumId: str) -> Dict[str, Any]: + """ + Get album details including songs + + Args: + albumId: ID of the album + + Returns: + dict with 'album' (Album) and 'songs' (List[Song]) + """ + response = self._makeRequest('getAlbum', {'id': albumId}) + albumData = response.get('album', {}) + + album = Album.fromDict(albumData) + songs = [Song.fromDict(s) for s in albumData.get('song', [])] + + return {'album': album, 'songs': songs} + + def getSong(self, songId: str) -> Song: + """ + Get song details + + Args: + songId: ID of the song + + Returns: + Song object + """ + response = self._makeRequest('getSong', {'id': songId}) + return Song.fromDict(response.get('song', {})) + + def getGenres(self) -> List[Genre]: + """ + Get all genres + + Returns: + List of Genre objects + """ + response = self._makeRequest('getGenres') + genresData = response.get('genres', {}) + return [Genre.fromDict(g) for g in genresData.get('genre', [])] + + def getSongsByGenre(self, genre: str, count: int = 100, offset: int = 0) -> List[Song]: + """ + Get songs by genre + + Args: + genre: Genre name + count: Maximum number of songs to return + offset: Pagination offset + + Returns: + List of Song objects + """ + params = { + 'genre': genre, + 'count': count, + 'offset': offset + } + response = self._makeRequest('getSongsByGenre', params) + songsData = response.get('songsByGenre', {}) + return [Song.fromDict(s) for s in songsData.get('song', [])] + + def getRandomSongs(self, size: int = 10, genre: str = None, + fromYear: int = None, toYear: int = None) -> List[Song]: + """ + Get random songs + + Args: + size: Number of songs to return + genre: Optional genre filter + fromYear: Optional start year filter + toYear: Optional end year filter + + Returns: + List of Song objects + """ + params = {'size': size} + if genre: + params['genre'] = genre + if fromYear: + params['fromYear'] = fromYear + if toYear: + params['toYear'] = toYear + + response = self._makeRequest('getRandomSongs', params) + songsData = response.get('randomSongs', {}) + return [Song.fromDict(s) for s in songsData.get('song', [])] + + # ==================== Search ==================== + + def search(self, query: str, artistCount: int = 20, + albumCount: int = 20, songCount: int = 20) -> Dict[str, List]: + """ + Search for artists, albums, and songs + + Args: + query: Search query + artistCount: Max artists to return + albumCount: Max albums to return + songCount: Max songs to return + + Returns: + dict with 'artists', 'albums', 'songs' lists + """ + params = { + 'query': query, + 'artistCount': artistCount, + 'albumCount': albumCount, + 'songCount': songCount + } + response = self._makeRequest('search3', params) + searchResult = response.get('searchResult3', {}) + + return { + 'artists': [Artist.fromDict(a) for a in searchResult.get('artist', [])], + 'albums': [Album.fromDict(a) for a in searchResult.get('album', [])], + 'songs': [Song.fromDict(s) for s in searchResult.get('song', [])] + } + + # ==================== Playlists ==================== + + def getPlaylists(self) -> List[Playlist]: + """ + Get all playlists + + Returns: + List of Playlist objects + """ + response = self._makeRequest('getPlaylists') + playlistsData = response.get('playlists', {}) + return [Playlist.fromDict(p) for p in playlistsData.get('playlist', [])] + + def getPlaylist(self, playlistId: str) -> Playlist: + """ + Get playlist details including songs + + Args: + playlistId: ID of the playlist + + Returns: + Playlist object with songs populated + """ + response = self._makeRequest('getPlaylist', {'id': playlistId}) + return Playlist.fromDict(response.get('playlist', {})) + + def createPlaylist(self, name: str, songIds: List[str] = None) -> Playlist: + """ + Create a new playlist + + Args: + name: Playlist name + songIds: Optional list of song IDs to add + + Returns: + Created Playlist object + """ + params = {'name': name} + if songIds: + params['songId'] = songIds + + response = self._makeRequest('createPlaylist', params) + return Playlist.fromDict(response.get('playlist', {})) + + def updatePlaylist(self, playlistId: str, name: str = None, + songIdsToAdd: List[str] = None, + songIndexesToRemove: List[int] = None) -> None: + """ + Update a playlist + + Args: + playlistId: ID of the playlist + name: New name (optional) + songIdsToAdd: Song IDs to add (optional) + songIndexesToRemove: Song indexes to remove (optional) + """ + params = {'playlistId': playlistId} + if name: + params['name'] = name + if songIdsToAdd: + params['songIdToAdd'] = songIdsToAdd + if songIndexesToRemove: + params['songIndexToRemove'] = songIndexesToRemove + + self._makeRequest('updatePlaylist', params) + + def deletePlaylist(self, playlistId: str) -> None: + """ + Delete a playlist + + Args: + playlistId: ID of the playlist to delete + """ + self._makeRequest('deletePlaylist', {'id': playlistId}) + + # ==================== User Actions ==================== + + def star(self, itemId: str, itemType: str = 'song') -> None: + """ + Star (favorite) an item + + Args: + itemId: ID of the item + itemType: Type of item ('song', 'album', 'artist') + """ + paramName = { + 'song': 'id', + 'album': 'albumId', + 'artist': 'artistId' + }.get(itemType, 'id') + + self._makeRequest('star', {paramName: itemId}) + + def unstar(self, itemId: str, itemType: str = 'song') -> None: + """ + Unstar (unfavorite) an item + + Args: + itemId: ID of the item + itemType: Type of item ('song', 'album', 'artist') + """ + paramName = { + 'song': 'id', + 'album': 'albumId', + 'artist': 'artistId' + }.get(itemType, 'id') + + self._makeRequest('unstar', {paramName: itemId}) + + def setRating(self, itemId: str, rating: int) -> None: + """ + Set rating for an item (1-5 stars, 0 to remove) + + Args: + itemId: ID of the item + rating: Rating value (0-5) + """ + self._makeRequest('setRating', {'id': itemId, 'rating': rating}) + + def scrobble(self, songId: str, submission: bool = True) -> None: + """ + Scrobble a song (register as played) + + Args: + songId: ID of the song + submission: True for full scrobble, False for "now playing" + """ + self._makeRequest('scrobble', {'id': songId, 'submission': submission}) + + # ==================== Play Queue ==================== + + def getPlayQueue(self) -> Dict[str, Any]: + """ + Get the saved play queue + + Returns: + dict with 'songs' (List[Song]), 'current' (str), 'position' (int) + """ + response = self._makeRequest('getPlayQueue') + queueData = response.get('playQueue', {}) + + return { + 'songs': [Song.fromDict(s) for s in queueData.get('entry', [])], + 'current': queueData.get('current'), + 'position': queueData.get('position', 0) + } + + def savePlayQueue(self, songIds: List[str], current: str = None, + position: int = None) -> None: + """ + Save the current play queue + + Args: + songIds: List of song IDs in the queue + current: ID of currently playing song + position: Position in current song (milliseconds) + """ + params = {'id': songIds} + if current: + params['current'] = current + if position is not None: + params['position'] = position + + self._makeRequest('savePlayQueue', params) + + # ==================== Starred/Favorites ==================== + + def getStarred(self) -> Dict[str, List]: + """ + Get all starred items + + Returns: + dict with 'artists', 'albums', 'songs' lists + """ + response = self._makeRequest('getStarred2') + starredData = response.get('starred2', {}) + + return { + 'artists': [Artist.fromDict(a) for a in starredData.get('artist', [])], + 'albums': [Album.fromDict(a) for a in starredData.get('album', [])], + 'songs': [Song.fromDict(s) for s in starredData.get('song', [])] + } + + # ==================== Lyrics ==================== + + def getLyrics(self, artist: str = None, title: str = None) -> Optional[str]: + """ + Get lyrics for a song + + Args: + artist: Artist name + title: Song title + + Returns: + Lyrics text or None if not found + """ + params = {} + if artist: + params['artist'] = artist + if title: + params['title'] = title + + response = self._makeRequest('getLyrics', params) + lyricsData = response.get('lyrics', {}) + return lyricsData.get('value') + + # ==================== System ==================== + + def startScan(self) -> None: + """Start a library scan""" + self._makeRequest('startScan') + + def getScanStatus(self) -> Dict[str, Any]: + """ + Get library scan status + + Returns: + dict with 'scanning' (bool) and 'count' (int) + """ + response = self._makeRequest('getScanStatus') + scanData = response.get('scanStatus', {}) + return { + 'scanning': scanData.get('scanning', False), + 'count': scanData.get('count', 0) + } diff --git a/src/api/models.py b/src/api/models.py new file mode 100644 index 0000000..da91223 --- /dev/null +++ b/src/api/models.py @@ -0,0 +1,214 @@ +""" +Data models for Subsonic API responses +""" + +from dataclasses import dataclass, field +from datetime import datetime +from typing import Optional, List + + +@dataclass +class Artist: + """Artist model""" + id: str + name: str + albumCount: int = 0 + starred: Optional[datetime] = None + coverArt: Optional[str] = None + artistImageUrl: Optional[str] = None + + @classmethod + def fromDict(cls, data: dict) -> 'Artist': + """Create Artist from API response dict""" + starred = None + if data.get('starred'): + try: + starred = datetime.fromisoformat(data['starred'].replace('Z', '+00:00')) + except (ValueError, TypeError): + pass + + return cls( + id=str(data.get('id', '')), + name=data.get('name', 'Unknown Artist'), + albumCount=data.get('albumCount', 0), + starred=starred, + coverArt=data.get('coverArt'), + artistImageUrl=data.get('artistImageUrl') + ) + + +@dataclass +class Album: + """Album model""" + id: str + name: str + artist: str + artistId: Optional[str] = None + songCount: int = 0 + duration: int = 0 + year: Optional[int] = None + genre: Optional[str] = None + coverArt: Optional[str] = None + starred: Optional[datetime] = None + playCount: int = 0 + userRating: int = 0 + + @classmethod + def fromDict(cls, data: dict) -> 'Album': + """Create Album from API response dict""" + starred = None + if data.get('starred'): + try: + starred = datetime.fromisoformat(data['starred'].replace('Z', '+00:00')) + except (ValueError, TypeError): + pass + + return cls( + id=str(data.get('id', '')), + name=data.get('name', data.get('album', 'Unknown Album')), + artist=data.get('artist', 'Unknown Artist'), + artistId=data.get('artistId'), + songCount=data.get('songCount', 0), + duration=data.get('duration', 0), + year=data.get('year'), + genre=data.get('genre'), + coverArt=data.get('coverArt'), + starred=starred, + playCount=data.get('playCount', 0), + userRating=data.get('userRating', 0) + ) + + +@dataclass +class Song: + """Song/Track model""" + id: str + title: str + album: str + albumId: str + artist: str + artistId: Optional[str] = None + duration: int = 0 + track: Optional[int] = None + discNumber: Optional[int] = None + year: Optional[int] = None + genre: Optional[str] = None + bitRate: Optional[int] = None + contentType: Optional[str] = None + suffix: Optional[str] = None + path: Optional[str] = None + coverArt: Optional[str] = None + starred: Optional[datetime] = None + userRating: int = 0 + playCount: int = 0 + bookmarkPosition: Optional[int] = None + + @classmethod + def fromDict(cls, data: dict) -> 'Song': + """Create Song from API response dict""" + starred = None + if data.get('starred'): + try: + starred = datetime.fromisoformat(data['starred'].replace('Z', '+00:00')) + except (ValueError, TypeError): + pass + + return cls( + id=str(data.get('id', '')), + title=data.get('title', 'Unknown Title'), + album=data.get('album', 'Unknown Album'), + albumId=str(data.get('albumId', '')), + artist=data.get('artist', 'Unknown Artist'), + artistId=data.get('artistId'), + duration=data.get('duration', 0), + track=data.get('track'), + discNumber=data.get('discNumber'), + year=data.get('year'), + genre=data.get('genre'), + bitRate=data.get('bitRate'), + contentType=data.get('contentType'), + suffix=data.get('suffix'), + path=data.get('path'), + coverArt=data.get('coverArt'), + starred=starred, + userRating=data.get('userRating', 0), + playCount=data.get('playCount', 0), + bookmarkPosition=data.get('bookmarkPosition') + ) + + @property + def durationFormatted(self) -> str: + """Return duration as formatted string (MM:SS or HH:MM:SS)""" + if self.duration <= 0: + return "0:00" + hours = self.duration // 3600 + minutes = (self.duration % 3600) // 60 + seconds = self.duration % 60 + if hours > 0: + return f"{hours}:{minutes:02d}:{seconds:02d}" + return f"{minutes}:{seconds:02d}" + + +@dataclass +class Playlist: + """Playlist model""" + id: str + name: str + songCount: int = 0 + duration: int = 0 + public: bool = False + owner: Optional[str] = None + created: Optional[datetime] = None + changed: Optional[datetime] = None + coverArt: Optional[str] = None + songs: List[Song] = field(default_factory=list) + + @classmethod + def fromDict(cls, data: dict) -> 'Playlist': + """Create Playlist from API response dict""" + created = None + changed = None + if data.get('created'): + try: + created = datetime.fromisoformat(data['created'].replace('Z', '+00:00')) + except (ValueError, TypeError): + pass + if data.get('changed'): + try: + changed = datetime.fromisoformat(data['changed'].replace('Z', '+00:00')) + except (ValueError, TypeError): + pass + + songs = [] + if 'entry' in data: + songs = [Song.fromDict(s) for s in data['entry']] + + return cls( + id=str(data.get('id', '')), + name=data.get('name', 'Unnamed Playlist'), + songCount=data.get('songCount', 0), + duration=data.get('duration', 0), + public=data.get('public', False), + owner=data.get('owner'), + created=created, + changed=changed, + coverArt=data.get('coverArt'), + songs=songs + ) + + +@dataclass +class Genre: + """Genre model""" + name: str + songCount: int = 0 + albumCount: int = 0 + + @classmethod + def fromDict(cls, data: dict) -> 'Genre': + """Create Genre from API response dict""" + return cls( + name=data.get('value', data.get('name', 'Unknown Genre')), + songCount=data.get('songCount', 0), + albumCount=data.get('albumCount', 0) + ) diff --git a/src/config/__init__.py b/src/config/__init__.py new file mode 100644 index 0000000..1442896 --- /dev/null +++ b/src/config/__init__.py @@ -0,0 +1 @@ +"""Configuration management module""" diff --git a/src/config/settings.py b/src/config/settings.py new file mode 100644 index 0000000..6ad0540 --- /dev/null +++ b/src/config/settings.py @@ -0,0 +1,168 @@ +""" +Configuration management with XDG compliance +""" + +import os +import json +from pathlib import Path +from typing import Optional, Dict, Any + +APP_VENDOR = "stormux" +APP_NAME = "navipy" + + +def getConfigDir() -> Path: + """Get XDG-compliant config directory""" + xdgConfig = os.environ.get('XDG_CONFIG_HOME') + baseDir = Path(xdgConfig) if xdgConfig else Path.home() / '.config' + configDir = baseDir / APP_VENDOR / APP_NAME + + configDir.mkdir(parents=True, exist_ok=True) + return configDir + + +def getDataDir() -> Path: + """Get XDG-compliant data directory""" + xdgData = os.environ.get('XDG_DATA_HOME') + baseDir = Path(xdgData) if xdgData else Path.home() / '.local' / 'share' + dataDir = baseDir / APP_VENDOR / APP_NAME + + dataDir.mkdir(parents=True, exist_ok=True) + return dataDir + + +def getCacheDir() -> Path: + """Get XDG-compliant cache directory""" + xdgCache = os.environ.get('XDG_CACHE_HOME') + baseDir = Path(xdgCache) if xdgCache else Path.home() / '.cache' + cacheDir = baseDir / APP_VENDOR / APP_NAME + + cacheDir.mkdir(parents=True, exist_ok=True) + return cacheDir + + +class Settings: + """Application settings manager""" + + def __init__(self): + self.configDir = getConfigDir() + self.configFile = self.configDir / 'settings.json' + self.serversFile = self.configDir / 'servers.json' + self._legacyConfigDir = self._getLegacyConfigDir() + self._settings = self._loadSettings() + self._servers = self._loadServers() + + def _getLegacyConfigDir(self) -> Path: + """Legacy configuration path kept for backwards compatibility.""" + xdgConfig = os.environ.get('XDG_CONFIG_HOME') + baseDir = Path(xdgConfig) if xdgConfig else Path.home() / '.config' + return baseDir / APP_NAME + + def _loadSettings(self) -> Dict[str, Any]: + """Load settings from file""" + defaults = { + 'general': { + 'defaultServer': None, + 'startMinimized': False + }, + 'playback': { + 'volume': 100, + 'shuffle': False, + 'repeat': 'none', # none, one, all + 'gapless': True + }, + 'interface': { + 'pageStep': 5, + 'announceTrackChanges': True + } + } + + for candidate in (self.configFile, self._legacyConfigDir / 'settings.json'): + if candidate.exists(): + try: + with open(candidate, 'r', encoding='utf-8') as f: + loaded = json.load(f) + # Merge loaded settings with defaults + for section in defaults: + if section in loaded: + defaults[section].update(loaded[section]) + return defaults + except (json.JSONDecodeError, IOError): + continue + + return defaults + + def _loadServers(self) -> Dict[str, Dict[str, str]]: + """Load server configurations from file""" + for candidate in (self.serversFile, self._legacyConfigDir / 'servers.json'): + if candidate.exists(): + try: + with open(candidate, 'r', encoding='utf-8') as f: + return json.load(f) + except (json.JSONDecodeError, IOError): + continue + return {} + + def save(self) -> None: + """Save settings to file""" + try: + with open(self.configFile, 'w', encoding='utf-8') as f: + json.dump(self._settings, f, indent=2) + except IOError as e: + print(f"Failed to save settings: {e}") + + def saveServers(self) -> None: + """Save server configurations to file""" + try: + with open(self.serversFile, 'w', encoding='utf-8') as f: + json.dump(self._servers, f, indent=2) + except IOError as e: + print(f"Failed to save servers: {e}") + + def get(self, section: str, key: str, default: Any = None) -> Any: + """Get a setting value""" + return self._settings.get(section, {}).get(key, default) + + def set(self, section: str, key: str, value: Any) -> None: + """Set a setting value""" + if section not in self._settings: + self._settings[section] = {} + self._settings[section][key] = value + self.save() + + # Server management + + def getServers(self) -> Dict[str, Dict[str, str]]: + """Get all server configurations""" + return self._servers + + def getServer(self, name: str) -> Optional[Dict[str, str]]: + """Get a specific server configuration""" + return self._servers.get(name) + + def addServer(self, name: str, url: str, username: str, password: str) -> None: + """Add or update a server configuration""" + self._servers[name] = { + 'url': url, + 'username': username, + 'password': password + } + self.saveServers() + + def removeServer(self, name: str) -> None: + """Remove a server configuration""" + if name in self._servers: + del self._servers[name] + self.saveServers() + + def getDefaultServer(self) -> Optional[str]: + """Get the default server name""" + return self.get('general', 'defaultServer') + + def setDefaultServer(self, name: str) -> None: + """Set the default server""" + self.set('general', 'defaultServer', name) + + def hasServers(self) -> bool: + """Check if any servers are configured""" + return len(self._servers) > 0 diff --git a/src/integrations/__init__.py b/src/integrations/__init__.py new file mode 100644 index 0000000..8a65dbc --- /dev/null +++ b/src/integrations/__init__.py @@ -0,0 +1 @@ +"""Integration helpers for NaviPy.""" diff --git a/src/integrations/mpris.py b/src/integrations/mpris.py new file mode 100644 index 0000000..c0d98cc --- /dev/null +++ b/src/integrations/mpris.py @@ -0,0 +1,389 @@ +""" +MPRIS v2 integration using dbus-python with a GLib main loop. + +We avoid QtDBus because some environments block Qt's D-Bus socket while the +standard dbus-python bindings work. The service exposes both interfaces on +`/org/mpris/MediaPlayer2` and runs a GLib loop in a background thread. +""" + +from __future__ import annotations + +import logging +import re +import threading +from typing import Callable, Dict, Optional + +try: + import dbus + import dbus.service + from dbus.mainloop.glib import DBusGMainLoop + from gi.repository import GLib + DBUS_AVAILABLE = True +except Exception: # pragma: no cover - optional dependency + DBUS_AVAILABLE = False + dbus = None # type: ignore + DBusGMainLoop = None # type: ignore + GLib = None # type: ignore + +from PySide6.QtCore import QMetaObject, Qt + +logger = logging.getLogger(__name__) + + +def _sanitize_track_id(track_id: str) -> str: + return re.sub(r"[^A-Za-z0-9]", "_", track_id or "track") + + +if DBUS_AVAILABLE: + DBusObjectBase = dbus.service.Object +else: + class DBusObjectBase: # type: ignore + """Placeholder when dbus-python is unavailable.""" + pass + + +class MprisService(DBusObjectBase): + BUS_NAME = "org.mpris.MediaPlayer2.navipy" + OBJECT_PATH = "/org/mpris/MediaPlayer2" + + def __init__( + self, + playback, + art_url_resolver: Optional[Callable[[str], Optional[str]]] = None, + raise_callback: Optional[Callable[[], None]] = None, + quit_callback: Optional[Callable[[], None]] = None, + on_volume_changed: Optional[Callable[[int], None]] = None, + on_shuffle_changed: Optional[Callable[[bool], None]] = None, + on_loop_changed: Optional[Callable[[str], None]] = None, + ): + if not DBUS_AVAILABLE: + self.available = False + logger.warning("MPRIS disabled: dbus-python/GLib bindings not available.") + return + + self.playback = playback + self.art_url_resolver = art_url_resolver + self.raise_callback = raise_callback + self.quit_callback = quit_callback + self.on_volume_changed = on_volume_changed + self.on_shuffle_changed = on_shuffle_changed + self.on_loop_changed = on_loop_changed + + self._metadata: Dict[str, object] = {} + self._playbackState: str = "stopped" + self._currentTrackPath: dbus.ObjectPath = dbus.ObjectPath("/org/mpris/MediaPlayer2/TrackList/NoTrack") + + self.available = False + self._loop = None + self._loop_thread: Optional[threading.Thread] = None + + bus = self._connect_to_bus() + if not bus: + return + + self.bus = bus + super().__init__(bus, self.OBJECT_PATH) + self.available = True + logger.info("MPRIS registered as %s", self.BUS_NAME) + + self._start_loop() + self.updateMetadata(self.playback.currentSong()) + self.updatePlaybackStatus(self._playbackState) + self.notifyCapabilities() + self.notifyVolumeChanged() + self.notifyShuffleChanged() + self.notifyLoopStatus() + + # ===== DBus setup ===== + + def _connect_to_bus(self) -> Optional[dbus.SessionBus]: + """Connect to the session bus, logging a warning on failure.""" + try: + DBusGMainLoop(set_as_default=True) + bus = dbus.SessionBus() + bus.request_name(self.BUS_NAME, dbus.bus.NAME_FLAG_DO_NOT_QUEUE) + return bus + except Exception as e: + logger.warning("MPRIS disabled: %s", e) + return None + + def _start_loop(self): + """Run a GLib main loop in a background thread for DBus dispatch.""" + self._loop = GLib.MainLoop() + self._loop_thread = threading.Thread(target=self._loop.run, daemon=True) + self._loop_thread.start() + + def shutdown(self): + """Stop the DBus loop.""" + if self._loop: + self._loop.quit() + if self._loop_thread and self._loop_thread.is_alive(): + self._loop_thread.join(timeout=1) + + # ===== Helpers ===== + + def _call_on_main(self, func: Callable, *args): + """Invoke playback operations on the Qt main thread.""" + try: + QMetaObject.invokeMethod(self.playback, lambda: func(*args), Qt.QueuedConnection) + except Exception: + try: + func(*args) + except Exception as e: + logger.debug("MPRIS call failed: %s", e) + + def _build_metadata(self, song) -> Dict[str, object]: + if not song: + self._currentTrackPath = dbus.ObjectPath("/org/mpris/MediaPlayer2/TrackList/NoTrack") + return dbus.Dictionary( + {"mpris:trackid": self._currentTrackPath}, + signature="sv", + ) + + track_path = dbus.ObjectPath(f"/org/navipy/track/{_sanitize_track_id(song.id)}") + duration_us = int(song.duration * 1_000_000) + metadata: Dict[str, object] = { + "mpris:trackid": track_path, + "mpris:length": dbus.Int64(duration_us), + "xesam:title": dbus.String(song.title or "Unknown Title"), + "xesam:album": dbus.String(song.album or ""), + "xesam:artist": dbus.Array([song.artist], signature="s") if song.artist else dbus.Array([], signature="s"), + "xesam:genre": dbus.Array([song.genre], signature="s") if song.genre else dbus.Array([], signature="s"), + "xesam:trackNumber": dbus.Int32(song.track or 0), + "xesam:discNumber": dbus.Int32(song.discNumber or 0), + } + + art_url = self._resolve_art_url(song.coverArt) + if art_url: + metadata["mpris:artUrl"] = art_url + + self._currentTrackPath = track_path + return dbus.Dictionary(metadata, signature="sv") + + def _resolve_art_url(self, cover_id: Optional[str]) -> Optional[str]: + if not cover_id or not self.art_url_resolver: + return None + try: + return self.art_url_resolver(cover_id) + except Exception: + return None + + def _emit_properties_changed(self, interface: str, changes: Dict[str, object]): + """Emit PropertiesChanged for the player object.""" + try: + payload = dbus.Dictionary(changes, signature="sv") + invalidated = dbus.Array([], signature="s") + self.PropertiesChanged(interface, payload, invalidated) + except Exception as e: + logger.warning("Failed to emit PropertiesChanged (%s): %s", interface, e) + + # ===== External notifications ===== + + def updateMetadata(self, song) -> None: + if not self.available: + return + self._metadata = self._build_metadata(song) + self._emit_properties_changed("org.mpris.MediaPlayer2.Player", {"Metadata": self._metadata}) + + def updatePlaybackStatus(self, state: str) -> None: + self._playbackState = state + if not self.available: + return + self._emit_properties_changed( + "org.mpris.MediaPlayer2.Player", + {"PlaybackStatus": self._player_props()["PlaybackStatus"]}, + ) + + def notifyCapabilities(self) -> None: + if not self.available: + return + props = self._player_props() + self._emit_properties_changed( + "org.mpris.MediaPlayer2.Player", + { + "CanGoNext": props["CanGoNext"], + "CanGoPrevious": props["CanGoPrevious"], + "CanPlay": props["CanPlay"], + "CanPause": props["CanPause"], + "CanSeek": props["CanSeek"], + "CanControl": True, + }, + ) + + def notifyVolumeChanged(self) -> None: + if self.available: + self._emit_properties_changed("org.mpris.MediaPlayer2.Player", {"Volume": self._player_props()["Volume"]}) + + def notifyShuffleChanged(self) -> None: + if self.available: + self._emit_properties_changed("org.mpris.MediaPlayer2.Player", {"Shuffle": self._player_props()["Shuffle"]}) + + def notifyLoopStatus(self) -> None: + if self.available: + self._emit_properties_changed("org.mpris.MediaPlayer2.Player", {"LoopStatus": self._player_props()["LoopStatus"]}) + + # ===== Root interface properties ===== + + def _root_props(self) -> Dict[str, object]: + return { + "CanQuit": dbus.Boolean(True), + "CanRaise": dbus.Boolean(True), + "HasTrackList": dbus.Boolean(False), + "CanSetFullscreen": dbus.Boolean(False), + "Fullscreen": dbus.Boolean(False), + "DesktopEntry": dbus.String("navipy"), + "Identity": dbus.String("NaviPy"), + "SupportedUriSchemes": dbus.Array(["http", "https"], signature="s"), + "SupportedMimeTypes": dbus.Array( + ["audio/mpeg", "audio/flac", "audio/ogg", "audio/mp4", "audio/aac", "audio/wav"], + signature="s", + ), + } + + # ===== Player interface properties ===== + + def _player_props(self) -> Dict[str, object]: + queue = getattr(self.playback, "queue", []) + mode = getattr(self.playback, "repeatMode", "none") + player = getattr(self.playback, "player", None) + audio_output = getattr(self.playback, "audioOutput", None) + + return { + "PlaybackStatus": dbus.String({"playing": "Playing", "paused": "Paused", "stopped": "Stopped"}.get(self._playbackState, "Stopped")), + "LoopStatus": dbus.String({"one": "Track", "all": "Playlist", "none": "None"}.get(mode, "None")), + "Rate": dbus.Double(1.0), + "Shuffle": dbus.Boolean(bool(getattr(self.playback, "shuffleEnabled", False))), + "Metadata": self._metadata, + "Volume": dbus.Double(float(audio_output.volume()) if audio_output else 0.0), + "Position": dbus.Int64(int(player.position() * 1000) if player else 0), + "MinimumRate": dbus.Double(1.0), + "MaximumRate": dbus.Double(1.0), + "CanGoNext": dbus.Boolean(len(queue) > 1 or (len(queue) == 1 and mode != "none")), + "CanGoPrevious": dbus.Boolean(len(queue) > 0), + "CanPlay": dbus.Boolean(bool(queue)), + "CanPause": dbus.Boolean(bool(queue)), + "CanControl": dbus.Boolean(True), + "CanSeek": dbus.Boolean(bool(queue)), + "CanGoForward": dbus.Boolean(False), + "CanGoBackward": dbus.Boolean(False), + } + + # ===== org.freedesktop.DBus.Properties ===== + + @dbus.service.method(dbus_interface="org.freedesktop.DBus.Properties", in_signature="ss", out_signature="v") + def Get(self, interface: str, prop: str): + if interface == "org.mpris.MediaPlayer2": + return self._root_props().get(prop) + if interface == "org.mpris.MediaPlayer2.Player": + return self._player_props().get(prop) + raise dbus.exceptions.DBusException("org.freedesktop.DBus.Error.InvalidArgs", f"Unknown interface {interface}") + + @dbus.service.method(dbus_interface="org.freedesktop.DBus.Properties", in_signature="s", out_signature="a{sv}") + def GetAll(self, interface: str): + if interface == "org.mpris.MediaPlayer2": + return self._root_props() + if interface == "org.mpris.MediaPlayer2.Player": + return self._player_props() + raise dbus.exceptions.DBusException("org.freedesktop.DBus.Error.InvalidArgs", f"Unknown interface {interface}") + + @dbus.service.method(dbus_interface="org.freedesktop.DBus.Properties", in_signature="ssv") + def Set(self, interface: str, prop: str, value): + if interface != "org.mpris.MediaPlayer2.Player": + raise dbus.exceptions.DBusException("org.freedesktop.DBus.Error.InvalidArgs", "Properties on this interface are read-only") + + if prop == "LoopStatus": + loop_status = str(value) + mode = {"Track": "one", "Playlist": "all", "None": "none"}.get(loop_status, "none") + if self.on_loop_changed: + self.on_loop_changed(loop_status) + else: + self._call_on_main(self.playback.setRepeatMode, mode) + self.notifyLoopStatus() + elif prop == "Shuffle": + enabled = bool(value) + if self.on_shuffle_changed: + self.on_shuffle_changed(enabled) + else: + self._call_on_main(self.playback.setShuffle, enabled) + self.notifyShuffleChanged() + elif prop == "Volume": + percent = int(max(0.0, min(1.0, float(value))) * 100) + if self.on_volume_changed: + self.on_volume_changed(percent) + else: + self._call_on_main(self.playback.setVolume, percent) + self.notifyVolumeChanged() + else: + raise dbus.exceptions.DBusException("org.freedesktop.DBus.Error.InvalidArgs", f"Property {prop} is not writable") + + # ===== Signals ===== + + @dbus.service.signal(dbus_interface="org.freedesktop.DBus.Properties", signature="sa{sv}as") + def PropertiesChanged(self, interface_name, changed_properties, invalidated_properties): + pass + + @dbus.service.signal(dbus_interface="org.mpris.MediaPlayer2.Player", signature="x") + def Seeked(self, position): + pass + + # ===== Root interface methods ===== + + @dbus.service.method(dbus_interface="org.mpris.MediaPlayer2") + def Raise(self): + if self.raise_callback: + self.raise_callback() + + @dbus.service.method(dbus_interface="org.mpris.MediaPlayer2") + def Quit(self): + if self.quit_callback: + self.quit_callback() + + # ===== Player methods ===== + + @dbus.service.method(dbus_interface="org.mpris.MediaPlayer2.Player") + def Next(self): + self._call_on_main(self.playback.next) + + @dbus.service.method(dbus_interface="org.mpris.MediaPlayer2.Player") + def Previous(self): + self._call_on_main(self.playback.previous) + + @dbus.service.method(dbus_interface="org.mpris.MediaPlayer2.Player") + def Pause(self): + player = getattr(self.playback, "player", None) + if player: + self._call_on_main(player.pause) + + @dbus.service.method(dbus_interface="org.mpris.MediaPlayer2.Player") + def PlayPause(self): + self._call_on_main(self.playback.togglePlayPause) + + @dbus.service.method(dbus_interface="org.mpris.MediaPlayer2.Player") + def Stop(self): + self._call_on_main(self.playback.stop) + + @dbus.service.method(dbus_interface="org.mpris.MediaPlayer2.Player") + def Play(self): + self._call_on_main(self.playback.play) + + @dbus.service.method(dbus_interface="org.mpris.MediaPlayer2.Player", in_signature="x") + def Seek(self, offset: int): + player = getattr(self.playback, "player", None) + if not player: + return + current = player.position() * 1000 # to microseconds + target = max(0, current + offset) + self._call_on_main(self.playback.seek, int(target / 1000)) + self.Seeked(dbus.Int64(target)) + + @dbus.service.method(dbus_interface="org.mpris.MediaPlayer2.Player", in_signature="ox") + def SetPosition(self, track_id: dbus.ObjectPath, position: int): + if track_id != self._currentTrackPath: + return + self._call_on_main(self.playback.seek, int(position / 1000)) + self.Seeked(dbus.Int64(position)) + + @dbus.service.method(dbus_interface="org.mpris.MediaPlayer2.Player", in_signature="s") + def OpenUri(self, uri: str): + # Navidrome streams require authentication; ignore external open requests. + _ = uri diff --git a/src/main_window.py b/src/main_window.py new file mode 100644 index 0000000..3480aca --- /dev/null +++ b/src/main_window.py @@ -0,0 +1,1248 @@ +"""Main application window for NaviPy.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Dict, List, Optional + +from PySide6.QtWidgets import ( + QHBoxLayout, + QLabel, + QListWidget, + QListWidgetItem, + QMainWindow, + QPushButton, + QSlider, + QSplitter, + QStatusBar, + QTreeWidgetItem, + QVBoxLayout, + QWidget, +) +from PySide6.QtCore import Qt +from PySide6.QtGui import ( + QAction, + QAccessible, + QAccessibleEvent, + QAccessibleAnnouncementEvent, + QGuiApplication, + QKeySequence, + QShortcut, +) + +from src.accessibility.accessible_tree import AccessibleTreeWidget +from src.api.client import SubsonicClient, SubsonicError +from src.api.models import Album, Artist, Playlist, Song +from src.config.settings import Settings +from src.managers.playback_manager import PlaybackManager +from src.integrations.mpris import MprisService +from src.widgets.accessible_text_dialog import AccessibleTextDialog +from src.widgets.search_dialog import SearchDialog +from src.widgets.server_dialog import ServerDialog + + +class MainWindow(QMainWindow): + """Main NaviPy application window""" + + def __init__(self): + super().__init__() + self.setWindowTitle("NaviPy - Navidrome Client") + self.setMinimumSize(980, 640) + + self.settings = Settings() + self.client: Optional[SubsonicClient] = None + self.playback = PlaybackManager(self) + self.mpris: Optional[MprisService] = None + + self.pageStep = self.settings.get("interface", "pageStep", 5) + self.volume = self.settings.get("playback", "volume", 100) + self.shuffleEnabled = self.settings.get("playback", "shuffle", False) + self.repeatMode = self.settings.get("playback", "repeat", "none") + self.announceTrackChangesEnabled = self.settings.get("interface", "announceTrackChanges", True) + self._announceOnTrackChange = False + + self.setupMenus() + self.setupUi() + self.connectSignals() + self.applyPersistedPlaybackSettings() + self.enablePlaybackActions(False) + + self.playback.setVolume(self.volume) + self.setupMpris() + + # Connect to server if one is configured + if self.settings.hasServers(): + self.connectToDefaultServer() + else: + self.showServerSetup() + + # ============ UI setup ============ + + def setupMenus(self): + """Setup the menu bar""" + menuBar = self.menuBar() + menuBar.setAccessibleName("Menu Bar") + + # File menu + fileMenu = menuBar.addMenu("&File") + + self.connectAction = QAction("&Connect to Server...", self) + self.connectAction.setShortcut(QKeySequence("Ctrl+O")) + self.connectAction.triggered.connect(self.showServerSetup) + fileMenu.addAction(self.connectAction) + + fileMenu.addSeparator() + + self.refreshAction = QAction("&Refresh Library", self) + self.refreshAction.setShortcut(QKeySequence("F5")) + self.refreshAction.triggered.connect(self.refreshLibrary) + self.refreshAction.setEnabled(False) + fileMenu.addAction(self.refreshAction) + + fileMenu.addSeparator() + + self.quitAction = QAction("&Quit", self) + self.quitAction.setShortcut(QKeySequence("Ctrl+Q")) + self.quitAction.triggered.connect(self.close) + fileMenu.addAction(self.quitAction) + + # Playback menu + playbackMenu = menuBar.addMenu("&Playback") + + self.playPauseAction = QAction("&Play/Pause", self) + self.playPauseAction.setShortcut(QKeySequence("Space")) + self.playPauseAction.setEnabled(False) + playbackMenu.addAction(self.playPauseAction) + + self.stopAction = QAction("&Stop", self) + self.stopAction.setEnabled(False) + playbackMenu.addAction(self.stopAction) + + playbackMenu.addSeparator() + + self.previousAction = QAction("Pre&vious Track", self) + self.previousAction.setShortcut(QKeySequence("Ctrl+Left")) + self.previousAction.setEnabled(False) + playbackMenu.addAction(self.previousAction) + + self.nextAction = QAction("&Next Track", self) + self.nextAction.setShortcut(QKeySequence("Ctrl+Right")) + self.nextAction.setEnabled(False) + playbackMenu.addAction(self.nextAction) + + playbackMenu.addSeparator() + + self.shuffleAction = QAction("&Shuffle", self) + self.shuffleAction.setShortcut(QKeySequence("Alt+S")) + self.shuffleAction.setCheckable(True) + playbackMenu.addAction(self.shuffleAction) + + self.repeatAction = QAction("&Repeat Off", self) + self.repeatAction.setShortcut(QKeySequence("Alt+R")) + self.repeatAction.setCheckable(True) + playbackMenu.addAction(self.repeatAction) + + playbackMenu.addSeparator() + + self.favoriteAction = QAction("&Favorite", self) + self.favoriteAction.setShortcut(QKeySequence("+")) + self.favoriteAction.setEnabled(False) + playbackMenu.addAction(self.favoriteAction) + + self.unfavoriteAction = QAction("Un&favorite", self) + self.unfavoriteAction.setShortcut(QKeySequence("_")) + self.unfavoriteAction.setEnabled(False) + playbackMenu.addAction(self.unfavoriteAction) + + playbackMenu.addSeparator() + + self.volumeUpAction = QAction("Volume &Up", self) + self.volumeUpAction.setShortcut(QKeySequence("Ctrl+Up")) + self.volumeUpAction.setEnabled(False) + playbackMenu.addAction(self.volumeUpAction) + + self.volumeDownAction = QAction("Volume &Down", self) + self.volumeDownAction.setShortcut(QKeySequence("Ctrl+Down")) + self.volumeDownAction.setEnabled(False) + playbackMenu.addAction(self.volumeDownAction) + + # View menu + viewMenu = menuBar.addMenu("&View") + + self.searchAction = QAction("&Search...", self) + self.searchAction.setShortcut(QKeySequence("Ctrl+F")) + self.searchAction.setEnabled(False) + viewMenu.addAction(self.searchAction) + + viewMenu.addSeparator() + + self.announceTrackAction = QAction("Announce Current &Track", self) + self.announceTrackAction.setShortcut(QKeySequence("Ctrl+T")) + self.announceTrackAction.setEnabled(False) + viewMenu.addAction(self.announceTrackAction) + + self.announcePositionAction = QAction("Announce &Position", self) + self.announcePositionAction.setShortcut(QKeySequence("Ctrl+P")) + self.announcePositionAction.setEnabled(False) + viewMenu.addAction(self.announcePositionAction) + + self.announceTrackChangesAction = QAction("Announce Track &Changes", self) + self.announceTrackChangesAction.setCheckable(True) + self.announceTrackChangesAction.setChecked(self.announceTrackChangesEnabled) + viewMenu.addAction(self.announceTrackChangesAction) + + # Help menu + helpMenu = menuBar.addMenu("&Help") + + self.aboutAction = QAction("&About NaviPy", self) + self.aboutAction.triggered.connect(self.showAbout) + helpMenu.addAction(self.aboutAction) + + def setupUi(self): + """Setup the main UI""" + centralWidget = QWidget() + self.setCentralWidget(centralWidget) + mainLayout = QHBoxLayout(centralWidget) + + # Create splitter for resizable panels + self.splitter = QSplitter(Qt.Horizontal) + self.splitter.setAccessibleName("Main Content") + + # Left panel - Library browser + leftPanel = QWidget() + leftLayout = QVBoxLayout(leftPanel) + + libraryLabel = QLabel("Library Browser") + libraryLabel.setAccessibleName("Library Panel") + leftLayout.addWidget(libraryLabel) + + self.libraryStatus = QLabel("Connect to a server to browse your library") + self.libraryStatus.setAccessibleName("Library Status") + leftLayout.addWidget(self.libraryStatus) + + self.libraryTree = AccessibleTreeWidget() + self.libraryTree.setHeaderHidden(True) + self.libraryTree.setAccessibleName("Library Tree") + self.libraryTree.setRootIsDecorated(True) + self.libraryTree.setItemsExpandable(True) + self.libraryTree.pageStep = self.pageStep + self.libraryTree.setEnabled(False) + leftLayout.addWidget(self.libraryTree) + + self.splitter.addWidget(leftPanel) + + # Right panel - Now playing and queue + rightPanel = QWidget() + rightLayout = QVBoxLayout(rightPanel) + + nowPlayingLabel = QLabel("Now Playing") + nowPlayingLabel.setAccessibleName("Now Playing Section") + rightLayout.addWidget(nowPlayingLabel) + + self.nowPlayingInfo = QLabel("No track playing") + self.nowPlayingInfo.setAccessibleName("Current Track") + rightLayout.addWidget(self.nowPlayingInfo) + + self.positionLabel = QLabel("00:00 / 00:00") + self.positionLabel.setAccessibleName("Playback Position") + rightLayout.addWidget(self.positionLabel) + + self.positionSlider = QSlider(Qt.Horizontal) + self.positionSlider.setAccessibleName("Seek Slider") + self.positionSlider.setRange(0, 1000) + self.positionSlider.setEnabled(False) + rightLayout.addWidget(self.positionSlider) + + controlsLayout = QHBoxLayout() + + self.prevButton = QPushButton("Previous") + self.prevButton.setAccessibleName("Previous Track") + self.prevButton.setEnabled(False) + controlsLayout.addWidget(self.prevButton) + + self.playButton = QPushButton("Play/Pause") + self.playButton.setAccessibleName("Play or Pause") + self.playButton.setEnabled(False) + controlsLayout.addWidget(self.playButton) + + self.stopButton = QPushButton("Stop") + self.stopButton.setAccessibleName("Stop Playback") + self.stopButton.setEnabled(False) + controlsLayout.addWidget(self.stopButton) + + self.nextButton = QPushButton("Next") + self.nextButton.setAccessibleName("Next Track") + self.nextButton.setEnabled(False) + controlsLayout.addWidget(self.nextButton) + + rightLayout.addLayout(controlsLayout) + + queueLabel = QLabel("Play Queue") + queueLabel.setAccessibleName("Queue Section") + rightLayout.addWidget(queueLabel) + + self.queueList = QListWidget() + self.queueList.setAccessibleName("Queue List") + self.queueList.setSelectionMode(QListWidget.SingleSelection) + self.queueList.setEnabled(False) + rightLayout.addWidget(self.queueList) + + queueButtons = QHBoxLayout() + + self.removeQueueButton = QPushButton("Remove Selected") + self.removeQueueButton.setAccessibleName("Remove Selected Track from Queue") + self.removeQueueButton.setEnabled(False) + queueButtons.addWidget(self.removeQueueButton) + + self.clearQueueButton = QPushButton("Clear Queue") + self.clearQueueButton.setAccessibleName("Clear Queue") + self.clearQueueButton.setEnabled(False) + queueButtons.addWidget(self.clearQueueButton) + + rightLayout.addLayout(queueButtons) + rightLayout.addStretch() + + self.splitter.addWidget(rightPanel) + + self.splitter.setSizes([560, 420]) + mainLayout.addWidget(self.splitter) + + # Status bar + self.statusBar = QStatusBar() + self.setStatusBar(self.statusBar) + + self.connectionStatus = QLabel("Not connected") + self.connectionStatus.setAccessibleName("Connection Status") + self.statusBar.addPermanentWidget(self.connectionStatus) + + self.playbackStatus = QLabel("Stopped") + self.playbackStatus.setAccessibleName("Playback Status") + self.statusBar.addPermanentWidget(self.playbackStatus) + + self.volumeStatus = QLabel(f"Volume: {self.volume}%") + self.volumeStatus.setAccessibleName("Volume Status") + self.statusBar.addPermanentWidget(self.volumeStatus) + + self.liveRegion = QLabel("") + self.liveRegion.setAccessibleName("Live Region") + self.liveRegion.setAccessibleDescription("Announcements") + self.liveRegion.setStyleSheet("color: transparent;") + self.statusBar.addPermanentWidget(self.liveRegion, 1) + + def connectSignals(self): + """Connect signals after widgets exist.""" + self.libraryTree.itemExpanded.connect(self.onLibraryExpanded) + self.libraryTree.itemActivated.connect(self.onLibraryActivated) + + self.playButton.clicked.connect(self.playPauseAction.trigger) + self.prevButton.clicked.connect(self.previousAction.trigger) + self.nextButton.clicked.connect(self.nextAction.trigger) + self.stopButton.clicked.connect(self.stopAction.trigger) + + self.playPauseAction.triggered.connect(self.playback.togglePlayPause) + self.stopAction.triggered.connect(self.playback.stop) + self.previousAction.triggered.connect(self.handlePreviousShortcut) + self.nextAction.triggered.connect(self.handleNextShortcut) + self.shuffleAction.toggled.connect(self.onShuffleToggled) + self.repeatAction.toggled.connect(self.onRepeatToggled) + self.announceTrackChangesAction.toggled.connect(self.onAnnounceTrackChangesToggled) + self.volumeUpAction.triggered.connect(lambda: self.adjustVolume(5)) + self.volumeDownAction.triggered.connect(lambda: self.adjustVolume(-5)) + self.favoriteAction.triggered.connect(self.favoriteSelection) + self.unfavoriteAction.triggered.connect(self.unfavoriteSelection) + + self.searchAction.triggered.connect(self.openSearchDialog) + + self.positionSlider.sliderMoved.connect(self.onSeekRequested) + + self.queueList.itemActivated.connect(self.onQueueItemActivated) + self.removeQueueButton.clicked.connect(self.removeSelectedFromQueue) + self.clearQueueButton.clicked.connect(self.clearQueue) + + self.announceTrackAction.triggered.connect(self.announceTrack) + self.announcePositionAction.triggered.connect(self.announcePosition) + self.announceTrackLiveShortcut = QShortcut(QKeySequence("Alt+C"), self) + self.announceTrackLiveShortcut.activated.connect(self.announceCurrentTrackLive) + + self.previousShortcut = QShortcut(QKeySequence("Z"), self) + self.previousShortcut.activated.connect(self.handlePreviousShortcut) + + self.playShortcut = QShortcut(QKeySequence("X"), self) + self.playShortcut.activated.connect(self.handlePlayShortcut) + + self.pauseToggleShortcut = QShortcut(QKeySequence("C"), self) + self.pauseToggleShortcut.activated.connect(self.handlePauseToggleShortcut) + + self.stopShortcut = QShortcut(QKeySequence("V"), self) + self.stopShortcut.activated.connect(self.handleStopShortcut) + + self.nextShortcut = QShortcut(QKeySequence("B"), self) + self.nextShortcut.activated.connect(self.handleNextShortcut) + + self.playback.trackChanged.connect(self.onTrackChanged) + self.playback.queueChanged.connect(self.onQueueChanged) + self.playback.playbackStateChanged.connect(self.onPlaybackStateChanged) + self.playback.positionChanged.connect(self.onPositionChanged) + self.playback.errorOccurred.connect(self.onPlaybackError) + + def setupMpris(self): + """Initialize the MPRIS service and wire signal updates.""" + try: + self.mpris = MprisService( + playback=self.playback, + art_url_resolver=self._resolveCoverArtUrl, + raise_callback=self.bringToFront, + quit_callback=self.close, + on_volume_changed=self.setVolumeFromExternal, + on_shuffle_changed=lambda enabled: self.setShuffleFromExternal(enabled, announce=False), + on_loop_changed=lambda loop: self.setRepeatFromExternal(loop, announce=False), + ) + except Exception: + self.mpris = None + return + + if not self.mpris or not self.mpris.available: + self.mpris = None + return + + self.playback.trackChanged.connect(self.mpris.updateMetadata) + self.playback.playbackStateChanged.connect(self.mpris.updatePlaybackStatus) + self.playback.queueChanged.connect(self._handleQueueChangedForMpris) + self.playback.errorOccurred.connect(lambda _message: self.mpris.updatePlaybackStatus("stopped")) + self.mpris.updateMetadata(self.playback.currentSong()) + self.mpris.updatePlaybackStatus("stopped") + self.mpris.notifyCapabilities() + self.mpris.notifyVolumeChanged() + self.mpris.notifyShuffleChanged() + self.mpris.notifyLoopStatus() + + # Additional keyboard shortcuts for quick volume changes + self.volumeUpShortcut = QShortcut(QKeySequence("0"), self) + self.volumeUpShortcut.activated.connect(lambda: self.adjustVolume(5)) + self.volumeDownShortcut = QShortcut(QKeySequence("9"), self) + self.volumeDownShortcut.activated.connect(lambda: self.adjustVolume(-5)) + + # ============ Connection handling ============ + + def showServerSetup(self): + """Show the server setup dialog""" + dialog = ServerDialog(self.settings, parent=self) + if dialog.exec(): + serverName = dialog.getServerName() + self.connectToServer(serverName) + + def connectToDefaultServer(self): + """Connect to the default server""" + defaultServer = self.settings.getDefaultServer() + if defaultServer: + self.connectToServer(defaultServer) + else: + servers = self.settings.getServers() + if servers: + self.connectToServer(list(servers.keys())[0]) + + def connectToServer(self, serverName: str): + """Connect to a specific server""" + server = self.settings.getServer(serverName) + if not server: + AccessibleTextDialog.showError( + "Connection Error", + f"Server '{serverName}' not found in configuration", + parent=self + ) + return + + self.connectionStatus.setText(f"Connecting to {serverName}...") + + try: + self.client = SubsonicClient( + server['url'], + server['username'], + server['password'] + ) + + if self.client.ping(): + self.connectionStatus.setText(f"Connected to {serverName}") + self.playback.setStreamResolver(lambda song: self.client.getStreamUrl(song.id)) + self.onConnected() + else: + self.handleConnectionFailure("Failed to connect to server. Please check your settings.") + except SubsonicError as e: + self.handleConnectionFailure(f"Failed to connect: {e.message}") + except Exception as e: + self.handleConnectionFailure(f"Failed to connect: {str(e)}") + + def handleConnectionFailure(self, message: str): + """Handle errors when connecting to the server.""" + self.connectionStatus.setText("Connection failed") + AccessibleTextDialog.showError("Connection Error", message, parent=self) + + def onConnected(self): + """Called when successfully connected to a server""" + self.refreshAction.setEnabled(True) + self.searchAction.setEnabled(True) + self.libraryTree.setEnabled(True) + self.libraryStatus.setText("Loading library...") + self.refreshLibrary() + + # ============ Library browsing ============ + + def refreshLibrary(self): + """Refresh the library browser""" + if not self.client: + return + + self.libraryTree.clear() + self.libraryStatus.setText("Loading artists, playlists, and genres...") + + # Root sections + self.artistsRoot = QTreeWidgetItem(["Artists"]) + self.artistsRoot.setData(0, Qt.UserRole, {"type": "artists_root", "loaded": True}) + self.artistsRoot.setExpanded(True) + self.libraryTree.addTopLevelItem(self.artistsRoot) + + self.playlistsRoot = QTreeWidgetItem(["Playlists"]) + self.playlistsRoot.setData(0, Qt.UserRole, {"type": "playlists_root", "loaded": True}) + self.playlistsRoot.setExpanded(True) + self.libraryTree.addTopLevelItem(self.playlistsRoot) + + self.genresRoot = QTreeWidgetItem(["Genres"]) + self.genresRoot.setData(0, Qt.UserRole, {"type": "genres_root", "loaded": True}) + self.genresRoot.setExpanded(True) + self.libraryTree.addTopLevelItem(self.genresRoot) + + try: + self.loadArtists() + self.loadPlaylists() + self.loadGenres() + self.libraryStatus.setText("Library ready. Use the tree to browse and press Enter to play.") + except Exception as e: + AccessibleTextDialog.showError( + "Error", + f"Failed to load library: {str(e)}", + parent=self + ) + self.libraryStatus.setText("Library failed to load.") + + def loadArtists(self): + """Populate top-level artists.""" + artists = self.client.getArtists() + for artist in artists: + item = QTreeWidgetItem([artist.name]) + description = f"{artist.albumCount} albums" if artist.albumCount else "Artist" + item.setData(0, Qt.UserRole, {"type": "artist", "id": artist.id, "artist": artist, "loaded": False}) + item.setData(0, Qt.AccessibleTextRole, f"{artist.name}, {description}") + item.addChild(QTreeWidgetItem(["Loading albums..."])) + self.artistsRoot.addChild(item) + + def loadPlaylists(self): + """Populate top-level playlists.""" + playlists = self.client.getPlaylists() + for playlist in playlists: + label = f"{playlist.name} ({playlist.songCount} tracks)" + item = QTreeWidgetItem([label]) + item.setData(0, Qt.UserRole, {"type": "playlist", "id": playlist.id, "playlist": playlist, "loaded": False}) + item.setData(0, Qt.AccessibleTextRole, label) + item.addChild(QTreeWidgetItem(["Loading tracks..."])) + self.playlistsRoot.addChild(item) + + def loadGenres(self): + """Populate top-level genres.""" + genres = self.client.getGenres() + for genre in genres: + label = f"{genre.name} ({genre.songCount} songs)" + item = QTreeWidgetItem([label]) + item.setData(0, Qt.UserRole, {"type": "genre", "name": genre.name, "loaded": False}) + item.setData(0, Qt.AccessibleTextRole, label) + item.addChild(QTreeWidgetItem(["Loading songs..."])) + self.genresRoot.addChild(item) + + def onLibraryExpanded(self, item: QTreeWidgetItem): + """Lazy-load children when an item is expanded.""" + data: Dict = item.data(0, Qt.UserRole) or {} + if data.get("loaded"): + return + + try: + item.takeChildren() + itemType = data.get("type") + if itemType == "artist": + self.populateArtistAlbums(item, data["id"]) + elif itemType == "album": + self.populateAlbumSongs(item, data["id"]) + elif itemType == "playlist": + self.populatePlaylistSongs(item, data["id"]) + elif itemType == "genre": + self.populateGenreSongs(item, data["name"]) + data["loaded"] = True + item.setData(0, Qt.UserRole, data) + except Exception as e: + AccessibleTextDialog.showError( + "Library Error", + f"Could not load content: {str(e)}", + parent=self + ) + + def onLibraryActivated(self, item: QTreeWidgetItem): + """Handle activation (Enter/Return) in the library tree.""" + data: Dict = item.data(0, Qt.UserRole) or {} + itemType = data.get("type") + if itemType == "song": + song: Song = data["song"] + self.playback.enqueue(song, playNow=True) + self.statusBar.showMessage(f"Playing {song.title} by {song.artist}", 4000) + self.enablePlaybackActions(True) + elif itemType == "playlist": + self.playPlaylist(data.get("id"), item) + elif itemType == "album": + self.playAlbum(data.get("id"), item) + elif itemType == "artist": + self.playArtist(data.get("id"), item) + elif itemType == "artists_root": + self.playAllArtists() + elif itemType == "genre": + self.playGenre(data.get("name"), item) + else: + # Toggle expansion for other nodes + item.setExpanded(not item.isExpanded()) + + def populateArtistAlbums(self, parentItem: QTreeWidgetItem, artistId: str): + """Add albums for a given artist.""" + result = self.client.getArtist(artistId) + albums: List[Album] = result.get("albums", []) + for album in albums: + label = f"{album.name} ({album.songCount} tracks)" + albumItem = QTreeWidgetItem([label]) + albumItem.setData(0, Qt.UserRole, {"type": "album", "id": album.id, "album": album, "loaded": False}) + albumItem.setData(0, Qt.AccessibleTextRole, label) + albumItem.addChild(QTreeWidgetItem(["Loading tracks..."])) + parentItem.addChild(albumItem) + + def populateAlbumSongs(self, parentItem: QTreeWidgetItem, albumId: str): + """Add songs for a given album.""" + result = self.client.getAlbum(albumId) + songs: List[Song] = result.get("songs", []) + for song in songs: + label = self.formatSongLabel(song) + songItem = QTreeWidgetItem([label]) + songItem.setData(0, Qt.UserRole, {"type": "song", "song": song}) + songItem.setData(0, Qt.AccessibleTextRole, label) + parentItem.addChild(songItem) + + def populatePlaylistSongs(self, parentItem: QTreeWidgetItem, playlistId: str): + """Add songs for a playlist.""" + playlist: Playlist = self.client.getPlaylist(playlistId) + for song in playlist.songs: + label = self.formatSongLabel(song, includeAlbum=True) + songItem = QTreeWidgetItem([label]) + songItem.setData(0, Qt.UserRole, {"type": "song", "song": song}) + songItem.setData(0, Qt.AccessibleTextRole, label) + parentItem.addChild(songItem) + parentItem.setData(0, Qt.UserRole, {"type": "playlist", "id": playlistId, "playlist": playlist, "loaded": True}) + + def populateGenreSongs(self, parentItem: QTreeWidgetItem, genreName: str): + """Add songs for a genre (limited batch).""" + songs = self.client.getSongsByGenre(genreName, count=200) + for song in songs: + label = self.formatSongLabel(song, includeAlbum=True) + songItem = QTreeWidgetItem([label]) + songItem.setData(0, Qt.UserRole, {"type": "song", "song": song}) + songItem.setData(0, Qt.AccessibleTextRole, label) + parentItem.addChild(songItem) + parentItem.setData(0, Qt.UserRole, {"type": "genre", "name": genreName, "loaded": True}) + + @staticmethod + def formatSongLabel(song: Song, includeAlbum: bool = False) -> str: + """Create a descriptive label for a song.""" + prefix = f"{song.track}. " if song.track else "" + core = f"{prefix}{song.title}" + details = f"{song.artist}" + if includeAlbum: + details = f"{details} — {song.album}" + return f"{core} ({song.durationFormatted}) — {details}" + + def _populateAlbumItemWithSongs(self, parentItem: QTreeWidgetItem, songs: List[Song]): + """Populate an album tree item with song children.""" + parentItem.takeChildren() + for song in songs: + label = self.formatSongLabel(song) + child = QTreeWidgetItem([label]) + child.setData(0, Qt.UserRole, {"type": "song", "song": song}) + child.setData(0, Qt.AccessibleTextRole, label) + parentItem.addChild(child) + data: Dict = parentItem.data(0, Qt.UserRole) or {} + data["loaded"] = True + parentItem.setData(0, Qt.UserRole, data) + + def _populateGenreItemWithSongs(self, parentItem: QTreeWidgetItem, songs: List[Song]): + """Populate a genre item with the provided songs.""" + parentItem.takeChildren() + for song in songs: + label = self.formatSongLabel(song, includeAlbum=True) + child = QTreeWidgetItem([label]) + child.setData(0, Qt.UserRole, {"type": "song", "song": song}) + child.setData(0, Qt.AccessibleTextRole, label) + parentItem.addChild(child) + data: Dict = parentItem.data(0, Qt.UserRole) or {} + data["loaded"] = True + parentItem.setData(0, Qt.UserRole, data) + + # ============ Search ============ + + def openSearchDialog(self): + """Open the search dialog.""" + if not self.client: + return + dialog = SearchDialog(self.client, parent=self) + dialog.songActivated.connect(self.onSearchSongChosen) + dialog.exec() + + def onSearchSongChosen(self, song: Song): + """Handle song selection from search.""" + self.playback.enqueue(song, playNow=True) + self.enablePlaybackActions(True) + self.statusBar.showMessage(f"Playing {song.title} by {song.artist}", 4000) + + # ============ Queue management ============ + + def onQueueChanged(self, queue: List[Song]): + """Refresh the queue list widget.""" + self.queueList.blockSignals(True) + self.queueList.clear() + for index, song in enumerate(queue): + text = f"{index + 1}. {song.artist} — {song.title} ({song.durationFormatted})" + item = QListWidgetItem(text) + item.setData(Qt.UserRole, index) + item.setData(Qt.AccessibleTextRole, text) + self.queueList.addItem(item) + self.queueList.blockSignals(False) + + hasItems = len(queue) > 0 + self.queueList.setEnabled(hasItems) + self.removeQueueButton.setEnabled(hasItems) + self.clearQueueButton.setEnabled(hasItems) + self.enablePlaybackActions(hasItems) + self.announceTrackAction.setEnabled(hasItems) + self.announcePositionAction.setEnabled(hasItems) + + def onQueueItemActivated(self, item: QListWidgetItem): + """Play the selected queue item.""" + index = item.data(Qt.UserRole) + if index is not None: + self.playback.playIndex(int(index)) + + def removeSelectedFromQueue(self): + """Remove the selected item from the queue.""" + row = self.queueList.currentRow() + if row < 0: + return + if 0 <= row < len(self.playback.queue): + del self.playback.queue[row] + if row <= self.playback.currentIndex: + self.playback.currentIndex = max(-1, self.playback.currentIndex - 1) + if not self.playback.queue: + self.playback.stop() + self.playback.queueChanged.emit(self.playback.queue.copy()) + + def clearQueue(self): + """Clear the entire queue.""" + self.playback.clearQueue() + + # ============ Playback updates ============ + + def startPlaybackWithSongs(self, songs: List[Song], label: str): + """Replace queue with provided songs and start playback.""" + if not songs: + AccessibleTextDialog.showWarning("Nothing to Play", f"No songs found for {label}.", parent=self) + return + self.playback.clearQueue() + self.playback.enqueueMany(songs, playFirst=True) + self.statusBar.showMessage(f"Playing {label}", 4000) + self.enablePlaybackActions(True) + + def playAlbum(self, albumId: str, item: Optional[QTreeWidgetItem] = None): + """Play all songs in an album.""" + if not self.client or not albumId: + self.announceLive("No album selected.") + return + try: + albumData = self.client.getAlbum(albumId) + album: Optional[Album] = albumData.get("album") + songs: List[Song] = albumData.get("songs", []) + self.startPlaybackWithSongs(songs, f"album {album.name if album else albumId}") + if item and songs: + self._populateAlbumItemWithSongs(item, songs) + item.setExpanded(True) + except Exception as e: + AccessibleTextDialog.showError("Album Error", str(e), parent=self) + + def playArtist(self, artistId: str, item: Optional[QTreeWidgetItem] = None): + """Play all songs by an artist across their albums.""" + if not self.client or not artistId: + self.announceLive("No artist selected.") + return + try: + artistData = self.client.getArtist(artistId) + artist: Optional[Artist] = artistData.get("artist") + albums: List[Album] = artistData.get("albums", []) + songs: List[Song] = [] + for album in albums: + albumData = self.client.getAlbum(album.id) + songs.extend(albumData.get("songs", [])) + self.startPlaybackWithSongs(songs, artist.name if artist else f"artist {artistId}") + if item: + item.setExpanded(True) + except Exception as e: + AccessibleTextDialog.showError("Artist Error", str(e), parent=self) + + def playAllArtists(self): + """Play all songs across all artists.""" + if not self.client: + self.announceLive("Not connected to a server.") + return + try: + self.announceLive("Loading all artists...") + artists: List[Artist] = self.client.getArtists() + songs: List[Song] = [] + for artist in artists: + artistData = self.client.getArtist(artist.id) + for album in artistData.get("albums", []): + albumData = self.client.getAlbum(album.id) + songs.extend(albumData.get("songs", [])) + self.startPlaybackWithSongs(songs, "all artists") + except Exception as e: + AccessibleTextDialog.showError("Library Error", str(e), parent=self) + + def playGenre(self, genreName: str, item: Optional[QTreeWidgetItem] = None): + """Play all songs within a genre.""" + if not self.client or not genreName: + self.announceLive("No genre selected.") + return + try: + songs = self.client.getSongsByGenre(genreName, count=5000) + self.startPlaybackWithSongs(songs, f"genre {genreName}") + if item and songs: + self._populateGenreItemWithSongs(item, songs) + item.setExpanded(True) + except Exception as e: + AccessibleTextDialog.showError("Genre Error", str(e), parent=self) + + def playPlaylist(self, playlistId: str, item: Optional[QTreeWidgetItem] = None): + """Load a playlist and start playback.""" + try: + playlist: Playlist = self.client.getPlaylist(playlistId) + songs = playlist.songs + if not songs: + AccessibleTextDialog.showWarning("Playlist Empty", "This playlist has no tracks.", parent=self) + return + self.playback.clearQueue() + self.playback.enqueueMany(songs, playFirst=True) + self.statusBar.showMessage(f"Playing playlist {playlist.name}", 4000) + if item: + # Mark as loaded and populate the tree view if needed + item.takeChildren() + for song in songs: + label = self.formatSongLabel(song, includeAlbum=True) + child = QTreeWidgetItem([label]) + child.setData(0, Qt.UserRole, {"type": "song", "song": song}) + child.setData(0, Qt.AccessibleTextRole, label) + item.addChild(child) + item.setData(0, Qt.UserRole, {"type": "playlist", "id": playlistId, "playlist": playlist, "loaded": True}) + self.enablePlaybackActions(True) + except Exception as e: + AccessibleTextDialog.showError("Playlist Error", str(e), parent=self) + + def onTrackChanged(self, song: Song): + """Update UI when track changes.""" + self.nowPlayingInfo.setText(f"{song.title} — {song.artist} ({song.album})") + self.announceTrackAction.setEnabled(True) + self.announcePositionAction.setEnabled(True) + self.positionSlider.setEnabled(True) + self.favoriteAction.setEnabled(True) + self.unfavoriteAction.setEnabled(True) + if self.announceTrackChangesEnabled and self._announceOnTrackChange: + self.announceCurrentTrackLive() + self._announceOnTrackChange = False + + def onPlaybackStateChanged(self, state: str): + """Update playback state labels and actions.""" + self.playbackStatus.setText(state.capitalize()) + if state in ("playing", "paused"): + self.playButton.setText("Pause" if state == "playing" else "Play") + self.playPauseAction.setText("Pause" if state == "playing" else "Play") + else: + self.playButton.setText("Play/Pause") + self.playPauseAction.setText("Play/Pause") + + def onPositionChanged(self, position: int, duration: int): + """Update seek slider and position label.""" + if duration <= 0: + self.positionLabel.setText("00:00 / 00:00") + return + + self.positionLabel.setText(f"{self.formatTime(position)} / {self.formatTime(duration)}") + sliderValue = int((position / duration) * 1000) + self.positionSlider.blockSignals(True) + self.positionSlider.setValue(sliderValue) + self.positionSlider.blockSignals(False) + + def onPlaybackError(self, message: str): + """Show playback errors accessibly.""" + AccessibleTextDialog.showError("Playback Error", message, parent=self) + self.playbackStatus.setText("Error") + + def onRepeatToggled(self, checked: bool): + """Cycle repeat mode.""" + mode = "all" if checked else "none" + self.applyRepeatMode(mode) + + def onShuffleToggled(self, checked: bool): + """Handle shuffle toggle with announcement.""" + self.setShuffleState(checked) + + def onAnnounceTrackChangesToggled(self, checked: bool): + """Persist preference for automatic track change announcements.""" + self.announceTrackChangesEnabled = checked + self.settings.set("interface", "announceTrackChanges", checked) + self.announceLive(f"Announce track changes {'enabled' if checked else 'disabled'}") + + def onSeekRequested(self, value: int): + """Seek within the current track using slider position.""" + duration = self.playback.player.duration() + if duration > 0: + target = int((value / 1000) * duration) + self.playback.seek(target) + + def bringToFront(self): + """Raise the window in response to MPRIS Raise.""" + self.showNormal() + self.raise_() + self.activateWindow() + + def setVolumePercent(self, volumePercent: int, announce: bool = False): + """Set volume from 0-100 and sync UI/settings.""" + volumePercent = max(0, min(100, volumePercent)) + self.volume = volumePercent + self.playback.setVolume(volumePercent) + self.volumeStatus.setText(f"Volume: {self.volume}%") + self.settings.set("playback", "volume", self.volume) + if announce: + self.announceLive(f"Volume {self.volume} percent") + if self.mpris and self.mpris.available: + self.mpris.notifyVolumeChanged() + + def setVolumeFromExternal(self, volumePercent: int): + """Apply volume set via MPRIS without re-announcing.""" + self.setVolumePercent(volumePercent, announce=False) + + def adjustVolume(self, delta: int): + """Adjust volume by a delta and update UI/settings.""" + self.setVolumePercent(self.volume + delta) + + def setShuffleState(self, enabled: bool, announce: bool = True, persist: bool = True): + """Apply shuffle setting consistently for UI, playback, and persistence.""" + self.shuffleAction.blockSignals(True) + self.shuffleAction.setChecked(enabled) + self.shuffleAction.blockSignals(False) + + self.playback.setShuffle(enabled) + self.shuffleEnabled = enabled + if persist: + self.settings.set("playback", "shuffle", enabled) + if announce: + self.announceLive(f"Shuffle {'enabled' if enabled else 'disabled'}") + if self.mpris and self.mpris.available: + self.mpris.notifyShuffleChanged() + + def setShuffleFromExternal(self, enabled: bool, announce: bool = False): + """Handle shuffle updates coming from MPRIS.""" + self.setShuffleState(enabled, announce=announce, persist=True) + + def applyRepeatMode(self, mode: str, announce: bool = True, persist: bool = True): + """Apply repeat mode ('none', 'one', 'all') across UI and playback.""" + if mode not in ("none", "one", "all"): + mode = "none" + + self.repeatAction.blockSignals(True) + self.repeatAction.setChecked(mode != "none") + if mode == "one": + self.repeatAction.setText("Repeat One") + elif mode == "all": + self.repeatAction.setText("Repeat All") + else: + self.repeatAction.setText("Repeat Off") + self.repeatAction.blockSignals(False) + + self.repeatMode = mode + self.playback.setRepeatMode(mode) + if persist: + self.settings.set("playback", "repeat", mode) + if announce: + self.announceLive(f"Repeat {'enabled' if mode != 'none' else 'disabled'}") + if self.mpris and self.mpris.available: + self.mpris.notifyLoopStatus() + + def setRepeatFromExternal(self, loopStatus: str, announce: bool = False): + """Map MPRIS loop status to internal repeat modes.""" + mode = {"Track": "one", "Playlist": "all", "None": "none"}.get(loopStatus, "none") + self.applyRepeatMode(mode, announce=announce, persist=True) + + def announceTrack(self): + """Speak current track details via an accessible dialog.""" + text = self.nowPlayingInfo.text() + AccessibleTextDialog.showInfo("Current Track", text, parent=self) + + def announcePosition(self): + """Speak current playback position.""" + AccessibleTextDialog.showInfo("Playback Position", self.positionLabel.text(), parent=self) + + def announceCurrentTrackLive(self): + """Announce the currently playing track via the live region.""" + song = self.playback.currentSong() + message = self.buildTrackAnnouncement(song) + self.announceLive(message) + + def enablePlaybackActions(self, enabled: bool): + """Enable or disable playback-related actions.""" + self.playPauseAction.setEnabled(enabled) + self.stopAction.setEnabled(enabled) + self.previousAction.setEnabled(enabled) + self.nextAction.setEnabled(enabled) + self.shuffleAction.setEnabled(True) + self.repeatAction.setEnabled(True) + self.volumeUpAction.setEnabled(True) + self.volumeDownAction.setEnabled(True) + self.favoriteAction.setEnabled(enabled) + self.unfavoriteAction.setEnabled(enabled) + + self.prevButton.setEnabled(enabled) + self.playButton.setEnabled(enabled) + self.stopButton.setEnabled(enabled) + self.nextButton.setEnabled(enabled) + self.positionSlider.setEnabled(enabled) + + # ============ Helpers ============ + + @staticmethod + def formatTime(ms: int) -> str: + """Convert milliseconds to mm:ss or hh:mm:ss.""" + totalSeconds = ms // 1000 + hours = totalSeconds // 3600 + minutes = (totalSeconds % 3600) // 60 + seconds = totalSeconds % 60 + if hours: + return f"{hours}:{minutes:02d}:{seconds:02d}" + return f"{minutes:02d}:{seconds:02d}" + + def copyToClipboard(self): + """Allow AccessibleTreeWidget to copy the current item's text.""" + item = self.libraryTree.currentItem() + if item: + QGuiApplication.clipboard().setText(item.text(0)) + + def buildTrackAnnouncement(self, song: Optional[Song]) -> str: + """Construct a live announcement for the current track with fallbacks.""" + if not song: + return "No track playing." + + title = (song.title or "").strip() + artist = (song.artist or "").strip() + album = (song.album or "").strip() + filename = Path(song.path).name if song.path else "" + + if title and artist and album: + return f"{title} by {artist} from {album}" + if title and artist: + return f"{title} by {artist}" + if filename: + return filename + if title: + return title + return "Unknown track" + + def buildFavoriteAnnouncement(self, action: str, song: Optional[Song], label: str) -> str: + """Create an announcement for favorite/unfavorite actions with track fallbacks.""" + base = self.buildTrackAnnouncement(song) if song else (label or "item") + verb = "added to favorites" if action == "favorite" else "removed from favorites" + return f"{base} {verb}" + + def buildFavoriteFailureAnnouncement(self, action: str, song: Optional[Song], label: str) -> str: + """Create an error announcement for favorite/unfavorite actions.""" + base = self.buildTrackAnnouncement(song) if song else (label or "item") + verb = "favorite" if action == "favorite" else "unfavorite" + return f"Could not {verb} {base}" + + def _resolveCoverArtUrl(self, coverId: Optional[str]) -> Optional[str]: + """Provide a cover art URL for MPRIS metadata when possible.""" + if not coverId or not self.client: + return None + try: + return self.client.getCoverArtUrl(coverId) + except Exception: + return None + + def announceLive(self, text: str): + """Update a live region and status bar for screen readers.""" + self.liveRegion.setText(text) + self.statusBar.showMessage(text, 2000) + try: + # Prefer explicit announcement event where supported + ann = QAccessibleAnnouncementEvent(self.liveRegion, text) + QAccessible.updateAccessibility(ann) + except Exception: + try: + event = QAccessibleEvent(self.liveRegion, QAccessible.Event.Alert) + QAccessible.updateAccessibility(event) + except Exception: + # As a last resort, change accessible name to trigger a change event + self.liveRegion.setAccessibleName(text) + except Exception: + # If accessibility event fails, rely on status bar message + pass + + # Shortcut handlers with feedback when no playback is active + + def handlePreviousShortcut(self, checked: bool = False): + """Go to previous track or announce why it cannot.""" + if not self.playback.queue: + self.announceLive("No tracks in the queue.") + return + if not self.playback.currentSong(): + self.announceLive("No track playing.") + return + self._announceOnTrackChange = True + self.playback.previous() + + def handlePlayShortcut(self, checked: bool = False): + """Start or resume playback, announcing if nothing is queued.""" + if not self.playback.queue: + self.announceLive("No tracks in the queue.") + return + self.playback.play() + + def handlePauseToggleShortcut(self, checked: bool = False): + """Toggle pause or announce when nothing is playing.""" + if not self.playback.currentSong(): + message = "No tracks in the queue." if not self.playback.queue else "No track playing." + self.announceLive(message) + return + self.playPauseAction.trigger() + + def handleStopShortcut(self, checked: bool = False): + """Stop playback or announce when nothing is playing.""" + if not self.playback.currentSong(): + self.announceLive("Nothing is playing.") + return + self.stopAction.trigger() + + def handleNextShortcut(self, checked: bool = False): + """Advance to next track or announce when it is unavailable.""" + if not self.playback.queue: + self.announceLive("No tracks in the queue.") + return + if not self.playback.currentSong(): + self.announceLive("No track playing.") + return + self._announceOnTrackChange = True + self.playback.next() + + def applyPersistedPlaybackSettings(self): + """Restore saved shuffle and repeat preferences without announcing.""" + shuffleEnabled = bool(self.shuffleEnabled) + repeatMode = self.repeatMode if self.repeatMode in ("none", "one", "all") else "none" + + self.setShuffleState(shuffleEnabled, announce=False, persist=False) + self.applyRepeatMode(repeatMode, announce=False, persist=False) + + self.announceTrackChangesAction.blockSignals(True) + self.announceTrackChangesAction.setChecked(self.announceTrackChangesEnabled) + self.announceTrackChangesAction.blockSignals(False) + + def _handleQueueChangedForMpris(self, queue: List[Song]): + """Update MPRIS capabilities and metadata when the queue changes.""" + if not self.mpris or not self.mpris.available: + return + self.mpris.notifyCapabilities() + if not queue: + self.mpris.updateMetadata(None) + + def getCurrentMediaTarget(self): + """Return (type, id, label, song) for the most relevant selection.""" + # Library tree selection + item = self.libraryTree.currentItem() + if item: + data: Dict = item.data(0, Qt.UserRole) or {} + itemType = data.get("type") + if itemType == "song": + song: Song = data["song"] + label = self.buildTrackAnnouncement(song) + return ("song", song.id, label, song) + if itemType in ("album", "artist"): + label = item.text(0) + return (itemType, data.get("id"), label, None) + + # Queue selection + row = self.queueList.currentRow() + if 0 <= row < len(self.playback.queue): + song = self.playback.queue[row] + label = self.buildTrackAnnouncement(song) + return ("song", song.id, label, song) + + # Now playing + current = self.playback.currentSong() + if current: + label = self.buildTrackAnnouncement(current) + return ("song", current.id, label, current) + return None + + def favoriteSelection(self): + """Favorite the selected or currently playing item.""" + target = self.getCurrentMediaTarget() + if not target or not self.client: + AccessibleTextDialog.showWarning("Favorite", "No item selected to favorite.", parent=self) + return + itemType, itemId, label, song = target + try: + self.client.star(itemId, itemType) + message = self.buildFavoriteAnnouncement("favorite", song, label) + self.statusBar.showMessage(message, 3000) + self.announceLive(message) + except Exception as e: + self.announceLive(self.buildFavoriteFailureAnnouncement("favorite", song, label)) + AccessibleTextDialog.showError("Favorite Failed", str(e), parent=self) + + def unfavoriteSelection(self): + """Unfavorite the selected or currently playing item.""" + target = self.getCurrentMediaTarget() + if not target or not self.client: + AccessibleTextDialog.showWarning("Unfavorite", "No item selected to unfavorite.", parent=self) + return + itemType, itemId, label, song = target + try: + self.client.unstar(itemId, itemType) + message = self.buildFavoriteAnnouncement("unfavorite", song, label) + self.statusBar.showMessage(message, 3000) + self.announceLive(message) + except Exception as e: + self.announceLive(self.buildFavoriteFailureAnnouncement("unfavorite", song, label)) + AccessibleTextDialog.showError("Unfavorite Failed", str(e), parent=self) + + def showAbout(self): + """Show the about dialog""" + AccessibleTextDialog.showInfo( + "About NaviPy", + "NaviPy - Accessible Navidrome Client\n\n" + "An accessible music player for Navidrome servers.\n\n" + "Built with PySide6 for full keyboard navigation " + "and screen reader compatibility.\n\n" + "Version: 0.1.0 (Development)", + parent=self + ) + + def closeEvent(self, event): + """Handle window close""" + self.settings.set("playback", "volume", self.volume) + self.settings.save() + if self.mpris: + self.mpris.shutdown() + event.accept() diff --git a/src/managers/__init__.py b/src/managers/__init__.py new file mode 100644 index 0000000..f706bd9 --- /dev/null +++ b/src/managers/__init__.py @@ -0,0 +1 @@ +"""Business logic managers module""" diff --git a/src/managers/playback_manager.py b/src/managers/playback_manager.py new file mode 100644 index 0000000..fde2a56 --- /dev/null +++ b/src/managers/playback_manager.py @@ -0,0 +1,206 @@ +""" +Playback manager using PySide6 multimedia for streaming audio +""" + +from __future__ import annotations + +from typing import Callable, List, Optional +from random import randint + +from PySide6.QtCore import QObject, QUrl, Signal +from PySide6.QtMultimedia import QAudioOutput, QMediaPlayer + +from src.api.models import Song + + +class PlaybackManager(QObject): + """ + Handles the play queue and integrates QMediaPlayer with Subsonic streams. + A resolver callable is provided by the main window to convert a Song into + a streamable URL. + """ + + trackChanged = Signal(Song) + queueChanged = Signal(list) + playbackStateChanged = Signal(str) + positionChanged = Signal(int, int) # position, duration + errorOccurred = Signal(str) + + def __init__(self, parent: Optional[QObject] = None): + super().__init__(parent) + self.player = QMediaPlayer() + self.audioOutput = QAudioOutput() + self.player.setAudioOutput(self.audioOutput) + + self.queue: List[Song] = [] + self.currentIndex: int = -1 + self.streamResolver: Optional[Callable[[Song], str]] = None + self.shuffleEnabled = False + self.repeatMode = "none" # none, one, all + + self.player.playbackStateChanged.connect(self._handlePlaybackStateChanged) + self.player.positionChanged.connect(self._handlePositionChanged) + self.player.mediaStatusChanged.connect(self._handleMediaStatus) + self.player.errorOccurred.connect(self._handleError) + + def setStreamResolver(self, resolver: Callable[[Song], str]) -> None: + """Set resolver used to turn a Song into a playable URL.""" + self.streamResolver = resolver + + def setVolume(self, volumePercent: int) -> None: + """Set audio output volume (0-100).""" + volumePercent = max(0, min(100, volumePercent)) + self.audioOutput.setVolume(volumePercent / 100) + + def enqueue(self, song: Song, playNow: bool = False) -> None: + """Add a song to the queue, optionally starting playback immediately.""" + self.queue.append(song) + self.queueChanged.emit(self.queue.copy()) + if playNow or self.currentIndex == -1: + self.playIndex(len(self.queue) - 1) + + def enqueueMany(self, songs: List[Song], playFirst: bool = False) -> None: + """Add multiple songs to the queue.""" + if not songs: + return + startIndex = len(self.queue) + self.queue.extend(songs) + self.queueChanged.emit(self.queue.copy()) + if playFirst or self.currentIndex == -1: + self.playIndex(startIndex) + + def clearQueue(self) -> None: + """Clear the play queue and stop playback.""" + self.queue = [] + self.currentIndex = -1 + self.player.stop() + self.queueChanged.emit(self.queue.copy()) + self.playbackStateChanged.emit("stopped") + + def playIndex(self, index: int) -> None: + """Play the song at the given queue index.""" + if not (0 <= index < len(self.queue)): + return + if not self.streamResolver: + self.errorOccurred.emit("No stream resolver configured.") + return + + self.currentIndex = index + song = self.queue[index] + streamUrl = self.streamResolver(song) + self.player.setSource(QUrl(streamUrl)) + self.player.play() + self.trackChanged.emit(song) + self.queueChanged.emit(self.queue.copy()) + + def togglePlayPause(self) -> None: + """Toggle between play and pause.""" + state = self.player.playbackState() + if state == QMediaPlayer.PlayingState: + self.player.pause() + elif state == QMediaPlayer.PausedState: + self.player.play() + else: + if self.currentIndex == -1 and self.queue: + self.playIndex(0) + elif self.currentIndex != -1: + self.player.play() + + def play(self) -> None: + """Start or resume playback without pausing when already playing.""" + state = self.player.playbackState() + if state == QMediaPlayer.PlayingState: + return + if state == QMediaPlayer.PausedState: + self.player.play() + return + if self.currentIndex == -1 and self.queue: + self.playIndex(0) + elif self.currentIndex != -1: + self.player.play() + + def stop(self) -> None: + """Stop playback and reset position.""" + self.player.stop() + self.playbackStateChanged.emit("stopped") + + def next(self, fromAuto: bool = False) -> None: + """Advance to the next track in the queue.""" + if not self.queue: + return + + if self.repeatMode == "one" and fromAuto: + self.playIndex(self.currentIndex) + return + + if self.shuffleEnabled: + target = randint(0, len(self.queue) - 1) + else: + target = self.currentIndex + 1 + + if target >= len(self.queue): + if self.repeatMode == "all": + target = 0 + else: + self.player.stop() + return + + self.playIndex(target) + + def previous(self) -> None: + """Return to the previous track.""" + if not self.queue: + return + target = self.currentIndex - 1 + if target < 0: + if self.repeatMode == "all": + target = len(self.queue) - 1 + else: + target = 0 + self.playIndex(target) + + def seek(self, positionMs: int) -> None: + """Seek to a position within the current track.""" + self.player.setPosition(max(0, positionMs)) + + def setShuffle(self, enabled: bool) -> None: + """Enable or disable shuffle mode.""" + self.shuffleEnabled = enabled + + def setRepeatMode(self, mode: str) -> None: + """Set repeat mode: none, one, or all.""" + if mode in ("none", "one", "all"): + self.repeatMode = mode + + def currentSong(self) -> Optional[Song]: + """Get the currently playing song if available.""" + if 0 <= self.currentIndex < len(self.queue): + return self.queue[self.currentIndex] + return None + + # Signal handlers + + def _handlePlaybackStateChanged(self, state) -> None: + """Emit simplified playback state.""" + mapping = { + QMediaPlayer.PlayingState: "playing", + QMediaPlayer.PausedState: "paused", + QMediaPlayer.StoppedState: "stopped" + } + self.playbackStateChanged.emit(mapping.get(state, "unknown")) + + def _handlePositionChanged(self, position: int) -> None: + """Emit position updates along with duration.""" + self.positionChanged.emit(position, self.player.duration()) + + def _handleMediaStatus(self, status) -> None: + """Automatically progress when a track finishes.""" + from PySide6.QtMultimedia import QMediaPlayer as MP # Local import avoids circular typing + if status == MP.EndOfMedia: + self.next(fromAuto=True) + + def _handleError(self, error) -> None: + """Surface player errors to the UI.""" + if error: + description = self.player.errorString() or str(error) + self.errorOccurred.emit(description) diff --git a/src/models/__init__.py b/src/models/__init__.py new file mode 100644 index 0000000..f98c583 --- /dev/null +++ b/src/models/__init__.py @@ -0,0 +1 @@ +"""Data models module""" diff --git a/src/widgets/__init__.py b/src/widgets/__init__.py new file mode 100644 index 0000000..ed8b7a0 --- /dev/null +++ b/src/widgets/__init__.py @@ -0,0 +1 @@ +"""UI widgets module""" diff --git a/src/widgets/accessible_text_dialog.py b/src/widgets/accessible_text_dialog.py new file mode 100644 index 0000000..69a1bee --- /dev/null +++ b/src/widgets/accessible_text_dialog.py @@ -0,0 +1,105 @@ +""" +Accessible text display dialog - single point of truth for showing text to screen reader users +Based on the implementation from Bifrost +""" + +from PySide6.QtWidgets import ( + QDialog, QVBoxLayout, QTextEdit, QDialogButtonBox +) +from PySide6.QtCore import Qt + + +class AccessibleTextDialog(QDialog): + """ + Single reusable dialog for displaying text content accessibly to screen readers. + Provides keyboard navigation, text selection, and proper focus management. + """ + + def __init__(self, title: str, content: str, dialogType: str = "info", parent=None): + """ + Initialize accessible text dialog + + Args: + title: Window title + content: Text content to display + dialogType: "info", "error", "success", or "warning" - affects accessible name + parent: Parent widget + """ + super().__init__(parent) + self.setWindowTitle(title) + self.setModal(True) + + # Size based on content length + if len(content) > 500: + self.setMinimumSize(600, 400) + elif len(content) > 200: + self.setMinimumSize(500, 300) + else: + self.setMinimumSize(400, 200) + + self.setupUi(content, dialogType) + + def setupUi(self, content: str, dialogType: str): + """Setup the dialog UI with accessible text widget""" + layout = QVBoxLayout(self) + + # Create accessible text edit widget + self.textEdit = QTextEdit() + self.textEdit.setPlainText(content) + self.textEdit.setReadOnly(True) + + # Set accessible name based on dialog type + accessibleNames = { + "info": "Information Text", + "error": "Error Details", + "warning": "Warning Information", + "success": "Success Information" + } + self.textEdit.setAccessibleName(accessibleNames.get(dialogType, "Dialog Text")) + + # Enable keyboard text selection and navigation + self.textEdit.setTextInteractionFlags( + Qt.TextSelectableByKeyboard | Qt.TextSelectableByMouse + ) + + layout.addWidget(self.textEdit) + + # Button box + buttonBox = QDialogButtonBox(QDialogButtonBox.Ok) + buttonBox.accepted.connect(self.accept) + layout.addWidget(buttonBox) + + # Focus the text edit first so user can immediately read content + self.textEdit.setFocus() + + @classmethod + def showInfo(cls, title: str, content: str, parent=None): + """Convenience method for info dialogs""" + dialog = cls(title, content, "info", parent) + dialog.exec() + + @classmethod + def showError(cls, title: str, message: str, details: str = None, parent=None): + """Convenience method for error dialogs with optional details""" + if details: + content = f"{message}\n\nError Details:\n{details}" + else: + content = message + dialog = cls(title, content, "error", parent) + dialog.exec() + + @classmethod + def showSuccess(cls, title: str, message: str, details: str = None, parent=None): + """Convenience method for success dialogs with optional details""" + if details: + content = f"{message}\n\n{details}" + else: + content = message + dialog = cls(title, content, "success", parent) + dialog.exec() + + @classmethod + def showWarning(cls, title: str, content: str, parent=None): + """Convenience method for warning dialogs""" + dialog = cls(title, content, "warning", parent) + dialog.exec() diff --git a/src/widgets/search_dialog.py b/src/widgets/search_dialog.py new file mode 100644 index 0000000..0735c60 --- /dev/null +++ b/src/widgets/search_dialog.py @@ -0,0 +1,108 @@ +""" +Accessible search dialog for finding tracks quickly. +""" + +from __future__ import annotations + +from typing import List + +from PySide6.QtCore import Signal, Qt +from PySide6.QtWidgets import ( + QDialog, + QDialogButtonBox, + QHBoxLayout, + QLabel, + QLineEdit, + QListWidget, + QListWidgetItem, + QPushButton, + QVBoxLayout, +) + +from src.api.client import SubsonicClient +from src.api.models import Song +from src.widgets.accessible_text_dialog import AccessibleTextDialog + + +class SearchDialog(QDialog): + """Simple dialog for searching the Navidrome library.""" + + songActivated = Signal(Song) + + def __init__(self, client: SubsonicClient, parent=None): + super().__init__(parent) + self.client = client + self.setWindowTitle("Search Library") + self.setMinimumSize(500, 420) + self.setupUi() + + def setupUi(self): + layout = QVBoxLayout(self) + + self.instructions = QLabel("Enter a song, artist, or album title. Press Enter to play results.") + self.instructions.setAccessibleName("Search Instructions") + self.instructions.setWordWrap(True) + layout.addWidget(self.instructions) + + inputLayout = QHBoxLayout() + self.queryEdit = QLineEdit() + self.queryEdit.setAccessibleName("Search Query") + self.queryEdit.returnPressed.connect(self.runSearch) + inputLayout.addWidget(self.queryEdit) + + self.searchButton = QPushButton("&Search") + self.searchButton.setAccessibleName("Start Search") + self.searchButton.clicked.connect(self.runSearch) + inputLayout.addWidget(self.searchButton) + + layout.addLayout(inputLayout) + + self.resultsList = QListWidget() + self.resultsList.setAccessibleName("Search Results") + self.resultsList.itemActivated.connect(self.activateSelection) + layout.addWidget(self.resultsList) + + self.statusLabel = QLabel("") + self.statusLabel.setAccessibleName("Search Status") + layout.addWidget(self.statusLabel) + + buttonBox = QDialogButtonBox(QDialogButtonBox.Close) + buttonBox.rejected.connect(self.reject) + layout.addWidget(buttonBox) + + def runSearch(self): + """Run the Subsonic search and populate results.""" + query = self.queryEdit.text().strip() + if not query: + self.statusLabel.setText("Enter a search term to begin.") + return + + self.statusLabel.setText("Searching...") + self.resultsList.clear() + try: + results = self.client.search(query, artistCount=0, albumCount=0, songCount=50) + songs: List[Song] = results.get("songs", []) + if not songs: + self.statusLabel.setText("No songs found.") + return + + for song in songs: + text = f"{song.title} — {song.artist} ({song.album}, {song.durationFormatted})" + item = QListWidgetItem(text) + item.setData(Qt.UserRole, song) + item.setData(Qt.AccessibleTextRole, text) + self.resultsList.addItem(item) + + self.statusLabel.setText(f"Found {len(songs)} songs. Activate a result to play.") + self.resultsList.setCurrentRow(0) + self.resultsList.setFocus() + except Exception as e: + AccessibleTextDialog.showError("Search Error", str(e), parent=self) + self.statusLabel.setText("Search failed.") + + def activateSelection(self, item: QListWidgetItem): + """Emit the chosen song and close the dialog.""" + song = item.data(Qt.UserRole) + if isinstance(song, Song): + self.songActivated.emit(song) + self.accept() diff --git a/src/widgets/server_dialog.py b/src/widgets/server_dialog.py new file mode 100644 index 0000000..7facb43 --- /dev/null +++ b/src/widgets/server_dialog.py @@ -0,0 +1,206 @@ +""" +Server connection dialog for adding/editing Navidrome servers +""" + +from PySide6.QtWidgets import ( + QDialog, QVBoxLayout, QHBoxLayout, QFormLayout, + QLineEdit, QPushButton, QLabel, QMessageBox, QCheckBox +) +from PySide6.QtCore import Qt + +from src.api.client import SubsonicClient, SubsonicError +from src.config.settings import Settings + + +class ServerDialog(QDialog): + """Dialog for configuring a Navidrome server connection""" + + def __init__(self, settings: Settings, serverName: str = None, parent=None): + """ + Initialize the server dialog + + Args: + settings: Application settings instance + serverName: Name of existing server to edit (None for new server) + parent: Parent widget + """ + super().__init__(parent) + self.settings = settings + self.editingServer = serverName + self.isNew = serverName is None + + self.setWindowTitle("Add Server" if self.isNew else "Edit Server") + self.setModal(True) + self.setMinimumWidth(400) + + self.setupUi() + self.loadExistingData() + + def setupUi(self): + """Setup the dialog UI""" + layout = QVBoxLayout(self) + + # Form layout for inputs + formLayout = QFormLayout() + + # Server name + self.nameEdit = QLineEdit() + self.nameEdit.setAccessibleName("Server Name") + self.nameEdit.setAccessibleDescription("A friendly name for this server") + nameLabel = QLabel("&Name:") + nameLabel.setBuddy(self.nameEdit) + formLayout.addRow(nameLabel, self.nameEdit) + + # Server URL + self.urlEdit = QLineEdit() + self.urlEdit.setAccessibleName("Server URL") + self.urlEdit.setAccessibleDescription("The full URL to your Navidrome server, for example https://music.example.com") + self.urlEdit.setPlaceholderText("https://music.example.com") + urlLabel = QLabel("&URL:") + urlLabel.setBuddy(self.urlEdit) + formLayout.addRow(urlLabel, self.urlEdit) + + # Username + self.usernameEdit = QLineEdit() + self.usernameEdit.setAccessibleName("Username") + usernameLabel = QLabel("U&sername:") + usernameLabel.setBuddy(self.usernameEdit) + formLayout.addRow(usernameLabel, self.usernameEdit) + + # Password + self.passwordEdit = QLineEdit() + self.passwordEdit.setEchoMode(QLineEdit.Password) + self.passwordEdit.setAccessibleName("Password") + passwordLabel = QLabel("&Password:") + passwordLabel.setBuddy(self.passwordEdit) + formLayout.addRow(passwordLabel, self.passwordEdit) + + # Set as default checkbox + self.defaultCheckbox = QCheckBox("Set as &default server") + self.defaultCheckbox.setAccessibleName("Set as default server") + formLayout.addRow("", self.defaultCheckbox) + + layout.addLayout(formLayout) + + # Status label for connection test + self.statusLabel = QLabel("") + self.statusLabel.setAccessibleName("Connection Status") + self.statusLabel.setWordWrap(True) + layout.addWidget(self.statusLabel) + + # Button layout + buttonLayout = QHBoxLayout() + + self.testButton = QPushButton("&Test Connection") + self.testButton.setAccessibleName("Test Connection") + self.testButton.clicked.connect(self.testConnection) + buttonLayout.addWidget(self.testButton) + + buttonLayout.addStretch() + + self.cancelButton = QPushButton("&Cancel") + self.cancelButton.setAccessibleName("Cancel") + self.cancelButton.clicked.connect(self.reject) + buttonLayout.addWidget(self.cancelButton) + + self.saveButton = QPushButton("&Save") + self.saveButton.setAccessibleName("Save") + self.saveButton.setDefault(True) + self.saveButton.clicked.connect(self.saveServer) + buttonLayout.addWidget(self.saveButton) + + layout.addLayout(buttonLayout) + + # Set initial focus + self.nameEdit.setFocus() + + def loadExistingData(self): + """Load existing server data if editing""" + if not self.isNew and self.editingServer: + server = self.settings.getServer(self.editingServer) + if server: + self.nameEdit.setText(self.editingServer) + self.nameEdit.setReadOnly(True) # Can't change name when editing + self.urlEdit.setText(server.get('url', '')) + self.usernameEdit.setText(server.get('username', '')) + self.passwordEdit.setText(server.get('password', '')) + + # Check if this is the default server + defaultServer = self.settings.getDefaultServer() + self.defaultCheckbox.setChecked(defaultServer == self.editingServer) + + def testConnection(self): + """Test connection to the server""" + url = self.urlEdit.text().strip() + username = self.usernameEdit.text().strip() + password = self.passwordEdit.text() + + if not url or not username or not password: + self.statusLabel.setText("Please fill in all fields") + return + + self.statusLabel.setText("Testing connection...") + self.testButton.setEnabled(False) + + try: + client = SubsonicClient(url, username, password) + if client.ping(): + self.statusLabel.setText("Connection successful!") + else: + self.statusLabel.setText("Connection failed: Invalid response") + except SubsonicError as e: + self.statusLabel.setText(f"Connection failed: {e.message}") + except Exception as e: + self.statusLabel.setText(f"Connection failed: {str(e)}") + finally: + self.testButton.setEnabled(True) + + def saveServer(self): + """Save the server configuration""" + name = self.nameEdit.text().strip() + url = self.urlEdit.text().strip() + username = self.usernameEdit.text().strip() + password = self.passwordEdit.text() + + # Validate inputs + if not name: + QMessageBox.warning(self, "Validation Error", "Please enter a server name") + self.nameEdit.setFocus() + return + + if not url: + QMessageBox.warning(self, "Validation Error", "Please enter the server URL") + self.urlEdit.setFocus() + return + + if not username: + QMessageBox.warning(self, "Validation Error", "Please enter a username") + self.usernameEdit.setFocus() + return + + if not password: + QMessageBox.warning(self, "Validation Error", "Please enter a password") + self.passwordEdit.setFocus() + return + + # Check for duplicate name when adding new server + if self.isNew and self.settings.getServer(name): + QMessageBox.warning( + self, "Validation Error", + f"A server named '{name}' already exists. Please choose a different name." + ) + self.nameEdit.setFocus() + return + + # Save the server + self.settings.addServer(name, url, username, password) + + # Set as default if checked + if self.defaultCheckbox.isChecked(): + self.settings.setDefaultServer(name) + + self.accept() + + def getServerName(self) -> str: + """Get the name of the saved server""" + return self.nameEdit.text().strip()