commit b5a0f3c67195dc1f003a597d5e9496240ce6da18 Author: Charles Escobar Date: Sun Aug 23 01:18:21 2026 -0500 Commit inicial: G Radio Remoto — Android Cliente remoto Android (Kotlin + Jetpack Compose) para G Radio Player, mismo protocolo TCP/relay que el cliente de escritorio: reproductor, buscador, parrilla, pautaje, botonera, comercios y visor remotos. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8447abf --- /dev/null +++ b/.gitignore @@ -0,0 +1,21 @@ +# Gradle / Android build +.gradle/ +.kotlin/ +build/ +app/build/ +*.apk +*.aab +local.properties + +# Android Studio / IDE +.idea/ +*.iml +.DS_Store +captures/ +.externalNativeBuild/ +.cxx/ + +# Keystores reales (nunca subir claves de firma) +*.jks +*.keystore +key.properties 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..1c71bb5 --- /dev/null +++ b/README.md @@ -0,0 +1,41 @@ +# G Radio Remoto — Android + +Cliente remoto para Android (Kotlin + Jetpack Compose) — controla +[G Radio Player](https://git.gradio.net/cescobar/G-Radio-Player) desde el +celular, en LAN o por internet vía relay. Mismo protocolo TCP/WebSocket que el +[cliente de escritorio](https://git.gradio.net/cescobar/G-Radio-Remoto). + +## Compilar + +```bash +./gradlew assembleDebug +# o +./gradlew assembleRelease +``` + +El APK queda en `app/build/outputs/apk/`. + +## Pantallas + +- **Player** — reproductor remoto +- **Buscador** — búsqueda de audio en el servidor +- **Parrilla** — programación musical +- **Pautaje** — comerciales y eventos +- **Botonera** — reproducción rápida de efectos +- **Comercios** — gestión de comerciales +- **Visor** — reportes remotos + +## Conexión + +Barra de conexión (`ConnectionBar`) para servidor, puerto y token — mismo +protocolo (`Protocol.kt`) que el cliente de escritorio, sincronizado con +`servidor.rs` de `radio-player`. + +## Idiomas + +Español, inglés (default) y portugués — `res/values{-es,-pt}/strings.xml`. + +## Licencia + +Distribuido bajo los términos de la **GNU General Public License v3.0 o posterior** +(GPL-3.0-or-later). Ver el archivo [`LICENSE`](./LICENSE). diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 0000000..ea8b2f3 --- /dev/null +++ b/app/build.gradle.kts @@ -0,0 +1,92 @@ +plugins { + alias(libs.plugins.android.application) + alias(libs.plugins.kotlin.android) + alias(libs.plugins.kotlin.compose) +} + +android { + namespace = "com.gradio.client" + compileSdk = 36 + + defaultConfig { + applicationId = "com.gradio.client" + minSdk = 26 + targetSdk = 36 + versionCode = 8 + versionName = "1.0.7" + + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + signingConfigs { + create("sideload") { + storeFile = file(System.getProperty("user.home") + "/.android/debug.keystore") + storePassword = "android" + keyAlias = "androiddebugkey" + keyPassword = "android" + } + } + + buildTypes { + release { + isMinifyEnabled = false + signingConfig = signingConfigs.getByName("sideload") + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) + } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + kotlinOptions { + jvmTarget = "11" + } + buildFeatures { + compose = true + } + packaging { + resources { + excludes += "/META-INF/{AL2.0,LGPL2.1}" + } + } +} + +dependencies { + implementation(libs.androidx.core.ktx) + implementation(libs.androidx.lifecycle.runtime.ktx) + implementation(libs.androidx.lifecycle.viewmodel.compose) + implementation(libs.androidx.activity.compose) + implementation(libs.androidx.navigation.compose) + implementation(platform(libs.androidx.compose.bom)) + implementation(libs.androidx.compose.ui) + implementation(libs.androidx.compose.ui.graphics) + implementation(libs.androidx.compose.ui.tooling.preview) + implementation(libs.androidx.compose.material3) + implementation(libs.okhttp) + implementation(libs.gson) + implementation("androidx.compose.material:material-icons-extended") + testImplementation(libs.junit) + androidTestImplementation(libs.androidx.junit) + androidTestImplementation(libs.androidx.espresso.core) + debugImplementation(libs.androidx.compose.ui.tooling) + debugImplementation(libs.androidx.compose.ui.test.manifest) +} + +tasks.register("renameApk") { + doLast { + val buildType = if (gradle.startParameter.taskNames.any { it.contains("Release") }) "release" else "debug" + val originalFile = file("build/outputs/apk/$buildType/app-$buildType.apk") + val newFile = file("build/outputs/apk/$buildType/GRadioClient.apk") + if (originalFile.exists()) { + originalFile.renameTo(newFile) + } + } +} + +afterEvaluate { + tasks.named("assembleDebug").configure { finalizedBy("renameApk") } + tasks.named("assembleRelease").configure { finalizedBy("renameApk") } +} diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..655f2f0 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1 @@ +-keep class com.gradio.client.data.** { *; } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..61fdf9b --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/java/com/gradio/client/MainActivity.kt b/app/src/main/java/com/gradio/client/MainActivity.kt new file mode 100644 index 0000000..4178061 --- /dev/null +++ b/app/src/main/java/com/gradio/client/MainActivity.kt @@ -0,0 +1,142 @@ +package com.gradio.client + +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.activity.viewModels +import androidx.compose.foundation.layout.* +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.* +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.gradio.client.network.EstadoCon +import com.gradio.client.ui.components.ConnectionBar +import com.gradio.client.ui.screens.* +import com.gradio.client.ui.theme.GRadioClientTheme +import com.gradio.client.ui.viewmodel.MainViewModel + +sealed class Screen(val route: String, val label: String, val icon: ImageVector) { + object Player : Screen("player", "Player", Icons.Default.PlayArrow) + object Buscador : Screen("buscador", "Búsqueda", Icons.Default.Search) + object Parrilla : Screen("parrilla", "Parrilla", Icons.Default.CalendarMonth) + object Botonera : Screen("botonera", "Botonera", Icons.Default.GridView) + object Pautaje : Screen("pautaje", "Pautaje", Icons.Default.Schedule) + object Comercios : Screen("comercios", "Comercios", Icons.Default.Campaign) + object Visor : Screen("visor", "Reportes", Icons.Default.BarChart) +} + +val SCREENS = listOf( + Screen.Player, + Screen.Buscador, + Screen.Parrilla, + Screen.Botonera, + Screen.Pautaje, + Screen.Comercios, + Screen.Visor +) + +class MainActivity : ComponentActivity() { + + private val vm: MainViewModel by viewModels() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enableEdgeToEdge() + setContent { + GRadioClientTheme { + GRadioClientApp(vm) + } + } + } +} + +@Composable +fun GRadioClientApp(vm: MainViewModel) { + val config by vm.config.collectAsState() + val estadoCon by vm.estadoCon.collectAsState() + val snackbar by vm.snackbar.collectAsState() + var pantalla by remember { mutableStateOf(Screen.Player) } + val snackbarHostState = remember { SnackbarHostState() } + + // Mostrar snackbar cuando llega + LaunchedEffect(snackbar) { + snackbar?.let { + snackbarHostState.showSnackbar(it, duration = SnackbarDuration.Short) + vm.limpiarSnackbar() + } + } + + Scaffold( + snackbarHost = { + SnackbarHost(snackbarHostState) { data -> + Snackbar( + snackbarData = data, + containerColor = com.gradio.client.ui.theme.GradioCard, + contentColor = com.gradio.client.ui.theme.OnBg + ) + } + }, + bottomBar = { + BottomNavBar(pantalla) { pantalla = it } + }, + containerColor = com.gradio.client.ui.theme.GradioBg + ) { paddingValues -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(paddingValues) + ) { + // Barra de conexión siempre visible arriba + ConnectionBar( + estadoCon = estadoCon, + config = config, + onConectar = { cfg -> vm.conectar(cfg) }, + onDesconectar = { vm.desconectar() } + ) + + // Contenido de la pantalla activa + Box(modifier = Modifier.fillMaxSize()) { + when (pantalla) { + Screen.Player -> PlayerScreen(vm) + Screen.Buscador -> BuscadorScreen(vm) + Screen.Parrilla -> ParrillaScreen(vm) + Screen.Botonera -> BotoneraScreen(vm) + Screen.Pautaje -> PautajeScreen(vm) + Screen.Comercios -> ComerciosScreen(vm) + Screen.Visor -> VisorScreen(vm) + } + } + } + } +} + +@Composable +private fun BottomNavBar(actual: Screen, onSelect: (Screen) -> Unit) { + NavigationBar( + containerColor = com.gradio.client.ui.theme.GradioSurface, + contentColor = com.gradio.client.ui.theme.OnBg + ) { + SCREENS.forEach { screen -> + NavigationBarItem( + selected = actual == screen, + onClick = { onSelect(screen) }, + icon = { + Icon(screen.icon, contentDescription = screen.label, modifier = Modifier.size(22.dp)) + }, + label = { Text(screen.label, fontSize = 10.sp, maxLines = 1) }, + colors = NavigationBarItemDefaults.colors( + selectedIconColor = com.gradio.client.ui.theme.GradioGreen, + selectedTextColor = com.gradio.client.ui.theme.GradioGreen, + unselectedIconColor = com.gradio.client.ui.theme.OnSurfaceDim, + unselectedTextColor = com.gradio.client.ui.theme.OnSurfaceDim, + indicatorColor = com.gradio.client.ui.theme.GradioGreenDk.copy(alpha = 0.2f) + ) + ) + } + } +} diff --git a/app/src/main/java/com/gradio/client/data/Protocol.kt b/app/src/main/java/com/gradio/client/data/Protocol.kt new file mode 100644 index 0000000..4b5721e --- /dev/null +++ b/app/src/main/java/com/gradio/client/data/Protocol.kt @@ -0,0 +1,189 @@ +package com.gradio.client.data + +import com.google.gson.annotations.SerializedName + +// ── Tipos compartidos ───────────────────────────────────────────────────────── + +data class EntradaRemota( + val ruta: String = "", + val dias: String = "", + val inicio: String = "", + val fin: String = "" +) + +data class TrackRemoto( + val ruta: String = "", + val duracion: String = "", + val titulo: String = "" +) + +data class EstadoRemoto( + val reproduciendo: Boolean = false, + val pausado: Boolean = false, + val track_actual: String = "", + val titulo_actual: String = "", + val posicion_secs: Double = 0.0, + val duracion_secs: Double = 0.0, + val upvol: Int = 85, + val downvol: Int = 85, + val comerciales_activos: Boolean = false, + val eventos_activos: Boolean = false, + val num_comerciales: Int = 0, + val num_eventos: Int = 0, + val num_eventos_espera: Int = 0, + val indice_actual: Int = 0 +) + +data class EntradaDir( + val nombre: String = "", + val ruta: String = "", + val es_dir: Boolean = false, + val es_audio: Boolean = false, + val tiene_hijos: Boolean = false +) + +data class ResultadoBusqueda( + val ruta: String = "", + val nombre: String = "", + val duracion: String = "" +) + +data class BotonRemoto( + val indice: Int = 0, + val etiqueta: String = "", + val ruta: String = "", + val color: String = "" +) + +data class ItemTanda( + val ruta: String = "", + val nombre: String = "", + val duracion_secs: Double = 0.0 +) + +data class TandaRemota( + val hora: Int = 0, + val minuto: Int = 0, + val items: List = emptyList(), + val duracion_total_secs: Double = 0.0 +) + +// ── Mensajes Cliente → Servidor ─────────────────────────────────────────────── + +sealed class MsgCliente { + abstract val tipo: String + + data class Auth(val token: String) : MsgCliente() { + override val tipo = "Auth" + } + object Ping : MsgCliente() { + override val tipo = "Ping" + } + data class ListarDir(val ruta: String) : MsgCliente() { + override val tipo = "ListarDir" + } + data class ObtenerPautaje(val tipo_p: String, val hora: Int, val minuto: Int) : MsgCliente() { + override val tipo = "ObtenerPautaje" + } + data class GuardarPautaje(val tipo_p: String, val hora: Int, val minuto: Int, val entradas: List) : MsgCliente() { + override val tipo = "GuardarPautaje" + } + data class ObtenerParrilla(val dia: Int, val hora: Int) : MsgCliente() { + override val tipo = "ObtenerParrilla" + } + data class GuardarParrilla(val dia: Int, val hora: Int, val items: List) : MsgCliente() { + override val tipo = "GuardarParrilla" + } + object ObtenerBotonera : MsgCliente() { + override val tipo = "ObtenerBotonera" + } + data class GuardarBotonera(val botones: List) : MsgCliente() { + override val tipo = "GuardarBotonera" + } + object ObtenerPlaylist : MsgCliente() { + override val tipo = "ObtenerPlaylist" + } + object ObtenerEstado : MsgCliente() { + override val tipo = "ObtenerEstado" + } + data class ComandoPlayer(val cmd: String) : MsgCliente() { + override val tipo = "ComandoPlayer" + } + data class SetVolumen(val upvol: Int) : MsgCliente() { + override val tipo = "SetVolumen" + } + data class ReproducirAhora(val ruta: String) : MsgCliente() { + override val tipo = "ReproducirAhora" + } + data class AgregarAlPlaylist(val ruta: String, val duracion: String, val alInicio: Boolean = false) : MsgCliente() { + override val tipo = "AgregarAlPlaylist" + } + data class EliminarDePlaylist(val indice: Int) : MsgCliente() { + override val tipo = "EliminarDePlaylist" + } + data class MoverEnPlaylist(val indice: Int, val arriba: Boolean) : MsgCliente() { + override val tipo = "MoverEnPlaylist" + } + data class Buscar(val consulta: String, val ruta: String?) : MsgCliente() { + override val tipo = "Buscar" + } + data class ObtenerReportes(val tipo_r: String, val fecha: String) : MsgCliente() { + override val tipo = "ObtenerReportes" + } + object ActualizarIndice : MsgCliente() { + override val tipo = "ActualizarIndice" + } + data class PlaylistPlayAhora(val ruta: String, val duracion: String) : MsgCliente() { + override val tipo = "PlaylistPlayAhora" + } + object StopGeneral : MsgCliente() { + override val tipo = "StopGeneral" + } + object VaciarComerciales : MsgCliente() { + override val tipo = "VaciarComerciales" + } + object VaciarEventos : MsgCliente() { + override val tipo = "VaciarEventos" + } + object VaciarEventosEspera : MsgCliente() { + override val tipo = "VaciarEventosEspera" + } + data class ObtenerCola(val tipo_cola: String) : MsgCliente() { + override val tipo = "ObtenerCola" + } + data class EliminarDeCola(val tipo_cola: String, val indice: Int) : MsgCliente() { + override val tipo = "EliminarDeCola" + } + object ObtenerProximasTandas : MsgCliente() { + override val tipo = "ObtenerProximasTandas" + } + data class ReproducirTanda(val hora: Int, val minuto: Int, val items: List) : MsgCliente() { + override val tipo = "ReproducirTanda" + } +} + +// ── Mensajes Servidor → Cliente ─────────────────────────────────────────────── + +sealed class MsgServidor { + data class AuthOk(val version: String) : MsgServidor() + object Pong : MsgServidor() + data class Error(val mensaje: String) : MsgServidor() + data class DirectorioListado(val ruta: String, val entradas: List) : MsgServidor() + data class PautajeObtenido(val tipo_p: String, val hora: Int, val minuto: Int, val entradas: List) : MsgServidor() + object PautajeGuardado : MsgServidor() + data class ParrillaObtenida(val dia: Int, val hora: Int, val items: List) : MsgServidor() + object ParrillaGuardada : MsgServidor() + data class BotoneraObtenida(val botones: List) : MsgServidor() + object BotoneraGuardada : MsgServidor() + data class PlaylistObtenida(val tracks: List) : MsgServidor() + data class EstadoObtenido(val estado: EstadoRemoto) : MsgServidor() + data class ResultadosBusqueda(val resultados: List) : MsgServidor() + data class ReportesObtenidos(val lineas: List) : MsgServidor() + data class PlaylistCambiada(val tracks: List) : MsgServidor() + data class EstadoCambiado(val estado: EstadoRemoto) : MsgServidor() + data class IndiceActualizado(val ok: Boolean, val mensaje: String) : MsgServidor() + data class ColaObtenida(val tipo_cola: String, val items: List) : MsgServidor() + data class ProximasTandasObtenidas(val tandas: List) : MsgServidor() + object Ok : MsgServidor() + object Unknown : MsgServidor() +} diff --git a/app/src/main/java/com/gradio/client/network/ConnectionManager.kt b/app/src/main/java/com/gradio/client/network/ConnectionManager.kt new file mode 100644 index 0000000..b4f2496 --- /dev/null +++ b/app/src/main/java/com/gradio/client/network/ConnectionManager.kt @@ -0,0 +1,394 @@ +package com.gradio.client.network + +import com.google.gson.Gson +import com.google.gson.JsonObject +import com.google.gson.JsonParser +import com.gradio.client.data.* +import kotlinx.coroutines.* +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.StateFlow +import okhttp3.* +import java.io.BufferedReader +import java.io.InputStreamReader +import java.io.PrintWriter +import java.net.Socket +import java.util.concurrent.LinkedBlockingQueue + +private const val RELAY_URL = "wss://relay.gradio.net/ws" + +sealed class EstadoCon { + object Desconectado : EstadoCon() + object Conectando : EstadoCon() + data class Conectado(val version: String) : EstadoCon() + data class Error(val mensaje: String) : EstadoCon() +} + +class ConnectionManager { + + private val gson = Gson() + private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob()) + + private val _estadoCon = MutableStateFlow(EstadoCon.Desconectado) + val estadoCon: StateFlow = _estadoCon + + private val _mensajes = MutableSharedFlow(extraBufferCapacity = 100) + val mensajes: SharedFlow = _mensajes + + private val cola = LinkedBlockingQueue() + + @Volatile private var activa = false + private var jobConexion: Job? = null + + // Contador de generación — se incrementa en cada desconexión para invalidar + // callbacks de OkHttp que llegan tarde (onFailure tras ws.cancel()). + private val generacion = java.util.concurrent.atomic.AtomicInteger(0) + + // Socket activo — cerrado explícitamente al desconectar para interrumpir readLine() + @Volatile private var socketActivo: Socket? = null + // WebSocket activo — cancelado al desconectar + @Volatile private var wsActivo: WebSocket? = null + @Volatile private var okHttpClient: OkHttpClient? = null + + // ── Conectar LAN (TCP) ──────────────────────────────────────────────────── + + fun conectarTCP(servidor: String, puerto: Int, token: String) { + desconectar() + jobConexion = scope.launch { + _estadoCon.value = EstadoCon.Conectando + var delaySecs = 5L + while (isActive) { + var socket: Socket? = null + try { + socket = Socket(servidor, puerto) + socket.soTimeout = 60_000 // 60s read timeout para detectar desconexiones + socketActivo = socket + activa = true + + val writer = PrintWriter(socket.getOutputStream(), true) + val reader = BufferedReader(InputStreamReader(socket.getInputStream())) + + // Auth + writer.println(toJson(MsgCliente.Auth(token))) + + // Lanzar escritor en hilo separado + val writerJob = launch { + while (isActive) { + val json = cola.poll(100, java.util.concurrent.TimeUnit.MILLISECONDS) ?: continue + writer.println(json) + } + } + + var desconectado = false + try { + while (isActive) { + val linea = try { + reader.readLine() + } catch (e: java.net.SocketTimeoutException) { + // Timeout de lectura — enviar Ping para mantener viva la conexión + if (activa) writer.println(toJson(MsgCliente.Ping)) + continue + } + if (linea == null) break + if (linea.isBlank()) continue + procesarLinea(linea, token) + } + desconectado = true + } catch (e: Exception) { + if (isActive) desconectado = true + } finally { + writerJob.cancel() + activa = false + socketActivo = null + try { socket.close() } catch (_: Exception) {} + } + + if (!isActive) break + + if (desconectado) { + _estadoCon.value = EstadoCon.Desconectado + delay(delaySecs * 1000L) + if (!isActive) break + delaySecs = (delaySecs * 2).coerceAtMost(60) + _estadoCon.value = EstadoCon.Conectando + } else break + + } catch (e: CancellationException) { + break + } catch (e: Exception) { + activa = false + socketActivo = null + try { socket?.close() } catch (_: Exception) {} + if (!isActive) break + _estadoCon.value = EstadoCon.Error("$servidor:$puerto — ${e.message}") + delay(delaySecs * 1000L) + if (!isActive) break + delaySecs = (delaySecs * 2).coerceAtMost(60) + _estadoCon.value = EstadoCon.Conectando + } + } + activa = false + socketActivo = null + _estadoCon.value = EstadoCon.Desconectado + } + } + + // ── Conectar Relay (WebSocket) ──────────────────────────────────────────── + + fun conectarRelay(relayId: String, token: String) { + desconectar() + val gen = generacion.get() // generación de esta sesión; callbacks de sesiones anteriores la ignorarán + jobConexion = scope.launch { + _estadoCon.value = EstadoCon.Conectando + var delaySecs = 5L + + while (isActive) { + val client = OkHttpClient.Builder() + .readTimeout(0, java.util.concurrent.TimeUnit.MILLISECONDS) + .pingInterval(30, java.util.concurrent.TimeUnit.SECONDS) + .build() + okHttpClient = client + + val continuacion = CompletableDeferred() + + val request = Request.Builder().url(RELAY_URL).build() + val ws = client.newWebSocket(request, object : WebSocketListener() { + override fun onOpen(webSocket: WebSocket, response: Response) { + webSocket.send("""{"tipo":"connect","id":"$relayId"}""") + } + + override fun onMessage(webSocket: WebSocket, text: String) { + if (generacion.get() != gen) return + scope.launch { + val trimmed = text.trim() + if (trimmed.isBlank()) return@launch + val json = try { JsonParser.parseString(trimmed).asJsonObject } catch (_: Exception) { null } + val tipoLower = json?.get("tipo")?.asString?.lowercase() ?: "" + when (tipoLower) { + "connected" -> webSocket.send(toJson(MsgCliente.Auth(token))) + "error" -> { + val msg = json?.get("msg")?.asString ?: "ID no encontrado" + _estadoCon.value = EstadoCon.Error("ID $relayId: $msg") + delay(10_000L) + if (continuacion.isActive) continuacion.complete(true) + } + else -> procesarLinea(trimmed, token) + } + } + } + + override fun onClosed(webSocket: WebSocket, code: Int, reason: String) { + activa = false + if (generacion.get() != gen) { + if (continuacion.isActive) continuacion.complete(false) + return + } + if (continuacion.isActive) continuacion.complete(isActive) + } + + override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { + activa = false + // Si la generación cambió, esta sesión fue cancelada intencionalmente — ignorar + if (!isActive || generacion.get() != gen) { + if (continuacion.isActive) continuacion.complete(false) + return + } + scope.launch { + // Re-verificar generación: desconectar() pudo haberse llamado entre + // el chequeo de arriba y la ejecución de esta coroutine. + if (generacion.get() != gen) return@launch + _estadoCon.value = EstadoCon.Error("relay: ${t.message ?: "error de conexión"}") + if (continuacion.isActive) continuacion.complete(true) + } + } + }) + + wsActivo = ws + + val writerJob = launch { + while (isActive) { + val json = cola.poll(100, java.util.concurrent.TimeUnit.MILLISECONDS) ?: continue + ws.send(json) + } + } + + val reconectar = try { + continuacion.await() + } catch (_: CancellationException) { + false + } finally { + writerJob.cancel() + ws.cancel() + wsActivo = null + try { client.dispatcher.executorService.shutdown() } catch (_: Exception) {} + } + + if (!reconectar || !isActive) break + delay(delaySecs * 1000L) + if (!isActive) break + delaySecs = (delaySecs * 2).coerceAtMost(60) + _estadoCon.value = EstadoCon.Conectando + } + + activa = false + wsActivo = null + _estadoCon.value = EstadoCon.Desconectado + } + } + + // ── Desconectar — interrumpe inmediatamente ─────────────────────────────── + + fun desconectar() { + generacion.incrementAndGet() // invalida callbacks pendientes de OkHttp + activa = false + // Cerrar socket TCP → interrumpe readLine() bloqueante + try { socketActivo?.close() } catch (_: Exception) {} + socketActivo = null + // Cancelar WebSocket + try { wsActivo?.cancel() } catch (_: Exception) {} + wsActivo = null + // Cancelar coroutina + jobConexion?.cancel() + jobConexion = null + // Apagar OkHttp + try { okHttpClient?.dispatcher?.executorService?.shutdown() } catch (_: Exception) {} + okHttpClient = null + cola.clear() + _estadoCon.value = EstadoCon.Desconectado + } + + // ── Enviar comando ──────────────────────────────────────────────────────── + + fun enviar(msg: MsgCliente) { + if (activa) cola.offer(toJson(msg)) + } + + // ── Parseo JSON del servidor ────────────────────────────────────────────── + + private fun procesarLinea(linea: String, token: String) { + val obj = try { JsonParser.parseString(linea).asJsonObject } catch (_: Exception) { return } + val tipo = obj.get("tipo")?.asString ?: return + val msg = parsearMsgServidor(tipo, obj) ?: return + + if (msg is MsgServidor.AuthOk) { + activa = true + _estadoCon.value = EstadoCon.Conectado(msg.version) + enviar(MsgCliente.ObtenerEstado) + enviar(MsgCliente.ObtenerPlaylist) + enviar(MsgCliente.ObtenerBotonera) + } else { + scope.launch { _mensajes.emit(msg) } + } + } + + private fun parsearMsgServidor(tipo: String, obj: JsonObject): MsgServidor? = when (tipo) { + "AuthOk" -> MsgServidor.AuthOk(obj["version"]?.asString ?: "") + "Pong" -> MsgServidor.Pong + "Ok" -> MsgServidor.Ok + "Error" -> MsgServidor.Error(obj["mensaje"]?.asString ?: "") + "PlaylistObtenida" -> MsgServidor.PlaylistObtenida( + gson.fromJson(obj["tracks"], Array::class.java).toList()) + "PlaylistCambiada" -> MsgServidor.PlaylistCambiada( + gson.fromJson(obj["tracks"], Array::class.java).toList()) + "EstadoObtenido" -> MsgServidor.EstadoObtenido( + gson.fromJson(obj["estado"], EstadoRemoto::class.java)) + "EstadoCambiado" -> MsgServidor.EstadoCambiado( + gson.fromJson(obj["estado"], EstadoRemoto::class.java)) + "PautajeObtenido" -> MsgServidor.PautajeObtenido( + obj["tipo_p"]?.asString ?: "", obj["hora"]?.asInt ?: 0, obj["minuto"]?.asInt ?: 0, + gson.fromJson(obj["entradas"], Array::class.java).toList()) + "PautajeGuardado" -> MsgServidor.PautajeGuardado + "ParrillaObtenida" -> MsgServidor.ParrillaObtenida( + obj["dia"]?.asInt ?: 0, obj["hora"]?.asInt ?: 0, + gson.fromJson(obj["items"], Array::class.java).toList()) + "ParrillaGuardada" -> MsgServidor.ParrillaGuardada + "BotoneraObtenida" -> MsgServidor.BotoneraObtenida( + gson.fromJson(obj["botones"], Array::class.java).toList()) + "BotoneraGuardada" -> MsgServidor.BotoneraGuardada + "ResultadosBusqueda" -> MsgServidor.ResultadosBusqueda( + gson.fromJson(obj["resultados"], Array::class.java).toList()) + "ReportesObtenidos" -> MsgServidor.ReportesObtenidos( + gson.fromJson(obj["lineas"], Array::class.java).toList()) + "ColaObtenida" -> MsgServidor.ColaObtenida( + obj["tipo_cola"]?.asString ?: "", + gson.fromJson(obj["items"], Array::class.java).toList()) + "ProximasTandasObtenidas" -> MsgServidor.ProximasTandasObtenidas( + gson.fromJson(obj["tandas"], Array::class.java).toList()) + "IndiceActualizado" -> MsgServidor.IndiceActualizado( + obj["ok"]?.asBoolean ?: false, obj["mensaje"]?.asString ?: "") + "DirectorioListado" -> MsgServidor.DirectorioListado( + obj["ruta"]?.asString ?: "", + gson.fromJson(obj["entradas"], Array::class.java).toList()) + else -> MsgServidor.Unknown + } + + // ── Serializar MsgCliente a JSON ────────────────────────────────────────── + + private fun toJson(msg: MsgCliente): String { + val obj = JsonObject() + obj.addProperty("tipo", msg.tipo) + when (msg) { + is MsgCliente.Auth -> obj.addProperty("token", msg.token) + is MsgCliente.ListarDir -> obj.addProperty("ruta", msg.ruta) + is MsgCliente.ObtenerPautaje -> { + obj.addProperty("tipo_p", msg.tipo_p) + obj.addProperty("hora", msg.hora) + obj.addProperty("minuto", msg.minuto) + } + is MsgCliente.GuardarPautaje -> { + obj.addProperty("tipo_p", msg.tipo_p) + obj.addProperty("hora", msg.hora) + obj.addProperty("minuto", msg.minuto) + obj.add("entradas", gson.toJsonTree(msg.entradas)) + } + is MsgCliente.ObtenerParrilla -> { + obj.addProperty("dia", msg.dia) + obj.addProperty("hora", msg.hora) + } + is MsgCliente.GuardarParrilla -> { + obj.addProperty("dia", msg.dia) + obj.addProperty("hora", msg.hora) + obj.add("items", gson.toJsonTree(msg.items)) + } + is MsgCliente.GuardarBotonera -> obj.add("botones", gson.toJsonTree(msg.botones)) + is MsgCliente.ComandoPlayer -> obj.addProperty("cmd", msg.cmd) + is MsgCliente.SetVolumen -> obj.addProperty("upvol", msg.upvol) + is MsgCliente.ReproducirAhora -> obj.addProperty("ruta", msg.ruta) + is MsgCliente.PlaylistPlayAhora -> { + obj.addProperty("ruta", msg.ruta) + obj.addProperty("duracion", msg.duracion) + } + is MsgCliente.AgregarAlPlaylist -> { + obj.addProperty("ruta", msg.ruta) + obj.addProperty("duracion", msg.duracion) + obj.addProperty("al_inicio", msg.alInicio) + } + is MsgCliente.EliminarDePlaylist -> obj.addProperty("indice", msg.indice) + is MsgCliente.MoverEnPlaylist -> { + obj.addProperty("indice", msg.indice) + obj.addProperty("arriba", msg.arriba) + } + is MsgCliente.Buscar -> { + obj.addProperty("consulta", msg.consulta) + if (msg.ruta != null) obj.addProperty("ruta", msg.ruta) + } + is MsgCliente.ObtenerReportes -> { + obj.addProperty("tipo_r", msg.tipo_r) + obj.addProperty("fecha", msg.fecha) + } + is MsgCliente.ObtenerCola -> obj.addProperty("tipo_cola", msg.tipo_cola) + is MsgCliente.EliminarDeCola -> { + obj.addProperty("tipo_cola", msg.tipo_cola) + obj.addProperty("indice", msg.indice) + } + is MsgCliente.ReproducirTanda -> { + obj.addProperty("hora", msg.hora) + obj.addProperty("minuto", msg.minuto) + obj.add("items", gson.toJsonTree(msg.items)) + } + else -> {} + } + return obj.toString() + } +} diff --git a/app/src/main/java/com/gradio/client/ui/components/ConnectionBar.kt b/app/src/main/java/com/gradio/client/ui/components/ConnectionBar.kt new file mode 100644 index 0000000..898996b --- /dev/null +++ b/app/src/main/java/com/gradio/client/ui/components/ConnectionBar.kt @@ -0,0 +1,249 @@ +package com.gradio.client.ui.components + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.* +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.text.input.VisualTransformation +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.gradio.client.R +import com.gradio.client.network.EstadoCon +import com.gradio.client.ui.theme.* +import com.gradio.client.ui.viewmodel.Config + +@Composable +fun ConnectionBar( + estadoCon: EstadoCon, + config: Config, + onConectar: (Config) -> Unit, + onDesconectar: () -> Unit, + modifier: Modifier = Modifier +) { + var expanded by remember { mutableStateOf(false) } + var modoRelay by remember { mutableStateOf(config.modoRelay) } + var servidor by remember { mutableStateOf(config.servidor) } + var puerto by remember { mutableStateOf(config.puerto.toString()) } + var relayId by remember { mutableStateOf(config.relayId) } + var token by remember { mutableStateOf(config.token) } + var showPass by remember { mutableStateOf(false) } + + val conectado = estadoCon is EstadoCon.Conectado + val conectando = estadoCon is EstadoCon.Conectando + val enError = estadoCon is EstadoCon.Error + val ocupado = conectando || enError // reconectando o con error — mostrar Cancelar + + Column( + modifier = modifier + .fillMaxWidth() + .background(GradioCard) + ) { + // ── Barra de estado (siempre visible) ──────────────────────────────── + Row( + modifier = Modifier + .fillMaxWidth() + .then( + if (!conectado && !ocupado) + Modifier.clickable { expanded = !expanded } + else Modifier + ) + .padding(horizontal = 12.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + // Logo G Radio (PNG real) + Image( + painter = painterResource(id = R.drawable.gradio_logo), + contentDescription = "G Radio", + modifier = Modifier.size(28.dp) + ) + Spacer(Modifier.width(8.dp)) + + // Indicador de estado + val (estadoColor, estadoTexto) = when (estadoCon) { + is EstadoCon.Conectado -> Pair(GradioGreen, "● Conectado v${estadoCon.version}") + is EstadoCon.Conectando -> Pair(WarningColor, "⟳ Conectando…") + is EstadoCon.Error -> Pair(ErrorColor, "✗ ${estadoCon.mensaje}") + is EstadoCon.Desconectado -> Pair(OnSurfaceDim, "● Desconectado") + } + + Text( + text = estadoTexto, + color = estadoColor, + fontSize = 13.sp, + fontWeight = FontWeight.Medium, + modifier = Modifier.weight(1f), + maxLines = 1, + overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis + ) + + if (conectando) { + CircularProgressIndicator( + modifier = Modifier.size(16.dp), + strokeWidth = 2.dp, + color = WarningColor + ) + Spacer(Modifier.width(6.dp)) + } + + when { + // Conectado → botón Desconectar + conectado -> { + TextButton( + onClick = onDesconectar, + colors = ButtonDefaults.textButtonColors(contentColor = ErrorColor) + ) { Text("Desconectar", fontSize = 12.sp) } + } + // Reconectando o en error → botón Cancelar + ocupado -> { + TextButton( + onClick = { + onDesconectar() + expanded = false + }, + colors = ButtonDefaults.textButtonColors(contentColor = ErrorColor) + ) { Text("Cancelar", fontSize = 12.sp) } + } + // Desconectado → flecha para expandir config + else -> { + Icon( + imageVector = if (expanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore, + contentDescription = "Configuración", + tint = OnSurfaceDim, + modifier = Modifier.size(20.dp) + ) + } + } + } + + // ── Panel de configuración expandible (solo cuando desconectado) ────── + AnimatedVisibility(visible = expanded && !conectado && !ocupado) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 4.dp) + ) { + // Toggle LAN / Internet + Row(verticalAlignment = Alignment.CenterVertically) { + Text("LAN", fontSize = 13.sp, color = if (!modoRelay) GradioGreen else OnSurfaceDim) + Switch( + checked = modoRelay, + onCheckedChange = { modoRelay = it }, + modifier = Modifier.padding(horizontal = 8.dp), + colors = SwitchDefaults.colors( + checkedThumbColor = GradioGreen, + checkedTrackColor = GradioGreenDk + ) + ) + Text("Internet (relay)", fontSize = 13.sp, color = if (modoRelay) GradioGreen else OnSurfaceDim) + } + + Spacer(Modifier.height(6.dp)) + + if (!modoRelay) { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField( + value = servidor, + onValueChange = { servidor = it }, + label = { Text("Servidor", fontSize = 12.sp) }, + singleLine = true, + modifier = Modifier.weight(1f), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri), + colors = textFieldColors() + ) + OutlinedTextField( + value = puerto, + onValueChange = { puerto = it.filter { c -> c.isDigit() } }, + label = { Text("Puerto", fontSize = 12.sp) }, + singleLine = true, + modifier = Modifier.width(80.dp), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + colors = textFieldColors() + ) + } + } else { + OutlinedTextField( + value = relayId, + onValueChange = { if (it.length <= 8 && it.all { c -> c.isDigit() }) relayId = it }, + label = { Text("ID del servidor (8 dígitos)", fontSize = 12.sp) }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + colors = textFieldColors() + ) + } + + Spacer(Modifier.height(6.dp)) + + OutlinedTextField( + value = token, + onValueChange = { token = it }, + label = { Text("Token (vacío = sin auth)", fontSize = 12.sp) }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + visualTransformation = if (showPass) VisualTransformation.None else PasswordVisualTransformation(), + trailingIcon = { + IconButton(onClick = { showPass = !showPass }) { + Icon( + imageVector = if (showPass) Icons.Default.VisibilityOff else Icons.Default.Visibility, + contentDescription = null, + tint = OnSurfaceDim + ) + } + }, + colors = textFieldColors() + ) + + Spacer(Modifier.height(8.dp)) + + Button( + onClick = { + val cfg = Config( + servidor = servidor, + puerto = puerto.toIntOrNull() ?: 7777, + token = token, + modoRelay = modoRelay, + relayId = relayId + ) + onConectar(cfg) + expanded = false + }, + modifier = Modifier.fillMaxWidth(), + colors = ButtonDefaults.buttonColors( + containerColor = GradioGreen, + contentColor = MaterialTheme.colorScheme.background + ) + ) { + Icon(Icons.Default.Link, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(6.dp)) + Text("Conectar", fontWeight = FontWeight.Bold) + } + Spacer(Modifier.height(8.dp)) + } + } + + HorizontalDivider(color = GradioSurface, thickness = 1.dp) + } +} + +@Composable +private fun textFieldColors() = OutlinedTextFieldDefaults.colors( + focusedBorderColor = GradioGreen, + unfocusedBorderColor = OnSurfaceDim.copy(alpha = 0.5f), + focusedLabelColor = GradioGreen, + cursorColor = GradioGreen, + focusedTextColor = OnBg, + unfocusedTextColor = OnBg, + unfocusedLabelColor = OnSurfaceDim, +) diff --git a/app/src/main/java/com/gradio/client/ui/screens/BotoneraScreen.kt b/app/src/main/java/com/gradio/client/ui/screens/BotoneraScreen.kt new file mode 100644 index 0000000..dcd7452 --- /dev/null +++ b/app/src/main/java/com/gradio/client/ui/screens/BotoneraScreen.kt @@ -0,0 +1,122 @@ +package com.gradio.client.ui.screens + +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.grid.GridCells +import androidx.compose.foundation.lazy.grid.LazyVerticalGrid +import androidx.compose.foundation.lazy.grid.items +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.GridView +import androidx.compose.material.icons.filled.Refresh +import androidx.compose.material3.* +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.gradio.client.data.BotonRemoto +import com.gradio.client.network.EstadoCon +import com.gradio.client.ui.theme.* +import com.gradio.client.ui.viewmodel.MainViewModel + +@Composable +fun BotoneraScreen(vm: MainViewModel) { + val botones by vm.botones.collectAsState() + val estCon by vm.estadoCon.collectAsState() + val activo = estCon is EstadoCon.Conectado + + Column(modifier = Modifier.fillMaxSize()) { + // Header + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon(Icons.Default.GridView, null, tint = GradioGreen, modifier = Modifier.size(20.dp)) + Spacer(Modifier.width(8.dp)) + Text("Botonera", fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = OnBg, modifier = Modifier.weight(1f)) + if (activo) { + IconButton(onClick = { vm.recargarBotonera() }) { + Icon(Icons.Default.Refresh, "Recargar", tint = OnSurfaceDim, modifier = Modifier.size(20.dp)) + } + } + } + + HorizontalDivider(color = GradioCard) + + if (!activo) { + Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Text("Conectate para ver la botonera", color = OnSurfaceDim, fontSize = 14.sp) + } + return@Column + } + + if (botones.isEmpty()) { + Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Text("Sin botones configurados", color = OnSurfaceDim, fontSize = 14.sp) + } + return@Column + } + + LazyVerticalGrid( + columns = GridCells.Adaptive(minSize = 120.dp), + modifier = Modifier + .fillMaxSize() + .padding(8.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + items(botones, key = { it.indice }) { boton -> + BotoneraBtn(boton = boton, onClick = { vm.presionarBoton(boton) }) + } + } + } +} + +@Composable +private fun BotoneraBtn(boton: BotonRemoto, onClick: () -> Unit) { + val btnColor = parseColor(boton.color) + val textColor = if (isColorDark(btnColor)) Color.White else Color.Black + + Button( + onClick = onClick, + modifier = Modifier + .fillMaxWidth() + .height(72.dp), + colors = ButtonDefaults.buttonColors(containerColor = btnColor, contentColor = textColor), + shape = MaterialTheme.shapes.medium + ) { + Text( + text = boton.etiqueta.ifBlank { "Botón ${boton.indice + 1}" }, + fontSize = 13.sp, + fontWeight = FontWeight.SemiBold, + textAlign = TextAlign.Center, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + lineHeight = 16.sp + ) + } +} + +private fun parseColor(hex: String): Color { + return try { + val clean = hex.trimStart('#') + when (clean.length) { + 6 -> Color(android.graphics.Color.parseColor("#$clean")) + 8 -> Color(android.graphics.Color.parseColor("#$clean")) + else -> GradioGreen + } + } catch (_: Exception) { GradioGreen } +} + +private fun isColorDark(color: Color): Boolean { + val r = color.red; val g = color.green; val b = color.blue + val luminance = 0.299 * r + 0.587 * g + 0.114 * b + return luminance < 0.5 +} diff --git a/app/src/main/java/com/gradio/client/ui/screens/BuscadorScreen.kt b/app/src/main/java/com/gradio/client/ui/screens/BuscadorScreen.kt new file mode 100644 index 0000000..03d0fa6 --- /dev/null +++ b/app/src/main/java/com/gradio/client/ui/screens/BuscadorScreen.kt @@ -0,0 +1,167 @@ +package com.gradio.client.ui.screens + +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.* +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.gradio.client.data.ResultadoBusqueda +import com.gradio.client.network.EstadoCon +import com.gradio.client.ui.theme.* +import com.gradio.client.ui.viewmodel.MainViewModel + +@Composable +fun BuscadorScreen(vm: MainViewModel) { + val resultados by vm.resultadosBusqueda.collectAsState() + val buscando by vm.buscando.collectAsState() + val estCon by vm.estadoCon.collectAsState() + val activo = estCon is EstadoCon.Conectado + var consulta by remember { mutableStateOf("") } + + Column(modifier = Modifier.fillMaxSize()) { + // ── Barra de búsqueda ───────────────────────────────────────────────── + Row( + modifier = Modifier + .fillMaxWidth() + .padding(12.dp), + verticalAlignment = Alignment.CenterVertically + ) { + OutlinedTextField( + value = consulta, + onValueChange = { consulta = it }, + label = { Text("Buscar audio…", fontSize = 13.sp) }, + singleLine = true, + modifier = Modifier.weight(1f), + enabled = activo, + leadingIcon = { Icon(Icons.Default.Search, null, tint = OnSurfaceDim, modifier = Modifier.size(20.dp)) }, + trailingIcon = { + if (consulta.isNotEmpty()) { + IconButton(onClick = { consulta = "" }) { + Icon(Icons.Default.Clear, null, tint = OnSurfaceDim, modifier = Modifier.size(18.dp)) + } + } + }, + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), + keyboardActions = KeyboardActions(onSearch = { + if (consulta.isNotBlank() && activo) vm.buscar(consulta) + }), + colors = OutlinedTextFieldDefaults.colors( + focusedBorderColor = GradioGreen, + unfocusedBorderColor = OnSurfaceDim.copy(alpha = 0.5f), + focusedLabelColor = GradioGreen, + cursorColor = GradioGreen, + focusedTextColor = OnBg, + unfocusedTextColor = OnBg, + unfocusedLabelColor = OnSurfaceDim, + disabledBorderColor = OnSurfaceDim.copy(alpha = 0.2f), + disabledTextColor = OnSurfaceDim.copy(alpha = 0.4f), + disabledLabelColor = OnSurfaceDim.copy(alpha = 0.3f), + ) + ) + Spacer(Modifier.width(8.dp)) + Button( + onClick = { if (consulta.isNotBlank() && activo) vm.buscar(consulta) }, + enabled = activo && consulta.isNotBlank() && !buscando, + colors = ButtonDefaults.buttonColors(containerColor = GradioGreen, contentColor = MaterialTheme.colorScheme.background) + ) { + if (buscando) { + CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp, color = MaterialTheme.colorScheme.background) + } else { + Icon(Icons.Default.Search, null, modifier = Modifier.size(20.dp)) + } + } + } + + HorizontalDivider(color = GradioCard) + + // ── Resultados ──────────────────────────────────────────────────────── + if (buscando) { + Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + CircularProgressIndicator(color = GradioGreen) + Spacer(Modifier.height(12.dp)) + Text("Buscando…", color = OnSurfaceDim, fontSize = 14.sp) + } + } + } else if (resultados.isEmpty() && !buscando) { + Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Icon(Icons.Default.LibraryMusic, null, tint = OnSurfaceDim.copy(alpha = 0.4f), modifier = Modifier.size(48.dp)) + Spacer(Modifier.height(8.dp)) + Text( + text = if (!activo) "Conectate para buscar audio" else "Escribe para buscar", + color = OnSurfaceDim, + fontSize = 14.sp + ) + } + } + } else { + Text( + text = "${resultados.size} resultado(s)", + fontSize = 12.sp, + color = OnSurfaceDim, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp) + ) + LazyColumn(modifier = Modifier.fillMaxSize()) { + items(resultados, key = { it.ruta }) { res -> + BuscadorRow( + res, activo, + onAlInicio = { vm.agregarAlPlaylist(res.ruta, alInicio = true) }, + onAlFinal = { vm.agregarAlPlaylist(res.ruta, alInicio = false) } + ) + HorizontalDivider(color = GradioCard.copy(alpha = 0.6f), thickness = 0.5.dp) + } + } + } + } +} + +@Composable +private fun BuscadorRow( + res: ResultadoBusqueda, + activo: Boolean, + onAlInicio: () -> Unit, + onAlFinal: () -> Unit +) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon(Icons.Default.AudioFile, null, tint = OnSurfaceDim.copy(alpha = 0.6f), modifier = Modifier.size(20.dp)) + Spacer(Modifier.width(10.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = res.nombre, + fontSize = 14.sp, + color = OnBg, + fontWeight = FontWeight.Medium, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + if (res.duracion.isNotBlank()) { + Text(res.duracion, fontSize = 11.sp, color = OnSurfaceDim) + } + } + if (activo) { + IconButton(onClick = onAlInicio) { + Icon(Icons.Default.VerticalAlignTop, "Agregar al inicio", tint = GradioGreen, modifier = Modifier.size(22.dp)) + } + IconButton(onClick = onAlFinal) { + Icon(Icons.Default.VerticalAlignBottom, "Agregar al final", tint = GradioGreen, modifier = Modifier.size(22.dp)) + } + } + } +} diff --git a/app/src/main/java/com/gradio/client/ui/screens/ComerciosScreen.kt b/app/src/main/java/com/gradio/client/ui/screens/ComerciosScreen.kt new file mode 100644 index 0000000..09266e8 --- /dev/null +++ b/app/src/main/java/com/gradio/client/ui/screens/ComerciosScreen.kt @@ -0,0 +1,425 @@ +package com.gradio.client.ui.screens + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.* +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.gradio.client.data.TandaRemota +import com.gradio.client.network.EstadoCon +import com.gradio.client.ui.theme.* +import com.gradio.client.ui.viewmodel.MainViewModel +import java.io.File + +@Composable +fun ComerciosScreen(vm: MainViewModel) { + val estado by vm.estadoPlayer.collectAsState() + val estCon by vm.estadoCon.collectAsState() + val activo = estCon is EstadoCon.Conectado + + val colaComerciales by vm.colaComerciales.collectAsState() + val colaEventos by vm.colaEventos.collectAsState() + val colaEventosEspera by vm.colaEventosEspera.collectAsState() + val proximasTandas by vm.proximasTandas.collectAsState() + + // Cargar las tres colas al entrar a la pantalla + LaunchedEffect(activo) { + if (activo) vm.recargarColas() + } + + if (!activo) { + Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Text("Conectate para controlar comerciales y eventos", color = OnSurfaceDim, fontSize = 14.sp) + } + return + } + + LazyColumn( + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(12.dp), + verticalArrangement = Arrangement.spacedBy(10.dp) + ) { + item { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically + ) { + Text( + "Comerciales y Eventos", + fontSize = 15.sp, + fontWeight = FontWeight.SemiBold, + color = OnBg, + modifier = Modifier.weight(1f) + ) + IconButton(onClick = { vm.recargarColas() }) { + Icon(Icons.Default.Refresh, "Recargar", tint = OnSurfaceDim, modifier = Modifier.size(20.dp)) + } + } + } + + item { + ColaCard( + titulo = "Comerciales", + icon = Icons.Default.Campaign, + activo = estado.comerciales_activos, + items = colaComerciales, + tipoCola = "comerciales", + labelDetener = "Detener", + onDetener = { vm.stopGeneral() }, + onVaciar = { vm.vaciarComerciales() }, + onEliminar = { i -> vm.eliminarDeCola("comerciales", i) } + ) + } + + item { + Text( + "Próximas tandas", + fontSize = 13.sp, + fontWeight = FontWeight.SemiBold, + color = OnSurfaceDim, + modifier = Modifier.padding(top = 2.dp, start = 2.dp) + ) + } + + if (proximasTandas.isEmpty()) { + item { + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors(containerColor = GradioCard) + ) { + Text( + "No hay tandas próximas en el horario", + fontSize = 12.sp, + color = OnSurfaceDim.copy(alpha = 0.7f), + modifier = Modifier.padding(12.dp) + ) + } + } + } else { + itemsIndexed(proximasTandas, key = { _, t -> "${t.hora}:${t.minuto}" }) { idx, tanda -> + TandaCard( + tanda = tanda, + colorIdx = idx, + onReproducir = { vm.reproducirTanda(tanda) } + ) + } + } + + item { + ColaCard( + titulo = "Eventos", + icon = Icons.Default.Event, + activo = estado.eventos_activos, + items = colaEventos, + tipoCola = "eventos", + labelDetener = "Detener", + onDetener = { vm.stopGeneral() }, + onVaciar = { vm.vaciarEventos() }, + onEliminar = { i -> vm.eliminarDeCola("eventos", i) } + ) + } + + item { + ColaCard( + titulo = "Eventos en espera", + icon = Icons.Default.HourglassBottom, + activo = false, + items = colaEventosEspera, + tipoCola = "eventos_espera", + labelDetener = null, + onDetener = {}, + onVaciar = { vm.vaciarEventosEspera() }, + onEliminar = { i -> vm.eliminarDeCola("eventos_espera", i) } + ) + } + } +} + +@Composable +private fun ColaCard( + titulo: String, + icon: ImageVector, + activo: Boolean, + items: List, + tipoCola: String, + labelDetener: String?, + onDetener: () -> Unit, + onVaciar: () -> Unit, + onEliminar: (Int) -> Unit, +) { + var confirmarVaciar by remember { mutableStateOf(false) } + var confirmarDetener by remember { mutableStateOf(false) } + + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors(containerColor = GradioCard) + ) { + Column(modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp)) { + + // ── Header ──────────────────────────────────────────────────────── + Row(verticalAlignment = Alignment.CenterVertically) { + Icon( + icon, null, + tint = if (activo) GradioGreen else OnSurfaceDim, + modifier = Modifier.size(20.dp) + ) + Spacer(Modifier.width(8.dp)) + Text( + titulo, + fontSize = 14.sp, + fontWeight = FontWeight.SemiBold, + color = OnBg, + modifier = Modifier.weight(1f) + ) + EstadoBadge(activo, items.size) + } + + // ── Botones de acción ───────────────────────────────────────────── + if (labelDetener != null || items.isNotEmpty()) { + Spacer(Modifier.height(8.dp)) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + if (labelDetener != null) { + OutlinedButton( + onClick = { confirmarDetener = true }, + modifier = Modifier.weight(1f), + enabled = activo, + colors = ButtonDefaults.outlinedButtonColors(contentColor = WarningColor), + border = androidx.compose.foundation.BorderStroke(1.dp, WarningColor.copy(alpha = 0.5f)), + contentPadding = PaddingValues(horizontal = 8.dp, vertical = 6.dp) + ) { + Icon(Icons.Default.Stop, null, modifier = Modifier.size(14.dp)) + Spacer(Modifier.width(4.dp)) + Text(labelDetener, fontSize = 12.sp) + } + } + if (items.isNotEmpty()) { + Button( + onClick = { confirmarVaciar = true }, + modifier = if (labelDetener != null) Modifier.weight(1f) else Modifier.fillMaxWidth(), + colors = ButtonDefaults.buttonColors(containerColor = ErrorColor.copy(alpha = 0.85f)), + contentPadding = PaddingValues(horizontal = 8.dp, vertical = 6.dp) + ) { + Icon(Icons.Default.ClearAll, null, modifier = Modifier.size(14.dp)) + Spacer(Modifier.width(4.dp)) + Text("Vaciar todo", fontSize = 12.sp) + } + } + } + } + + // ── Lista de ítems ──────────────────────────────────────────────── + if (items.isEmpty()) { + Spacer(Modifier.height(6.dp)) + Text( + "Cola vacía", + fontSize = 12.sp, + color = OnSurfaceDim.copy(alpha = 0.6f), + modifier = Modifier.padding(start = 4.dp) + ) + } else { + Spacer(Modifier.height(6.dp)) + HorizontalDivider(color = GradioSurface, thickness = 0.5.dp) + items.forEachIndexed { idx, ruta -> + ColaItem( + indice = idx, + ruta = ruta, + esActivo = activo && idx == 0, + onEliminar = { onEliminar(idx) } + ) + if (idx < items.lastIndex) { + HorizontalDivider( + color = GradioSurface.copy(alpha = 0.6f), + thickness = 0.5.dp, + modifier = Modifier.padding(start = 32.dp) + ) + } + } + } + } + } + + // ── Diálogos de confirmación ────────────────────────────────────────────── + if (confirmarDetener) { + AlertDialog( + onDismissRequest = { confirmarDetener = false }, + title = { Text("Detener $titulo", color = WarningColor) }, + text = { Text("Detiene el $titulo actualmente en reproducción.") }, + confirmButton = { + TextButton(onClick = { onDetener(); confirmarDetener = false }) { + Text("Confirmar", color = WarningColor) + } + }, + dismissButton = { + TextButton(onClick = { confirmarDetener = false }) { Text("Cancelar") } + }, + containerColor = GradioSurface + ) + } + + if (confirmarVaciar) { + AlertDialog( + onDismissRequest = { confirmarVaciar = false }, + title = { Text("Vaciar $titulo", color = ErrorColor) }, + text = { Text("Elimina todos los ítems de la cola de $titulo. Esta acción no se puede deshacer.") }, + confirmButton = { + TextButton(onClick = { onVaciar(); confirmarVaciar = false }) { + Text("Vaciar", color = ErrorColor) + } + }, + dismissButton = { + TextButton(onClick = { confirmarVaciar = false }) { Text("Cancelar") } + }, + containerColor = GradioSurface + ) + } +} + +// Colores de fondo alternados para las tarjetas de tanda — igual criterio que +// las 4 clases tanda-bg-0..3 del panel "Próximas tandas" del vivo (azul, verde, ámbar, rosa). +private val TandaColores = listOf( + Color(0xFF1E3A5F), // azul + Color(0xFF1F4D33), // verde + Color(0xFF5C4A1E), // ámbar + Color(0xFF5C2140), // rosa +) + +private fun formatDuracionTanda(totalSecs: Double): String { + val total = totalSecs.toInt().coerceAtLeast(0) + val h = total / 3600 + val m = (total % 3600) / 60 + val s = total % 60 + return if (h > 0) "%d:%02d:%02d".format(h, m, s) else "%d:%02d".format(m, s) +} + +@Composable +private fun TandaCard( + tanda: TandaRemota, + colorIdx: Int, + onReproducir: () -> Unit, +) { + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors(containerColor = TandaColores[colorIdx % TandaColores.size]) + ) { + Column(modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + "%02d:%02d".format(tanda.hora, tanda.minuto), + fontSize = 14.sp, + fontWeight = FontWeight.Bold, + color = OnBg + ) + Spacer(Modifier.weight(1f)) + Text( + formatDuracionTanda(tanda.duracion_total_secs), + fontSize = 12.sp, + color = OnBg.copy(alpha = 0.7f) + ) + Spacer(Modifier.width(4.dp)) + IconButton(onClick = onReproducir, modifier = Modifier.size(30.dp)) { + Icon(Icons.Default.PlayArrow, "Reproducir tanda", tint = OnBg, modifier = Modifier.size(20.dp)) + } + } + HorizontalDivider(color = OnBg.copy(alpha = 0.15f), thickness = 0.5.dp) + Spacer(Modifier.height(4.dp)) + tanda.items.forEachIndexed { i, item -> + val nombre = item.nombre.ifBlank { File(item.ruta).nameWithoutExtension.ifBlank { item.ruta } } + Text( + "${i + 1}. $nombre", + fontSize = 12.sp, + color = OnBg.copy(alpha = 0.9f), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(vertical = 1.dp) + ) + } + } + } +} + +@Composable +private fun ColaItem( + indice: Int, + ruta: String, + esActivo: Boolean, + onEliminar: () -> Unit, +) { + val nombre = File(ruta).nameWithoutExtension.ifBlank { ruta } + val bgColor = if (esActivo) GradioGreen.copy(alpha = 0.08f) else androidx.compose.ui.graphics.Color.Transparent + + Row( + modifier = Modifier + .fillMaxWidth() + .background(bgColor) + .padding(vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = if (esActivo) "▶" else "${indice + 1}", + fontSize = 11.sp, + color = if (esActivo) GradioGreen else OnSurfaceDim, + modifier = Modifier.width(28.dp), + fontWeight = if (esActivo) FontWeight.Bold else FontWeight.Normal + ) + Text( + text = nombre, + fontSize = 13.sp, + color = if (esActivo) GradioGreen else OnBg, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + fontWeight = if (esActivo) FontWeight.SemiBold else FontWeight.Normal + ) + IconButton( + onClick = onEliminar, + modifier = Modifier.size(32.dp) + ) { + Icon( + Icons.Default.Close, "Eliminar", + tint = ErrorColor.copy(alpha = 0.8f), + modifier = Modifier.size(16.dp) + ) + } + } +} + +@Composable +private fun EstadoBadge(activo: Boolean, cantidad: Int) { + val bgColor = when { + activo -> GradioGreen.copy(alpha = 0.15f) + cantidad > 0 -> WarningColor.copy(alpha = 0.12f) + else -> GradioCard + } + val textColor = when { + activo -> GradioGreen + cantidad > 0 -> WarningColor + else -> OnSurfaceDim + } + val label = when { + activo -> "● Activo" + cantidad > 0 -> "$cantidad en cola" + else -> "Vacía" + } + + Box( + modifier = Modifier + .background(bgColor, shape = MaterialTheme.shapes.small) + .padding(horizontal = 8.dp, vertical = 3.dp) + ) { + Text(label, fontSize = 11.sp, color = textColor, fontWeight = FontWeight.Medium) + } +} diff --git a/app/src/main/java/com/gradio/client/ui/screens/ParrillaScreen.kt b/app/src/main/java/com/gradio/client/ui/screens/ParrillaScreen.kt new file mode 100644 index 0000000..07dc0e3 --- /dev/null +++ b/app/src/main/java/com/gradio/client/ui/screens/ParrillaScreen.kt @@ -0,0 +1,188 @@ +package com.gradio.client.ui.screens + +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.* +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.gradio.client.network.EstadoCon +import com.gradio.client.ui.theme.* +import com.gradio.client.ui.viewmodel.MainViewModel + +private val DIAS = listOf("Lun", "Mar", "Mié", "Jue", "Vie", "Sáb", "Dom") + +@Composable +fun ParrillaScreen(vm: MainViewModel) { + val items by vm.parrillaItems.collectAsState() + val dia by vm.parrillaDia.collectAsState() + val hora by vm.parrillaHora.collectAsState() + val estCon by vm.estadoCon.collectAsState() + val activo = estCon is EstadoCon.Conectado + + var editItems by remember(items) { mutableStateOf(items.toMutableList()) } + var modoEdicion by remember { mutableStateOf(false) } + + Column(modifier = Modifier.fillMaxSize()) { + // ── Selector dia / hora ─────────────────────────────────────────────── + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 8.dp) + ) { + Text("Día", fontSize = 12.sp, color = OnSurfaceDim) + Spacer(Modifier.height(4.dp)) + ScrollableTabRow( + selectedTabIndex = dia - 1, + containerColor = GradioCard, + contentColor = GradioGreen, + edgePadding = 0.dp + ) { + DIAS.forEachIndexed { i, nombre -> + Tab( + selected = dia - 1 == i, + onClick = { + val nuevoDia = i + 1 + vm.cargarParrilla(nuevoDia, hora) + }, + text = { Text(nombre, fontSize = 13.sp) }, + selectedContentColor = GradioGreen, + unselectedContentColor = OnSurfaceDim + ) + } + } + Spacer(Modifier.height(8.dp)) + + // Selector hora + Row(verticalAlignment = Alignment.CenterVertically) { + Text("Hora: ", fontSize = 13.sp, color = OnSurfaceDim) + IconButton( + onClick = { vm.cargarParrilla(dia, (hora - 1 + 24) % 24) }, + enabled = activo, modifier = Modifier.size(32.dp) + ) { + Icon(Icons.Default.ChevronLeft, null, tint = OnBg, modifier = Modifier.size(20.dp)) + } + Text( + text = "%02d:00".format(hora), + fontSize = 16.sp, + fontWeight = FontWeight.Bold, + color = GradioGreen, + modifier = Modifier.width(56.dp), + textAlign = androidx.compose.ui.text.style.TextAlign.Center + ) + IconButton( + onClick = { vm.cargarParrilla(dia, (hora + 1) % 24) }, + enabled = activo, modifier = Modifier.size(32.dp) + ) { + Icon(Icons.Default.ChevronRight, null, tint = OnBg, modifier = Modifier.size(20.dp)) + } + Spacer(Modifier.weight(1f)) + if (activo && items.isNotEmpty()) { + TextButton(onClick = { + if (modoEdicion) { + vm.guardarParrilla(editItems) + modoEdicion = false + } else { + editItems = items.toMutableList() + modoEdicion = true + } + }) { + Text( + if (modoEdicion) "Guardar" else "Editar", + color = if (modoEdicion) GradioGreen else OnSurfaceDim, + fontSize = 13.sp + ) + } + if (modoEdicion) { + TextButton(onClick = { modoEdicion = false; editItems = items.toMutableList() }) { + Text("Cancelar", color = ErrorColor, fontSize = 13.sp) + } + } + } + } + } + + HorizontalDivider(color = GradioCard) + + if (!activo) { + Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Text("Conectate para ver la parrilla", color = OnSurfaceDim, fontSize = 14.sp) + } + return@Column + } + + if (items.isEmpty()) { + Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Icon(Icons.Default.MusicNote, null, tint = OnSurfaceDim.copy(alpha = 0.4f), modifier = Modifier.size(40.dp)) + Spacer(Modifier.height(8.dp)) + Text("Sin elementos en esta hora", color = OnSurfaceDim, fontSize = 14.sp) + } + } + return@Column + } + + val listaActual = if (modoEdicion) editItems else items + + LazyColumn(modifier = Modifier.fillMaxSize()) { + itemsIndexed(listaActual) { index, ruta -> + val esCarpeta = ruta.endsWith("/*") + val etiqueta = if (esCarpeta) + ruta.dropLast(2) // mostrar la ruta sin el "/*" final + else + ruta.substringAfterLast('/').substringBeforeLast('.') + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Text("${index + 1}", fontSize = 13.sp, color = OnSurfaceDim, modifier = Modifier.width(28.dp)) + Icon( + if (esCarpeta) Icons.Default.Folder else Icons.Default.AudioFile, + null, + tint = if (esCarpeta) GradioGreen.copy(alpha = 0.7f) else OnSurfaceDim.copy(alpha = 0.6f), + modifier = Modifier.size(18.dp) + ) + Spacer(Modifier.width(8.dp)) + Text( + etiqueta, + fontSize = 14.sp, + color = OnBg, + modifier = Modifier.weight(1f), + maxLines = 1, + overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis + ) + if (modoEdicion) { + IconButton(onClick = { + editItems = editItems.toMutableList().also { + if (index > 0) { val tmp = it[index]; it[index] = it[index-1]; it[index-1] = tmp } + } + }, modifier = Modifier.size(32.dp), enabled = index > 0) { + Icon(Icons.Default.KeyboardArrowUp, null, tint = OnSurfaceDim, modifier = Modifier.size(18.dp)) + } + IconButton(onClick = { + editItems = editItems.toMutableList().also { + if (index < it.size - 1) { val tmp = it[index]; it[index] = it[index+1]; it[index+1] = tmp } + } + }, modifier = Modifier.size(32.dp), enabled = index < editItems.size - 1) { + Icon(Icons.Default.KeyboardArrowDown, null, tint = OnSurfaceDim, modifier = Modifier.size(18.dp)) + } + IconButton(onClick = { + editItems = editItems.toMutableList().also { it.removeAt(index) } + }, modifier = Modifier.size(32.dp)) { + Icon(Icons.Default.Close, null, tint = ErrorColor, modifier = Modifier.size(18.dp)) + } + } + } + HorizontalDivider(color = GradioCard.copy(alpha = 0.6f), thickness = 0.5.dp) + } + } + } +} diff --git a/app/src/main/java/com/gradio/client/ui/screens/PautajeScreen.kt b/app/src/main/java/com/gradio/client/ui/screens/PautajeScreen.kt new file mode 100644 index 0000000..2ff41ed --- /dev/null +++ b/app/src/main/java/com/gradio/client/ui/screens/PautajeScreen.kt @@ -0,0 +1,176 @@ +package com.gradio.client.ui.screens + +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.* +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.gradio.client.data.EntradaRemota +import com.gradio.client.network.EstadoCon +import com.gradio.client.ui.theme.* +import com.gradio.client.ui.viewmodel.MainViewModel + +@Composable +fun PautajeScreen(vm: MainViewModel) { + val entradas by vm.pautajeEntradas.collectAsState() + val tipo by vm.pautajeTipo.collectAsState() + val hora by vm.pautajeHora.collectAsState() + val minuto by vm.pautajeMinuto.collectAsState() + val estCon by vm.estadoCon.collectAsState() + val activo = estCon is EstadoCon.Conectado + + var tipoSel by remember { mutableStateOf(tipo) } + var horaSel by remember { mutableStateOf(hora) } + var minutoSel by remember { mutableStateOf(minuto) } + var editEntradas by remember(entradas) { mutableStateOf(entradas.toMutableList()) } + var modoEdicion by remember { mutableStateOf(false) } + + Column(modifier = Modifier.fillMaxSize()) { + // ── Controles de selección ──────────────────────────────────────────── + Column(modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp)) { + // Tipo + Row(verticalAlignment = Alignment.CenterVertically) { + Text("Tipo: ", fontSize = 13.sp, color = OnSurfaceDim) + FilterChip( + selected = tipoSel == "comerciales", + onClick = { tipoSel = "comerciales" }, + label = { Text("Comerciales", fontSize = 12.sp) }, + modifier = Modifier.padding(end = 6.dp), + colors = FilterChipDefaults.filterChipColors( + selectedContainerColor = GradioGreen, + selectedLabelColor = MaterialTheme.colorScheme.background + ) + ) + FilterChip( + selected = tipoSel == "eventos", + onClick = { tipoSel = "eventos" }, + label = { Text("Eventos", fontSize = 12.sp) }, + colors = FilterChipDefaults.filterChipColors( + selectedContainerColor = GradioGreen, + selectedLabelColor = MaterialTheme.colorScheme.background + ) + ) + } + Spacer(Modifier.height(6.dp)) + + // Hora y minuto + Row(verticalAlignment = Alignment.CenterVertically) { + Text("Hora:", fontSize = 13.sp, color = OnSurfaceDim) + IconButton(onClick = { horaSel = (horaSel - 1 + 24) % 24 }, modifier = Modifier.size(32.dp)) { + Icon(Icons.Default.ChevronLeft, null, tint = OnBg, modifier = Modifier.size(18.dp)) + } + Text("%02d".format(horaSel), fontSize = 16.sp, fontWeight = FontWeight.Bold, color = GradioGreen, modifier = Modifier.width(36.dp), + textAlign = androidx.compose.ui.text.style.TextAlign.Center) + IconButton(onClick = { horaSel = (horaSel + 1) % 24 }, modifier = Modifier.size(32.dp)) { + Icon(Icons.Default.ChevronRight, null, tint = OnBg, modifier = Modifier.size(18.dp)) + } + Spacer(Modifier.width(12.dp)) + Text("Min:", fontSize = 13.sp, color = OnSurfaceDim) + IconButton(onClick = { minutoSel = (minutoSel - 1 + 60) % 60 }, modifier = Modifier.size(32.dp)) { + Icon(Icons.Default.ChevronLeft, null, tint = OnBg, modifier = Modifier.size(18.dp)) + } + Text("%02d".format(minutoSel), fontSize = 16.sp, fontWeight = FontWeight.Bold, color = GradioGreen, modifier = Modifier.width(36.dp), + textAlign = androidx.compose.ui.text.style.TextAlign.Center) + IconButton(onClick = { minutoSel = (minutoSel + 1) % 60 }, modifier = Modifier.size(32.dp)) { + Icon(Icons.Default.ChevronRight, null, tint = OnBg, modifier = Modifier.size(18.dp)) + } + Spacer(Modifier.weight(1f)) + if (activo) { + Button( + onClick = { vm.cargarPautaje(tipoSel, horaSel, minutoSel); modoEdicion = false }, + modifier = Modifier.height(36.dp), + colors = ButtonDefaults.buttonColors(containerColor = GradioGreenDk) + ) { Text("Ver", fontSize = 12.sp) } + } + } + + if (activo && entradas.isNotEmpty()) { + Row { + TextButton(onClick = { + if (modoEdicion) { vm.guardarPautaje(editEntradas); modoEdicion = false } + else { editEntradas = entradas.toMutableList(); modoEdicion = true } + }) { + Text(if (modoEdicion) "Guardar" else "Editar", color = if (modoEdicion) GradioGreen else OnSurfaceDim, fontSize = 13.sp) + } + if (modoEdicion) { + TextButton(onClick = { modoEdicion = false }) { + Text("Cancelar", color = ErrorColor, fontSize = 13.sp) + } + } + } + } + } + + HorizontalDivider(color = GradioCard) + + if (!activo) { + Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Text("Conectate para ver pautaje", color = OnSurfaceDim, fontSize = 14.sp) + } + return@Column + } + + val listaActual = if (modoEdicion) editEntradas else entradas + + if (listaActual.isEmpty()) { + Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Text("Sin entradas para esta hora", color = OnSurfaceDim, fontSize = 14.sp) + } + return@Column + } + + LazyColumn(modifier = Modifier.fillMaxSize()) { + itemsIndexed(listaActual) { index, entrada -> + PautajeRow(entrada, index, modoEdicion, + onEliminar = { editEntradas = editEntradas.toMutableList().also { it.removeAt(index) } } + ) + HorizontalDivider(color = GradioCard.copy(alpha = 0.6f), thickness = 0.5.dp) + } + } + } +} + +@Composable +private fun PautajeRow( + entrada: EntradaRemota, + index: Int, + modoEdicion: Boolean, + onEliminar: () -> Unit +) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Text("${index + 1}", fontSize = 12.sp, color = OnSurfaceDim, modifier = Modifier.width(24.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + entrada.ruta.substringAfterLast('/').substringBeforeLast('.'), + fontSize = 13.sp, color = OnBg, maxLines = 1, + overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis + ) + Text( + "Días: ${formatDias(entrada.dias)} | ${entrada.inicio} → ${entrada.fin}", + fontSize = 11.sp, color = OnSurfaceDim + ) + } + if (modoEdicion) { + IconButton(onClick = onEliminar, modifier = Modifier.size(32.dp)) { + Icon(Icons.Default.Close, null, tint = ErrorColor, modifier = Modifier.size(18.dp)) + } + } + } +} + +private fun formatDias(dias: String): String { + val nombres = listOf("L", "M", "X", "J", "V", "S", "D") + return dias.mapIndexed { i, c -> if (c != '0' && i < nombres.size) nombres[i] else "" }.filter { it.isNotEmpty() }.joinToString("") +} diff --git a/app/src/main/java/com/gradio/client/ui/screens/PlayerScreen.kt b/app/src/main/java/com/gradio/client/ui/screens/PlayerScreen.kt new file mode 100644 index 0000000..fd231f3 --- /dev/null +++ b/app/src/main/java/com/gradio/client/ui/screens/PlayerScreen.kt @@ -0,0 +1,293 @@ +package com.gradio.client.ui.screens + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.* +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.gradio.client.data.EstadoRemoto +import com.gradio.client.data.TrackRemoto +import com.gradio.client.network.EstadoCon +import com.gradio.client.ui.theme.* +import com.gradio.client.ui.viewmodel.MainViewModel +import java.io.File + +@Composable +fun PlayerScreen(vm: MainViewModel) { + val estado by vm.estadoPlayer.collectAsState() + val playlist by vm.playlist.collectAsState() + val estCon by vm.estadoCon.collectAsState() + val activo = estCon is EstadoCon.Conectado + + Column(modifier = Modifier.fillMaxSize()) { + // ── Info del track actual ───────────────────────────────────────────── + TrackHeader(estado) + + // ── Barra de progreso ───────────────────────────────────────────────── + val progress = if (estado.duracion_secs > 0) (estado.posicion_secs / estado.duracion_secs).toFloat() else 0f + LinearProgressIndicator( + progress = { progress }, + modifier = Modifier + .fillMaxWidth() + .height(4.dp), + color = GradioGreen, + trackColor = GradioCard + ) + + // ── Controles de transporte ─────────────────────────────────────────── + TransportControls(vm, activo) + + // ── Control de volumen ──────────────────────────────────────────────── + VolumeControl(vm, estado, activo) + + HorizontalDivider(color = GradioCard) + + // ── Stop general ────────────────────────────────────────────────────── + StopGeneralBar(vm, activo) + + HorizontalDivider(color = GradioCard) + + // ── Playlist ────────────────────────────────────────────────────────── + Text( + text = "Playlist (${playlist.size})", + fontSize = 12.sp, + color = OnSurfaceDim, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp) + ) + + LazyColumn(modifier = Modifier.fillMaxSize()) { + itemsIndexed(playlist, key = { i, t -> "$i-${t.ruta}" }) { index, track -> + PlaylistRow( + index = index, + track = track, + esActual = index == estado.indice_actual && activo, + activo = activo, + onPlay = { vm.playlistPlayAhora(track.ruta, track.duracion) }, + onSubir = { vm.moverEnPlaylist(index, true) }, + onBajar = { vm.moverEnPlaylist(index, false) }, + onEliminar = { vm.eliminarDePlaylist(index) } + ) + HorizontalDivider(color = GradioCard.copy(alpha = 0.6f), thickness = 0.5.dp) + } + } + } +} + +@Composable +private fun StopGeneralBar(vm: MainViewModel, activo: Boolean) { + var confirmar by remember { mutableStateOf(false) } + + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon(Icons.Default.Warning, null, tint = ErrorColor, modifier = Modifier.size(16.dp)) + Spacer(Modifier.width(6.dp)) + Text("Stop General", fontSize = 12.sp, color = ErrorColor, modifier = Modifier.weight(1f)) + Button( + onClick = { confirmar = true }, + enabled = activo, + colors = ButtonDefaults.buttonColors(containerColor = ErrorColor), + contentPadding = PaddingValues(horizontal = 14.dp, vertical = 6.dp), + modifier = Modifier.height(34.dp) + ) { + Icon(Icons.Default.StopCircle, null, modifier = Modifier.size(16.dp)) + Spacer(Modifier.width(4.dp)) + Text("Detener todo", fontSize = 12.sp) + } + } + + if (confirmar) { + AlertDialog( + onDismissRequest = { confirmar = false }, + title = { Text("Stop General", color = ErrorColor) }, + text = { Text("Detiene toda reproducción activa: parrilla, comerciales y eventos.") }, + confirmButton = { + TextButton(onClick = { vm.stopGeneral(); confirmar = false }) { + Text("Confirmar", color = ErrorColor) + } + }, + dismissButton = { + TextButton(onClick = { confirmar = false }) { Text("Cancelar") } + }, + containerColor = GradioSurface + ) + } +} + +@Composable +private fun TrackHeader(estado: EstadoRemoto) { + val titulo = estado.titulo_actual.ifBlank { + estado.track_actual.let { File(it).nameWithoutExtension }.ifBlank { "— Sin reproducción —" } + } + val posStr = fmtTiempo(estado.posicion_secs) + val durStr = fmtTiempo(estado.duracion_secs) + + Column(modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp)) { + Text( + text = titulo, + fontSize = 16.sp, + fontWeight = FontWeight.SemiBold, + color = OnBg, + maxLines = 2, + overflow = TextOverflow.Ellipsis + ) + Spacer(Modifier.height(2.dp)) + Row { + val estadoStr = when { + estado.reproduciendo -> "▶ Reproduciendo" + estado.pausado -> "⏸ Pausado" + else -> "⏹ Detenido" + } + Text(estadoStr, fontSize = 12.sp, color = if (estado.reproduciendo) GradioGreen else OnSurfaceDim) + Spacer(Modifier.weight(1f)) + Text("$posStr / $durStr", fontSize = 12.sp, color = OnSurfaceDim) + } + } +} + +@Composable +private fun TransportControls(vm: MainViewModel, activo: Boolean) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 8.dp, vertical = 4.dp), + horizontalArrangement = Arrangement.SpaceEvenly, + verticalAlignment = Alignment.CenterVertically + ) { + TransportBtn(Icons.Default.PlayArrow, "Play", activo, GradioGreen) { vm.play() } + TransportBtn(Icons.Default.Pause, "Pausa", activo) { vm.pause() } + TransportBtn(Icons.Default.Stop, "Stop", activo) { vm.stop() } + TransportBtn(Icons.Default.SkipNext, "Skip", activo) { vm.siguiente() } + TransportBtn(Icons.Default.StopCircle, "Stop-After", activo) { vm.stopAfter() } + } +} + +@Composable +private fun TransportBtn( + icon: androidx.compose.ui.graphics.vector.ImageVector, + label: String, + activo: Boolean, + color: androidx.compose.ui.graphics.Color = OnBg, + onClick: () -> Unit +) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + IconButton(onClick = onClick, enabled = activo) { + Icon(icon, contentDescription = label, tint = if (activo) color else OnSurfaceDim, modifier = Modifier.size(28.dp)) + } + Text(label, fontSize = 10.sp, color = if (activo) OnSurfaceDim else OnSurfaceDim.copy(alpha = 0.4f)) + } +} + +@Composable +private fun VolumeControl(vm: MainViewModel, estado: EstadoRemoto, activo: Boolean) { + var vol by remember(estado.upvol) { mutableFloatStateOf(estado.upvol.toFloat()) } + var isDragging by remember { mutableStateOf(false) } + + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon(Icons.Default.VolumeDown, null, tint = OnSurfaceDim, modifier = Modifier.size(18.dp)) + Slider( + value = if (isDragging) vol else estado.upvol.toFloat(), + onValueChange = { vol = it; isDragging = true }, + onValueChangeFinished = { + isDragging = false + vm.setVol(vol.toInt()) + }, + valueRange = 0f..100f, + enabled = activo, + modifier = Modifier.weight(1f).padding(horizontal = 8.dp), + colors = SliderDefaults.colors(thumbColor = GradioGreen, activeTrackColor = GradioGreen) + ) + Icon(Icons.Default.VolumeUp, null, tint = OnSurfaceDim, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(6.dp)) + Text("${if (isDragging) vol.toInt() else estado.upvol}%", fontSize = 13.sp, color = OnSurfaceDim, modifier = Modifier.width(36.dp)) + } +} + +@Composable +private fun PlaylistRow( + index: Int, + track: TrackRemoto, + esActual: Boolean, + activo: Boolean, + onPlay: () -> Unit, + onSubir: () -> Unit, + onBajar: () -> Unit, + onEliminar: () -> Unit +) { + val titulo = track.titulo.ifBlank { File(track.ruta).nameWithoutExtension } + val bgColor = if (esActual) GradioGreen.copy(alpha = 0.12f) else androidx.compose.ui.graphics.Color.Transparent + + Row( + modifier = Modifier + .fillMaxWidth() + .background(bgColor) + .padding(horizontal = 8.dp, vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically + ) { + // Número e indicador + Text( + text = if (esActual) "▶" else "${index + 1}", + fontSize = 12.sp, + color = if (esActual) GradioGreen else OnSurfaceDim, + modifier = Modifier.width(28.dp), + fontWeight = if (esActual) FontWeight.Bold else FontWeight.Normal + ) + + // Título + Column(modifier = Modifier.weight(1f)) { + Text( + text = titulo, + fontSize = 14.sp, + color = if (esActual) GradioGreen else OnBg, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + fontWeight = if (esActual) FontWeight.SemiBold else FontWeight.Normal + ) + if (track.duracion.isNotBlank()) { + Text(track.duracion, fontSize = 11.sp, color = OnSurfaceDim) + } + } + + // Botones de acción compactos + if (activo) { + SmallActionBtn(Icons.Default.PlayArrow, "Reproducir") { onPlay() } + SmallActionBtn(Icons.Default.KeyboardArrowUp, "Subir") { onSubir() } + SmallActionBtn(Icons.Default.KeyboardArrowDown, "Bajar") { onBajar() } + SmallActionBtn(Icons.Default.Close, "Eliminar", tint = ErrorColor) { onEliminar() } + } + } +} + +@Composable +private fun SmallActionBtn( + icon: androidx.compose.ui.graphics.vector.ImageVector, + label: String, + tint: androidx.compose.ui.graphics.Color = OnSurfaceDim, + onClick: () -> Unit +) { + IconButton(onClick = onClick, modifier = Modifier.size(32.dp)) { + Icon(icon, contentDescription = label, tint = tint, modifier = Modifier.size(18.dp)) + } +} + +private fun fmtTiempo(secs: Double): String { + val s = secs.toLong() + return "${s / 60}:${(s % 60).toString().padStart(2, '0')}" +} diff --git a/app/src/main/java/com/gradio/client/ui/screens/VisorScreen.kt b/app/src/main/java/com/gradio/client/ui/screens/VisorScreen.kt new file mode 100644 index 0000000..21da504 --- /dev/null +++ b/app/src/main/java/com/gradio/client/ui/screens/VisorScreen.kt @@ -0,0 +1,142 @@ +package com.gradio.client.ui.screens + +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.* +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.gradio.client.network.EstadoCon +import com.gradio.client.ui.theme.* +import com.gradio.client.ui.viewmodel.MainViewModel +import java.time.LocalDate +import java.time.format.DateTimeFormatter + +@Composable +fun VisorScreen(vm: MainViewModel) { + val lineas by vm.reporteLineas.collectAsState() + val estCon by vm.estadoCon.collectAsState() + val activo = estCon is EstadoCon.Conectado + + var tipoReporte by remember { mutableStateOf("parrilla") } + var fecha by remember { mutableStateOf(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))) } + val listState = rememberLazyListState() + + Column(modifier = Modifier.fillMaxSize()) { + // ── Controles ───────────────────────────────────────────────────────── + Column(modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Icon(Icons.Default.BarChart, null, tint = GradioGreen, modifier = Modifier.size(20.dp)) + Spacer(Modifier.width(8.dp)) + Text("Reportes", fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = OnBg) + } + Spacer(Modifier.height(8.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + listOf("parrilla" to "Parrilla", "comerciales" to "Comerciales", "eventos" to "Eventos").forEach { (key, label) -> + FilterChip( + selected = tipoReporte == key, + onClick = { tipoReporte = key }, + label = { Text(label, fontSize = 12.sp) }, + colors = FilterChipDefaults.filterChipColors( + selectedContainerColor = GradioGreen, + selectedLabelColor = MaterialTheme.colorScheme.background + ) + ) + } + } + Spacer(Modifier.height(6.dp)) + Row(verticalAlignment = Alignment.CenterVertically) { + OutlinedTextField( + value = fecha, + onValueChange = { if (it.length <= 8 && it.all { c -> c.isDigit() }) fecha = it }, + label = { Text("Fecha (YYYYMMDD)", fontSize = 12.sp) }, + singleLine = true, + modifier = Modifier.weight(1f), + enabled = activo, + colors = OutlinedTextFieldDefaults.colors( + focusedBorderColor = GradioGreen, + unfocusedBorderColor = OnSurfaceDim.copy(alpha = 0.5f), + focusedLabelColor = GradioGreen, + cursorColor = GradioGreen, + focusedTextColor = OnBg, + unfocusedTextColor = OnBg, + unfocusedLabelColor = OnSurfaceDim, + ) + ) + Spacer(Modifier.width(8.dp)) + IconButton( + onClick = { + val d = LocalDate.parse(fecha, DateTimeFormatter.ofPattern("yyyyMMdd")) + fecha = d.minusDays(1).format(DateTimeFormatter.ofPattern("yyyyMMdd")) + }, + enabled = activo + ) { + Icon(Icons.Default.ChevronLeft, null, tint = OnBg) + } + IconButton( + onClick = { + val d = LocalDate.parse(fecha, DateTimeFormatter.ofPattern("yyyyMMdd")) + fecha = d.plusDays(1).format(DateTimeFormatter.ofPattern("yyyyMMdd")) + }, + enabled = activo + ) { + Icon(Icons.Default.ChevronRight, null, tint = OnBg) + } + Button( + onClick = { vm.cargarReportes(tipoReporte, fecha) }, + enabled = activo, + colors = ButtonDefaults.buttonColors(containerColor = GradioGreenDk), + modifier = Modifier.height(48.dp) + ) { Text("Ver", fontSize = 13.sp) } + } + } + + HorizontalDivider(color = GradioCard) + + if (!activo) { + Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Text("Conectate para ver reportes", color = OnSurfaceDim, fontSize = 14.sp) + } + return@Column + } + + if (lineas.isEmpty()) { + Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Icon(Icons.Default.BarChart, null, tint = OnSurfaceDim.copy(alpha = 0.4f), modifier = Modifier.size(48.dp)) + Spacer(Modifier.height(8.dp)) + Text("Selecciona tipo y fecha", color = OnSurfaceDim, fontSize = 14.sp) + } + } + return@Column + } + + Text("${lineas.size} línea(s)", fontSize = 12.sp, color = OnSurfaceDim, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp)) + + LazyColumn( + state = listState, + modifier = Modifier.fillMaxSize().padding(horizontal = 8.dp) + ) { + items(lineas) { linea -> + Text( + text = linea, + fontSize = 11.sp, + fontFamily = FontFamily.Monospace, + color = if (linea.contains("ERROR", ignoreCase = true)) ErrorColor + else if (linea.contains("WARN", ignoreCase = true)) WarningColor + else OnBg.copy(alpha = 0.9f), + modifier = Modifier.padding(vertical = 1.dp) + ) + } + } + } +} diff --git a/app/src/main/java/com/gradio/client/ui/theme/Theme.kt b/app/src/main/java/com/gradio/client/ui/theme/Theme.kt new file mode 100644 index 0000000..ce6c370 --- /dev/null +++ b/app/src/main/java/com/gradio/client/ui/theme/Theme.kt @@ -0,0 +1,38 @@ +package com.gradio.client.ui.theme + +import androidx.compose.material3.* +import androidx.compose.runtime.Composable +import androidx.compose.ui.graphics.Color + +val GradioGreen = Color(0xFF1DB954) +val GradioGreenDk = Color(0xFF148A3C) +val GradioBg = Color(0xFF0F1117) +val GradioSurface = Color(0xFF1A1D27) +val GradioCard = Color(0xFF242838) +val OnBg = Color(0xFFE8EAF0) +val OnSurfaceDim = Color(0xFF9E9EB0) +val ErrorColor = Color(0xFFCF6679) +val WarningColor = Color(0xFFFFB74D) + +private val DarkColors = darkColorScheme( + primary = GradioGreen, + onPrimary = Color.Black, + primaryContainer = GradioGreenDk, + secondary = Color(0xFF5C6BC0), + background = GradioBg, + surface = GradioSurface, + surfaceVariant = GradioCard, + onBackground = OnBg, + onSurface = OnBg, + onSurfaceVariant = OnSurfaceDim, + error = ErrorColor, +) + +@Composable +fun GRadioClientTheme(content: @Composable () -> Unit) { + MaterialTheme( + colorScheme = DarkColors, + typography = Typography(), + content = content + ) +} diff --git a/app/src/main/java/com/gradio/client/ui/viewmodel/MainViewModel.kt b/app/src/main/java/com/gradio/client/ui/viewmodel/MainViewModel.kt new file mode 100644 index 0000000..cfb920d --- /dev/null +++ b/app/src/main/java/com/gradio/client/ui/viewmodel/MainViewModel.kt @@ -0,0 +1,296 @@ +package com.gradio.client.ui.viewmodel + +import android.app.Application +import android.content.Context +import android.net.ConnectivityManager +import android.net.Network +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.viewModelScope +import com.gradio.client.data.* +import com.gradio.client.network.ConnectionManager +import com.gradio.client.network.EstadoCon +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.launch + +data class Config( + val servidor: String = "192.168.1.100", + val puerto: Int = 7777, + val token: String = "", + val modoRelay: Boolean = false, + val relayId: String = "" +) + +class MainViewModel(app: Application) : AndroidViewModel(app) { + + val conexion = ConnectionManager() + + // ── Config persistida ───────────────────────────────────────────────────── + private val prefs = app.getSharedPreferences("gr_client", Context.MODE_PRIVATE) + + // ── Reconexión automática al recuperar señal (modo avión → activo) ──────── + private val cm = app.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager + private var reconectarJob: Job? = null + private val networkCallback = object : ConnectivityManager.NetworkCallback() { + override fun onAvailable(network: Network) { + // Cancelar reconexión pendiente para evitar disparos dobles + reconectarJob?.cancel() + reconectarJob = viewModelScope.launch { + delay(500L) // esperar que la red se estabilice + if (estadoCon.value is EstadoCon.Error) { + conectar(_config.value) + } + } + } + } + + private val _config = MutableStateFlow(cargarConfig()) + val config: StateFlow = _config + + // ── Estado de conexión ──────────────────────────────────────────────────── + val estadoCon: StateFlow = conexion.estadoCon + + // ── Estado del player ───────────────────────────────────────────────────── + private val _estadoPlayer = MutableStateFlow(EstadoRemoto()) + val estadoPlayer: StateFlow = _estadoPlayer + + private val _playlist = MutableStateFlow>(emptyList()) + val playlist: StateFlow> = _playlist + + // ── Búsqueda ────────────────────────────────────────────────────────────── + private val _resultadosBusqueda = MutableStateFlow>(emptyList()) + val resultadosBusqueda: StateFlow> = _resultadosBusqueda + + private val _buscando = MutableStateFlow(false) + val buscando: StateFlow = _buscando + + // ── Botonera ────────────────────────────────────────────────────────────── + private val _botones = MutableStateFlow>(emptyList()) + val botones: StateFlow> = _botones + + // ── Parrilla ────────────────────────────────────────────────────────────── + private val _parrillaItems = MutableStateFlow>(emptyList()) + val parrillaItems: StateFlow> = _parrillaItems + + private val _parrillaDia = MutableStateFlow(1) + val parrillaDia: StateFlow = _parrillaDia + + private val _parrillaHora = MutableStateFlow(0) + val parrillaHora: StateFlow = _parrillaHora + + // ── Pautaje ─────────────────────────────────────────────────────────────── + private val _pautajeEntradas = MutableStateFlow>(emptyList()) + val pautajeEntradas: StateFlow> = _pautajeEntradas + + private val _pautajeTipo = MutableStateFlow("comerciales") + val pautajeTipo: StateFlow = _pautajeTipo + + private val _pautajeHora = MutableStateFlow(0) + val pautajeHora: StateFlow = _pautajeHora + + private val _pautajeMinuto = MutableStateFlow(0) + val pautajeMinuto: StateFlow = _pautajeMinuto + + // ── Colas activas (comerciales / eventos / eventos en espera) ───────────── + private val _colaComerciales = MutableStateFlow>(emptyList()) + val colaComerciales: StateFlow> = _colaComerciales + + private val _colaEventos = MutableStateFlow>(emptyList()) + val colaEventos: StateFlow> = _colaEventos + + private val _colaEventosEspera = MutableStateFlow>(emptyList()) + val colaEventosEspera: StateFlow> = _colaEventosEspera + + private val _proximasTandas = MutableStateFlow>(emptyList()) + val proximasTandas: StateFlow> = _proximasTandas + + // ── Visor ───────────────────────────────────────────────────────────────── + private val _reporteLineas = MutableStateFlow>(emptyList()) + val reporteLineas: StateFlow> = _reporteLineas + + // ── Toast / snackbar ────────────────────────────────────────────────────── + private val _snackbar = MutableStateFlow(null) + val snackbar: StateFlow = _snackbar + + init { + viewModelScope.launch { + conexion.mensajes.collect { msg -> procesarMensaje(msg) } + } + cm.registerDefaultNetworkCallback(networkCallback) + } + + // ── Conexión ────────────────────────────────────────────────────────────── + + fun conectar(cfg: Config) { + _config.value = cfg + guardarConfig(cfg) + if (cfg.modoRelay) { + conexion.conectarRelay(cfg.relayId, cfg.token) + } else { + conexion.conectarTCP(cfg.servidor, cfg.puerto, cfg.token) + } + } + + fun desconectar() { + conexion.desconectar() + } + + // ── Comandos player ─────────────────────────────────────────────────────── + + fun play() = conexion.enviar(MsgCliente.ComandoPlayer("play")) + fun pause() = conexion.enviar(MsgCliente.ComandoPlayer("pause")) + fun stop() = conexion.enviar(MsgCliente.ComandoPlayer("stop")) + fun stopAfter() = conexion.enviar(MsgCliente.ComandoPlayer("stop_after")) + fun siguiente() = conexion.enviar(MsgCliente.ComandoPlayer("siguiente")) + fun setVol(v: Int) = conexion.enviar(MsgCliente.SetVolumen(v)) + fun stopGeneral() = conexion.enviar(MsgCliente.StopGeneral) + fun vaciarComerciales() { conexion.enviar(MsgCliente.VaciarComerciales); conexion.enviar(MsgCliente.ObtenerCola("comerciales")) } + fun vaciarEventos() { conexion.enviar(MsgCliente.VaciarEventos); conexion.enviar(MsgCliente.ObtenerCola("eventos")) } + fun vaciarEventosEspera() { conexion.enviar(MsgCliente.VaciarEventosEspera); conexion.enviar(MsgCliente.ObtenerCola("eventos_espera")) } + fun obtenerCola(tipo: String) = conexion.enviar(MsgCliente.ObtenerCola(tipo)) + fun eliminarDeCola(tipo: String, indice: Int) = conexion.enviar(MsgCliente.EliminarDeCola(tipo, indice)) + fun recargarColas() { + conexion.enviar(MsgCliente.ObtenerCola("comerciales")) + conexion.enviar(MsgCliente.ObtenerCola("eventos")) + conexion.enviar(MsgCliente.ObtenerCola("eventos_espera")) + conexion.enviar(MsgCliente.ObtenerProximasTandas) + } + fun reproducirTanda(tanda: TandaRemota) { + conexion.enviar(MsgCliente.ReproducirTanda(tanda.hora, tanda.minuto, tanda.items.map { it.ruta })) + conexion.enviar(MsgCliente.ObtenerProximasTandas) + mostrarSnackbar("Reproduciendo tanda %02d:%02d".format(tanda.hora, tanda.minuto)) + } + fun reproducirAhora(ruta: String) = conexion.enviar(MsgCliente.ReproducirAhora(ruta)) + fun playlistPlayAhora(ruta: String, duracion: String) = conexion.enviar(MsgCliente.PlaylistPlayAhora(ruta, duracion)) + fun eliminarDePlaylist(indice: Int) { + conexion.enviar(MsgCliente.EliminarDePlaylist(indice)) + conexion.enviar(MsgCliente.ObtenerPlaylist) + } + fun moverEnPlaylist(indice: Int, arriba: Boolean) { + conexion.enviar(MsgCliente.MoverEnPlaylist(indice, arriba)) + conexion.enviar(MsgCliente.ObtenerPlaylist) + } + + // ── Búsqueda ────────────────────────────────────────────────────────────── + + fun buscar(consulta: String) { + _buscando.value = true + _resultadosBusqueda.value = emptyList() + conexion.enviar(MsgCliente.Buscar(consulta, null)) + } + + fun agregarAlPlaylist(ruta: String, alInicio: Boolean = false) { + conexion.enviar(MsgCliente.AgregarAlPlaylist(ruta, "", alInicio)) + conexion.enviar(MsgCliente.ObtenerPlaylist) + mostrarSnackbar(if (alInicio) "Añadido al inicio de la lista" else "Añadido al final de la lista") + } + + // ── Botonera ────────────────────────────────────────────────────────────── + + fun presionarBoton(boton: BotonRemoto) { + conexion.enviar(MsgCliente.ReproducirAhora(boton.ruta)) + } + + fun recargarBotonera() = conexion.enviar(MsgCliente.ObtenerBotonera) + + // ── Parrilla ────────────────────────────────────────────────────────────── + + fun cargarParrilla(dia: Int, hora: Int) { + _parrillaDia.value = dia + _parrillaHora.value = hora + conexion.enviar(MsgCliente.ObtenerParrilla(dia, hora)) + } + + fun guardarParrilla(items: List) { + conexion.enviar(MsgCliente.GuardarParrilla(_parrillaDia.value, _parrillaHora.value, items)) + } + + // ── Pautaje ─────────────────────────────────────────────────────────────── + + fun cargarPautaje(tipo: String, hora: Int, minuto: Int) { + _pautajeTipo.value = tipo + _pautajeHora.value = hora + _pautajeMinuto.value = minuto + conexion.enviar(MsgCliente.ObtenerPautaje(tipo, hora, minuto)) + } + + fun guardarPautaje(entradas: List) { + conexion.enviar(MsgCliente.GuardarPautaje(_pautajeTipo.value, _pautajeHora.value, _pautajeMinuto.value, entradas)) + } + + // ── Visor ───────────────────────────────────────────────────────────────── + + fun cargarReportes(tipo: String, fecha: String) { + conexion.enviar(MsgCliente.ObtenerReportes(tipo, fecha)) + } + + // ── Snackbar ────────────────────────────────────────────────────────────── + + fun mostrarSnackbar(msg: String) { _snackbar.value = msg } + fun limpiarSnackbar() { _snackbar.value = null } + + // ── Procesador de mensajes del servidor ─────────────────────────────────── + + private fun procesarMensaje(msg: MsgServidor) { + when (msg) { + is MsgServidor.PlaylistObtenida, + is MsgServidor.PlaylistCambiada -> { + val tracks = if (msg is MsgServidor.PlaylistObtenida) msg.tracks else (msg as MsgServidor.PlaylistCambiada).tracks + _playlist.value = tracks + } + is MsgServidor.EstadoObtenido, + is MsgServidor.EstadoCambiado -> { + val est = if (msg is MsgServidor.EstadoObtenido) msg.estado else (msg as MsgServidor.EstadoCambiado).estado + _estadoPlayer.value = est + } + is MsgServidor.ResultadosBusqueda -> { + _buscando.value = false + _resultadosBusqueda.value = msg.resultados + } + is MsgServidor.BotoneraObtenida -> _botones.value = msg.botones + is MsgServidor.ParrillaObtenida -> _parrillaItems.value = msg.items + is MsgServidor.PautajeObtenido -> _pautajeEntradas.value = msg.entradas + is MsgServidor.ReportesObtenidos -> _reporteLineas.value = msg.lineas + is MsgServidor.ColaObtenida -> when (msg.tipo_cola) { + "comerciales" -> _colaComerciales.value = msg.items + "eventos" -> _colaEventos.value = msg.items + "eventos_espera" -> _colaEventosEspera.value = msg.items + } + is MsgServidor.ProximasTandasObtenidas -> _proximasTandas.value = msg.tandas + is MsgServidor.IndiceActualizado -> mostrarSnackbar(if (msg.ok) "Índice actualizado" else "Error: ${msg.mensaje}") + is MsgServidor.Error -> mostrarSnackbar("Error: ${msg.mensaje}") + is MsgServidor.PautajeGuardado -> mostrarSnackbar("Pautaje guardado") + is MsgServidor.ParrillaGuardada -> mostrarSnackbar("Parrilla guardada") + is MsgServidor.BotoneraGuardada -> mostrarSnackbar("Botonera guardada") + else -> {} + } + } + + // ── Configuración persistida ────────────────────────────────────────────── + + private fun cargarConfig() = Config( + servidor = prefs.getString("servidor", "192.168.1.100") ?: "192.168.1.100", + puerto = prefs.getInt("puerto", 7777), + token = prefs.getString("token", "") ?: "", + modoRelay = prefs.getBoolean("modo_relay", false), + relayId = prefs.getString("relay_id", "") ?: "" + ) + + private fun guardarConfig(c: Config) { + prefs.edit() + .putString("servidor", c.servidor) + .putInt("puerto", c.puerto) + .putString("token", c.token) + .putBoolean("modo_relay", c.modoRelay) + .putString("relay_id", c.relayId) + .apply() + } + + override fun onCleared() { + try { cm.unregisterNetworkCallback(networkCallback) } catch (_: Exception) {} + conexion.desconectar() + super.onCleared() + } +} diff --git a/app/src/main/res/drawable/gradio_logo.png b/app/src/main/res/drawable/gradio_logo.png new file mode 100755 index 0000000..a61a33f Binary files /dev/null and b/app/src/main/res/drawable/gradio_logo.png differ diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..4a213bb --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,4 @@ + + + + diff --git a/app/src/main/res/drawable/ic_launcher_foreground.xml b/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..fad9bfa --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,12 @@ + + + + + + diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.xml b/app/src/main/res/mipmap-hdpi/ic_launcher.xml new file mode 100644 index 0000000..d378acd --- /dev/null +++ b/app/src/main/res/mipmap-hdpi/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_round.xml b/app/src/main/res/mipmap-hdpi/ic_launcher_round.xml new file mode 100644 index 0000000..d378acd --- /dev/null +++ b/app/src/main/res/mipmap-hdpi/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.xml b/app/src/main/res/mipmap-mdpi/ic_launcher.xml new file mode 100644 index 0000000..d378acd --- /dev/null +++ b/app/src/main/res/mipmap-mdpi/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_round.xml b/app/src/main/res/mipmap-mdpi/ic_launcher_round.xml new file mode 100644 index 0000000..d378acd --- /dev/null +++ b/app/src/main/res/mipmap-mdpi/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.xml b/app/src/main/res/mipmap-xhdpi/ic_launcher.xml new file mode 100644 index 0000000..d378acd --- /dev/null +++ b/app/src/main/res/mipmap-xhdpi/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.xml b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.xml new file mode 100644 index 0000000..d378acd --- /dev/null +++ b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.xml b/app/src/main/res/mipmap-xxhdpi/ic_launcher.xml new file mode 100644 index 0000000..d378acd --- /dev/null +++ b/app/src/main/res/mipmap-xxhdpi/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.xml b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.xml new file mode 100644 index 0000000..d378acd --- /dev/null +++ b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.xml b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.xml new file mode 100644 index 0000000..d378acd --- /dev/null +++ b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.xml b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.xml new file mode 100644 index 0000000..d378acd --- /dev/null +++ b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml new file mode 100644 index 0000000..66fc0ad --- /dev/null +++ b/app/src/main/res/values-es/strings.xml @@ -0,0 +1,41 @@ + + + G Radio Client + + Player + Búsqueda + Parrilla + Botonera + Pautaje + Comercios + Reportes + + OK + Cancelar + Guardar + Cerrar + Conectar + Desconectar + Agregar + Eliminar + Editar + Confirmar + Detener + Detener todo + Subir + Bajar + + Servidor: + Puerto: + Token: + Desconectado + Conectado + + Cola vacía + Escribe para buscar + Conectate para buscar audio + Conectate para ver la botonera + Conectate para ver la parrilla + Conectate para ver pautaje + Conectate para ver reportes + diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml new file mode 100644 index 0000000..f503e09 --- /dev/null +++ b/app/src/main/res/values-pt/strings.xml @@ -0,0 +1,41 @@ + + + G Radio Client + + Player + Busca + Grade + Botoeira + Pauta + Comerciais + Relatórios + + OK + Cancelar + Salvar + Fechar + Conectar + Desconectar + Adicionar + Excluir + Editar + Confirmar + Parar + Parar tudo + Subir + Descer + + Servidor: + Porta: + Token: + Desconectado + Conectado + + Fila vazia + Digite para buscar + Conecte-se para buscar áudio + Conecte-se para ver a botoeira + Conecte-se para ver a grade + Conecte-se para ver a pauta + Conecte-se para ver relatórios + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..657501d --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,51 @@ + + + + G Radio Client + + + Player + Search + Schedule + Buttons + Ad schedule + Ads + Reports + + + OK + Cancel + Save + Close + Connect + Disconnect + Add + Delete + Edit + Confirm + Stop + Stop all + Up + Down + + + Server: + Port: + Token: + Disconnected + Connected + + + Empty queue + Type to search + Connect to search audio + Connect to see the buttons board + Connect to see the schedule + Connect to see the ad schedule + Connect to see reports + diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..63e196d --- /dev/null +++ b/app/src/main/res/values/themes.xml @@ -0,0 +1,4 @@ + + +