diff --git a/.gitignore b/.gitignore index f89a0ab..8685299 100644 --- a/.gitignore +++ b/.gitignore @@ -7,4 +7,6 @@ /app/build /captures .externalNativeBuild -.cxxreports/*-shots/ +.cxx +reports/*-shots/ +reports/*.md diff --git a/AGENTS.md b/AGENTS.md index 1e68716..bc283be 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,9 +69,10 @@ setup/login screen, `Ready` renders `HomeScreen`, which switches content on a whose media lives in a private object-storage bucket — pass the short-lived `POST /api/v1/videos/{shortUuid}/token` token as `?videoFileToken=` on those URLs (response shape: `{ files: { token, expires } }`; verified live). - - tube.jeena.net itself streams non-public media from a **publicly readable R2 - bucket** (`pub-….r2.dev`): no auth is enforced there today, but do not rely on - that — always request the file token for non-public videos. + - Some instances stream non-public media from object-storage hosts with only + URL-based access control — never rely on that; always request and use the + file token for non-public videos. (Instance-specific findings stay out of + the public repo and live in the private ops notes/agent-local instructions.) ## Conventions diff --git a/BACKLOG.md b/BACKLOG.md index 947bade..f9e6182 100644 --- a/BACKLOG.md +++ b/BACKLOG.md @@ -38,18 +38,20 @@ focus colors, always-focusable Sign in with inline validation. Deferred from rev - Logout / switch account: sign-out entry exists; add switch-account (re-login screen without losing scroll state). - Release build: enable `minifyEnabled` + R8 rules, decide signing/versioning. -- Thumbnails of private/internal videos may 404 — verified on tube.jeena.net: - instance thumbnail paths are publicly readable (HTTP 200 without auth); add a - fallback poster only if other instances behave differently. -- Security note for tube.jeena.net: object-storage (R2) media for private test - videos is publicly readable without token ("private" only via URL obscurity). - Flag to the instance admin; the app must not rely on this laxness. +- Thumbnails of private/internal videos may 404 — on some instances thumbnail + paths are publicly readable while on others they need auth; add a fallback + poster only if needed. +- Security note (verified live against tube.jeena.net): some instances serve + non-public media / thumbnails from object storage with only URL-based access + control. The app must not rely on that laxness; always send auth headers + / file tokens for non-public media. (Detail intentionally omitted from the + public repo — report instance-specific findings privately.) - Verify `searchTarget=local` channel search behaves well for instances without federation; consider `search/video-channels` endpoint as an alternative. - Release build: enable `minifyEnabled` + R8 rules, decide on signing, versioning scheme. - Verify `searchTarget=local` channel search behaves well for instances without federation; consider `search/video-channels` endpoint as an alternative. -- (Verified 2026-10-10 via the test account account) history subscriptions + watching endpoints +- (Verified 2026-10-10 via the test account) history subscriptions + watching endpoints behave as documented; upload seeding uses **flat multipart form fields** on `/api/v1/videos/upload` (legacy), not a metadata JSON part — only relevant for seeding test data, the app itself doesn't upload. 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 index 9ee3a32..92e06f2 100644 --- a/README.md +++ b/README.md @@ -66,4 +66,5 @@ Single-module Android TV app (`app/`): ## License -Not decided yet — TBD before first public release. \ No newline at end of file +JTube TV is free software: [GPL-3.0-or-later](LICENSE) — see the +[fsf.org license page](https://www.gnu.org/licenses/) for details. \ No newline at end of file diff --git a/TESTS.md b/TESTS.md index 46dbb1b..4f5dd87 100644 --- a/TESTS.md +++ b/TESTS.md @@ -13,10 +13,11 @@ when everything passes (playback, focus and UI states are untestable by script). ## Test environment / prerequisites - Instance: any PeerTube (baseline: , v8.3.1, media on R2 object storage). -- Account: `the test account` (sops: `~/.agents/secrets/jtube.env`). Credentials resolved +- Account: a dedicated test account (credentials via sops from `~/.agents/secrets/jtube.env`). + Credentials resolved at login; **do not store the password in the device during tests** — it's typed once on the setup screen (which is exactly feature 0). -- Seeded content (tagged `jtube-tv-test`, channel `the test channel`): +- Seeded content (tagged `jtube-tv-test`, in the test account's channel): - `JTube TV Test 1 - Sintel Teaser` **Private** (~52 s) - `JTube TV Test 2 - Caminandes Llamigos` **Private** (~2:30) - `JTube TV Test 3 - Cosmos Laundromat` **Private** (~50 s) @@ -57,7 +58,7 @@ APK version + device. - [ ] T9 Long video title truncates (2 lines max) without breaking the row layout; long channel names truncate. ### 2 — Channels -- [ ] T10 "Channels" lists account's own channels (`the test channel`), avatar when present, video count. +- [ ] T10 "Channels" lists the account's own channels, avatar when present, video count. - [ ] T11 Click channel → that channel's videos list; open and play one; back returns to the channel's list (not the channels screen lost state). - [ ] T12 Remote channel via direct handle is out of MVP scope, but local-channel search (when implemented) must be re-tested: `searchTarget=local` ignores federated results. diff --git a/app/src/main/java/net/jeena/jtubetv/JTubeApp.kt b/app/src/main/java/net/jeena/jtubetv/JTubeApp.kt index 60d5628..fe13971 100644 --- a/app/src/main/java/net/jeena/jtubetv/JTubeApp.kt +++ b/app/src/main/java/net/jeena/jtubetv/JTubeApp.kt @@ -1,6 +1,8 @@ package net.jeena.jtubetv import android.app.Application +import coil.ImageLoader +import coil.ImageLoaderFactory import net.jeena.jtubetv.data.PeerTubeRepository import net.jeena.jtubetv.data.auth.TokenStore import net.jeena.jtubetv.data.network.PeerTubeNetwork @@ -11,16 +13,29 @@ object AppGraph { private set lateinit var tokenStore: TokenStore private set + var appContext: android.content.Context? = null + private set fun init(context: Application) { + appContext = context tokenStore = TokenStore(context) repository = PeerTubeRepository(tokenStore, PeerTubeNetwork(tokenStore)) } } -class JTubeApp : Application() { +class JTubeApp : Application(), coil.ImageLoaderFactory { override fun onCreate() { super.onCreate() AppGraph.init(this) } + + /** + * TVs are slow compositors: decode thumbnails as RGB_565 at capped size so + * scrolling rows keep a smooth frame rate (user: "the animation has very low fps"). + */ + override fun newImageLoader(): ImageLoader = + ImageLoader.Builder(this) + .bitmapConfig(android.graphics.Bitmap.Config.RGB_565) + .crossfade(false) + .build() } \ No newline at end of file diff --git a/app/src/main/java/net/jeena/jtubetv/data/PeerTubeRepository.kt b/app/src/main/java/net/jeena/jtubetv/data/PeerTubeRepository.kt index 50e2eee..8922c39 100644 --- a/app/src/main/java/net/jeena/jtubetv/data/PeerTubeRepository.kt +++ b/app/src/main/java/net/jeena/jtubetv/data/PeerTubeRepository.kt @@ -2,7 +2,9 @@ package net.jeena.jtubetv.data import kotlinx.serialization.json.Json import net.jeena.jtubetv.data.api.HistoryElement +import net.jeena.jtubetv.data.api.ChannelStats import net.jeena.jtubetv.data.api.OAuthClient +import net.jeena.jtubetv.data.api.ServerConfigDto import net.jeena.jtubetv.data.api.PeerTubeApi import net.jeena.jtubetv.data.api.TokenResponse import net.jeena.jtubetv.data.api.UserDto @@ -86,7 +88,17 @@ class PeerTubeRepository( .addConverterFactory(json.asConverterFactory("application/json; charset=utf-8".toMediaType())) .build() .create(PeerTubeApi::class.java) - store.accountName = meApi.me().username + store.instanceName = try { + meApi.serverConfig().instance.name + } catch (_: Exception) { null } + val me = meApi.me() + store.accountName = me.username + store.userDisplayName = me.displayName ?: me.username + me.avatars.maxByOrNull { it.width }?.let { avatar -> + store.userAvatarUrl = avatar.fileUrl + ?.takeIf { url -> url.startsWith("http") } + ?: apiUrlOf(base) + avatar.path + } } catch (_: Exception) { store.accountName = username.substringBefore('@') // best effort fallback } @@ -94,6 +106,49 @@ class PeerTubeRepository( suspend fun me(): Result = runCatching { network.api.me() } + suspend fun serverConfig(): Result = runCatching { network.api.serverConfig() } + + /** Display name of a (possibly foreign) instance, via that instance's /config. */ + suspend fun instanceName(rawHost: String): Result = runCatching { + val base = "https://" + rawHost + val api = unauthenticatedApiFor(base) + api.serverConfig().instance.name ?: rawHost + } + + /** + * videosCount + total plays for a channel (listing DTOs don't carry them). + * Sums views over up to [maxPages] video pages. + */ + suspend fun channelStats(handle: String, maxPages: Int = 4): Result = + runCatching { + var start = 0L + var videos = 0L + var plays = 0L + var total: Long? = null + var latestThumb: String? = null + repeat(maxPages) { + val page = network.api.channelVideos(handle, start, 25) + if (total == null) { + total = page.total + latestThumb = page.data.firstOrNull()?.thumbnailPath?.let { path -> + if (path.startsWith("http")) path else baseUrl + "/" + path.trimStart('/') + } + } + plays += page.data.sumOf { it.views } + start += page.data.size + videos = total ?: videos + } + net.jeena.jtubetv.data.api.ChannelStats(videos, plays, latestThumb) + } + + private fun unauthenticatedApiFor(base: String): PeerTubeApi = + Retrofit.Builder() + .baseUrl(apiUrlOf(base) + "/") + .client(plainOkHttp()) + .addConverterFactory(json.asConverterFactory("application/json; charset=utf-8".toMediaType())) + .build() + .create(PeerTubeApi::class.java) + // ---- video lists ------------------------------------------------------- suspend fun localVideos(start: Long, count: Int, search: String? = null): Result = @@ -119,6 +174,19 @@ class PeerTubeRepository( suspend fun localChannels(start: Long, count: Int, search: String? = null): Result = runCatching { network.api.channels(start = start, count = count, search = search) } + /** + * Plain channel listing (the API has no local-only filter; returns local + + * followed-instance channels). Caller splits by host. + */ + suspend fun channelList(start: Long, count: Int): Result, Long>> = + runCatching { + val response = network.api.channels(search = null, start = start, count = count) + response.data to response.total + } + + suspend fun videoChannel(handle: String): Result = + runCatching { network.api.videoChannel(handle) } + suspend fun accountChannels(username: String): Result> = runCatching { val response: VideoChannelListResponse = network.api.accountChannels(username) diff --git a/app/src/main/java/net/jeena/jtubetv/data/api/Dtos.kt b/app/src/main/java/net/jeena/jtubetv/data/api/Dtos.kt index 52a1de0..91d3777 100644 --- a/app/src/main/java/net/jeena/jtubetv/data/api/Dtos.kt +++ b/app/src/main/java/net/jeena/jtubetv/data/api/Dtos.kt @@ -60,6 +60,14 @@ data class VideoListResponse( val data: List, ) +@Serializable +data class ChannelOwnerAccount( + val name: String, + val host: String? = null, + @SerialName("displayName") val displayName: String? = null, + val avatars: List = emptyList(), +) + @Serializable data class VideoChannelDto( val name: String, @@ -67,7 +75,10 @@ data class VideoChannelDto( val host: String, val description: String? = null, val avatars: List = emptyList(), + val banners: List = emptyList(), val videosCount: Long = 0, + val followersCount: Long = 0, + val ownerAccount: ChannelOwnerAccount? = null, ) @Serializable @@ -132,7 +143,28 @@ data class VideoTokenFiles( val expires: String? = null, ) +@Serializable +data class ServerConfigDto( + val instance: InstanceInfoDto, +) + +@Serializable +data class InstanceInfoDto( + val name: String? = null, + val shortDescription: String? = null, +) + +/** Per-channel stats not available in the listing; fetched on demand. */ +data class ChannelStats( + val videos: Long, + val plays: Long, + /** Thumbnail of the newest video — banner fallback for channels without one. */ + val latestThumbUrl: String? = null, +) + @Serializable data class UserDto( val username: String, + val displayName: String? = null, + val avatars: List = emptyList(), ) \ No newline at end of file diff --git a/app/src/main/java/net/jeena/jtubetv/data/api/PeerTubeApi.kt b/app/src/main/java/net/jeena/jtubetv/data/api/PeerTubeApi.kt index 76dd8e2..1c5940a 100644 --- a/app/src/main/java/net/jeena/jtubetv/data/api/PeerTubeApi.kt +++ b/app/src/main/java/net/jeena/jtubetv/data/api/PeerTubeApi.kt @@ -83,6 +83,11 @@ interface PeerTubeApi { @Path("account") account: String, ): VideoChannelListResponse + @GET("video-channels/{handle}") + suspend fun videoChannel( + @Path("handle") handle: String, + ): VideoChannelDto + @GET("video-channels/{handle}/videos") suspend fun channelVideos( @Path("handle") handle: String, @@ -112,4 +117,7 @@ interface PeerTubeApi { @GET("users/me") suspend fun me(): UserDto + + @GET("config") + suspend fun serverConfig(): ServerConfigDto } \ No newline at end of file diff --git a/app/src/main/java/net/jeena/jtubetv/data/auth/TokenStore.kt b/app/src/main/java/net/jeena/jtubetv/data/auth/TokenStore.kt index 2620641..054da4d 100644 --- a/app/src/main/java/net/jeena/jtubetv/data/auth/TokenStore.kt +++ b/app/src/main/java/net/jeena/jtubetv/data/auth/TokenStore.kt @@ -48,6 +48,20 @@ class TokenStore(context: Context) { get() = prefs.getString("refreshToken", null) private set(value) = prefs.edit().putString("refreshToken", value).apply() + /** Display name + avatar for the account button (from users/me at login). */ + var userDisplayName: String? + get() = prefs.getString("userDisplayName", null) + set(value) = prefs.edit().putString("userDisplayName", value).apply() + + /** Human-friendly instance name (e.g. "JTube") for card subtitles. */ + var instanceName: String? + get() = prefs.getString("instanceName", null) + set(value) = prefs.edit().putString("instanceName", value).apply() + + var userAvatarUrl: String? + get() = prefs.getString("userAvatarUrl", null) + set(value) = prefs.edit().putString("userAvatarUrl", value).apply() + /** Real account name from users/me — may differ from the login input (email). */ var accountName: String? get() = prefs.getString("accountName", null) diff --git a/app/src/main/java/net/jeena/jtubetv/ui/list/ImagePrefetcher.kt b/app/src/main/java/net/jeena/jtubetv/ui/list/ImagePrefetcher.kt new file mode 100644 index 0000000..e29ce93 --- /dev/null +++ b/app/src/main/java/net/jeena/jtubetv/ui/list/ImagePrefetcher.kt @@ -0,0 +1,53 @@ +package net.jeena.jtubetv.ui.list + +import android.content.Context +import coil.imageLoader +import coil.request.ImageRequest +import net.jeena.jtubetv.AppGraph +import net.jeena.jtubetv.data.api.Avatar +import net.jeena.jtubetv.data.api.VideoChannelDto +import net.jeena.jtubetv.data.api.VideoDto + +/** + * Warms Coil's caches for images that are already loaded from the API but not yet + * visible further down a row/list, so they pop in instantly instead of popping in + * over the network while scrolling. + * + * Uses the same request shape (size) as the visible [VideoCard]/[ChannelCard] + * renderers so the memory cache keys match exactly. + */ +object ImagePrefetcher { + + private val enqueued = HashSet() + + fun videoThumbnails(videos: List, context: Context = AppGraph.appContext!!) { + for (video in videos) { + val path = video.thumbnailPath?.takeIf { it.isNotBlank() } ?: continue + enqueue(context, AppGraph.repository.absoluteUrl(path), 480, 270) + } + } + + fun channelArt(channels: List, context: Context = AppGraph.appContext!!) { + for (channel in channels) { + val banner = channel.banners.maxByOrNull { it.width } + if (banner != null) enqueue(context, absolute(banner), 480, 270) + val avatar = channel.avatars.maxByOrNull { it.width } + if (avatar != null) enqueue(context, absolute(avatar), 80, 80) + } + } + + private fun absolute(a: Avatar): String = + (a.fileUrl ?: a.path).let { + if (it.startsWith("http")) it + else (AppGraph.tokenStore.baseUrl ?: "") + (if (it.startsWith("/")) "" else "/") + it + } + + private fun enqueue(context: Context, url: String, width: Int, height: Int) { + if (!enqueued.add(url)) return + val request = ImageRequest.Builder(context) + .data(url) + .size(width, height) + .build() + context.imageLoader.enqueue(request) + } +} \ No newline at end of file diff --git a/app/src/main/java/net/jeena/jtubetv/ui/list/PagedListViewModel.kt b/app/src/main/java/net/jeena/jtubetv/ui/list/PagedListViewModel.kt index c96c5bc..3429a76 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/list/PagedListViewModel.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/list/PagedListViewModel.kt @@ -27,6 +27,9 @@ abstract class PagedListViewModel : ViewModel() { protected abstract suspend fun fetch(start: Long, count: Int): Result> + /** Warm image caches for just-loaded rows so later scrolls don't fetch from network. */ + protected open fun onChunkLoaded(chunk: List) {} + fun loadMore(force: Boolean = false) { if (inFlight || (!force && exhausted)) return inFlight = true @@ -39,6 +42,7 @@ abstract class PagedListViewModel : ViewModel() { exhausted = chunk.size < pageSize items = items + chunk loadingInitial = false + onChunkLoaded(chunk) }, onFailure = { e -> if (items.isEmpty()) { diff --git a/app/src/main/java/net/jeena/jtubetv/ui/list/VideoListViewModel.kt b/app/src/main/java/net/jeena/jtubetv/ui/list/VideoListViewModel.kt index 90264f3..a723e8e 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/list/VideoListViewModel.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/list/VideoListViewModel.kt @@ -1,8 +1,13 @@ package net.jeena.jtubetv.ui.list +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewModelScope import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.launch import net.jeena.jtubetv.AppGraph import net.jeena.jtubetv.data.PeerTubeRepository @@ -30,6 +35,23 @@ class VideoListViewModel( val query = MutableStateFlow("") private var activeSearch: String? = null + /** For channel pages: the channel itself (banner + display name) as page header. */ + var channelHeader by androidx.compose.runtime.mutableStateOf( + null, + ) + private set + + override fun onChunkLoaded(chunk: List) { + ImagePrefetcher.videoThumbnails( + chunk.mapNotNull { + when (it) { + is VideoListItem.Video -> it.video + is VideoListItem.HistoryEntry -> it.history.video + } + } + ) + } + override suspend fun fetch(start: Long, count: Int): Result> { return when (val s = source) { is ListSource.LocalVideos -> @@ -49,6 +71,15 @@ class VideoListViewModel( } } + fun loadChannelHeader(repository: PeerTubeRepository) { + val s = source + if (s is ListSource.Channel) { + viewModelScope.launch { + channelHeader = repository.videoChannel(s.handle).getOrNull() + } + } + } + fun triggerSearch(raw: String) { query.value = raw activeSearch = raw.trim().ifBlank { null } diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt index dca0a69..a97a119 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt @@ -1,57 +1,257 @@ package net.jeena.jtubetv.ui.screens +import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.CircleShape -import androidx.compose.material3.Button -import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Groups +import androidx.compose.material.icons.filled.PlayArrow +import androidx.compose.material.icons.filled.VideoLibrary import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.layout.ContentScale -import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewmodel.compose.viewModel +import androidx.tv.material3.Border import androidx.tv.material3.Card import androidx.tv.material3.CardDefaults import coil.compose.AsyncImage +import android.util.Log +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch import net.jeena.jtubetv.AppGraph +import net.jeena.jtubetv.data.PeerTubeRepository import net.jeena.jtubetv.data.auth.TokenStore +import net.jeena.jtubetv.data.api.Avatar +import net.jeena.jtubetv.data.api.ChannelStats +import net.jeena.jtubetv.data.api.UserDto import net.jeena.jtubetv.data.api.VideoChannelDto -import net.jeena.jtubetv.ui.list.PagedListViewModel +import net.jeena.jtubetv.ui.list.ImagePrefetcher +import net.jeena.jtubetv.ui.screens.list.ContainerShape +import net.jeena.jtubetv.ui.screens.list.UnfocusedCardBg +import net.jeena.jtubetv.ui.screens.list.dpadCenterActivatable -class ChannelsViewModel(private val store: TokenStore) : PagedListViewModel() { +/** + * Channels, SmartTube-style: one row per LOCAL user. + * + * - Row 1: the logged-in user ("'s Channels"), then the other local + * users sorted by videos / subscribers / plays (desc). + * - Each row: that user's channels, same ordering; channels with no videos simply + * stay inside their user's row. + * - Followed-instance channels at the end, grouped per platform. + * + * API limits (verified, PeerTube 8.3.1): the /video-channels and /accounts listings + * have no isLocal filter and the listing carries no videosCount/views, so we page + * the full listing (max 100/page) and fetch per-channel stats (videos + sum of + * video views = plays) with small throttled calls. + */ +data class UserGroup( + val ownerName: String, + val label: String, + val avatar: Avatar?, + val channels: List, +) - private var cached: List? = null +class ChannelsViewModel(private val store: TokenStore) : ViewModel() { - override suspend fun fetch(start: Long, count: Int): Result> = - runCatching { - val existing = cached - if (existing == null) { - // MVP: the user's own channels (fully local). A paged, searchable - // local-channels listing needs a non-empty search term server-side. - val response = AppGraph.repository.accountChannels( - store.accountName ?: store.username ?: "", - ) - response.fold(onSuccess = { c -> cached = c; c }, onFailure = { throw it }) - } else existing + var user by mutableStateOf(null) + private set + var userChannels by mutableStateOf>(emptyList()) + private set + + var userRows by mutableStateOf>(emptyList()) + private set + + var loading by mutableStateOf(true) + private set + var error by mutableStateOf(null) + private set + + /** "name@host" -> stats; filled progressively in the background. */ + var stats by mutableStateOf>(emptyMap()) + private set + + /** host -> platform display name (e.g. "JTube" instead of tube.jeena.net). */ + var platformNames by mutableStateOf>(emptyMap()) + private set + + private var allChannels: List = emptyList() + + /** Channels from followed instances, grouped per platform. */ + var followedRows by mutableStateOf>(emptyList()) + private set + + private val repo: PeerTubeRepository = AppGraph.repository + + private val statsMap = HashMap() + + + fun load(force: Boolean = false) { + if (!force && userRows.isNotEmpty()) return + loading = true + error = null + viewModelScope.launch { + try { + // The user's own row renders FIRST (fast: one call), the rest streams in. + user = repo.me().getOrNull() + userChannels = user?.let { u -> + repo.accountChannels(u.username).getOrNull() ?: emptyList() + } ?: emptyList() + val host = store.baseUrl?.substringAfter("://")?.substringBefore('/') + platformNames = mapOf((host ?: "") to (store.instanceName ?: host ?: "")) + + // enum the whole channel list (federation-follow listing incl. local) + val all = mutableListOf() + var start = 0L + var total: Long? = null + var retries = 0 + while (total == null || start < total) { + val page = repo.channelList(start, 100).getOrNull() + if (page == null) { + retries++ + if (retries > 2) break + delay(500) + continue + } + retries = 0 + if (total == null) total = page.second + val known = all.map { it.name to it.host }.toSet() + all += page.first.filter { c -> (c.name to c.host) !in known } + start += 100 + android.util.Log.w( + "JTube", + "channels page " + (start / 100) + ": total=" + total + " all=" + all.size + + " locals=" + all.count { it.host == host }, + ) + allChannels = all + rebuildRows(host) + } + ImagePrefetcher.channelArt(all + userChannels) + + // stats (videos + plays) for every local channel: throttled parallel-ish + val locals = all.filter { it.host == host } + Log.w("JTube", "pages done: all=" + all.size + " locals=" + locals.size + + " userChannels=" + userChannels.size) + channelStatsLoop(locals, host) + } catch (e: Exception) { + error = e.message ?: "Could not load channels" + } finally { + loading = false + } } + } + + /** Fetch stats for [channels], re-sorting rows as data lands. */ + private fun channelStatsLoop(channels: List, host: String?) { + viewModelScope.launch { + for (channel in channels) { + val key = channel.name + "@" + channel.host + if (statsMap.containsKey(key)) continue + val cs = repo.channelStats(key).getOrNull() + if (cs == null) { android.util.Log.w("JTube", "stats FAIL " + key); continue } + android.util.Log.w("JTube", "stats " + key + " videos=" + cs.videos + " plays=" + cs.plays) + statsMap[key] = cs + stats = statsMap.toMap() + rebuildRows(host) + delay(120) + } + } + } + + private fun statOf(c: VideoChannelDto): Long = statsMap[c.name + "@" + c.host]?.videos ?: 0L + private fun playsOf(c: VideoChannelDto): Long = statsMap[c.name + "@" + c.host]?.plays ?: 0L + + /** Rebuilds the per-user rows from current channels+stats (sorted videos/subs/plays). */ + private fun rebuildRows(host: String?) { + runCatching { rebuildRowsInner(host) }.onFailure { + android.util.Log.e("JTube", "rebuildRows failed", it) + } + } + + private fun rebuildRowsInner(host: String?) { + val locals = allChannels.filter { it.host == host } + val foreign = allChannels.filter { it.host != host } + followedRows = foreign + .groupBy { it.host ?: "?" } + .values + .map { row -> + UserGroup( + ownerName = row.firstOrNull()?.host ?: "?", + label = (platformNames[row.firstOrNull()?.host] + ?: row.firstOrNull()?.host ?: "?") + " (followed)", + avatar = null, + channels = row.sortedWith( + compareByDescending { statOf(it) } + .thenByDescending { it.followersCount }, + ), + ) + } + .sortedByDescending { g -> g.channels.sumOf { it.followersCount } } + val ownNames = userChannels.map { c -> c.name }.toSet() + val byOwner = locals.groupBy { ownerKey(it) } + val groups = byOwner.values.map { row -> + val sorted = row.sortedWith( + compareByDescending { statOf(it) } + .thenByDescending { it.followersCount } + .thenByDescending { playsOf(it) }, + ) + val own = row.firstOrNull { it.name in ownNames } + UserGroup( + ownerName = ownerKey(row.first()), + label = ((own?.ownerAccount?.displayName ?: row.firstOrNull()?.ownerAccount?.displayName) ?: "?") + "'s Channels", + avatar = (own?.ownerAccount ?: row.first().ownerAccount)?.avatars?.maxByOrNull { it.width }, + channels = sorted, + ) + } + userRows = groups.sortedWith( + compareByDescending { g -> g.channels.any { it.name in ownNames } } + .thenByDescending { g -> g.channels.sumOf { statsMap[it.name + "@" + it.host]?.videos ?: 0 } } + .thenByDescending { g -> g.channels.sumOf { it.followersCount } }, + ) + Log.w( + "JTube", + "order now: " + userRows.take(6).joinToString(" | ") { g -> + g.ownerName + "(" + g.channels.size + "ch, " + + g.channels.sumOf { statsMap[it.name + "@" + it.host]?.videos ?: 0 } + "v" + + (if (g.channels.any { it.name in ownNames }) ", OWN" else "") + ")" + }, + ) + } + + private fun ownerKey(c: VideoChannelDto) = c.ownerAccount?.name ?: "" companion object { val factory: ViewModelProvider.Factory = object : ViewModelProvider.Factory { @@ -66,102 +266,289 @@ class ChannelsViewModel(private val store: TokenStore) : PagedListViewModel Unit, epoch: Int = 0, + onOpenDrawer: () -> Unit = {}, viewModel: ChannelsViewModel = viewModel(key = "channels$epoch", factory = ChannelsViewModel.factory), ) { - LaunchedEffect(Unit) { viewModel.loadMore(force = true) } + LaunchedEffect(epoch) { viewModel.load(force = true) } - val viewModel = viewModel - val items = viewModel.items - Box(Modifier.fillMaxSize()) { - when { - viewModel.loadingInitial && items.isEmpty() -> Box( - Modifier.fillMaxSize(), - contentAlignment = Alignment.Center, - ) { CircularProgressIndicator() } - items.isEmpty() -> { - val error = viewModel.initialError - Column( - modifier = Modifier.fillMaxSize().padding(16.dp), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.Center, - ) { - if (error != null) { - Text("Could not load channels", color = MaterialTheme.colorScheme.error) - Text(error, style = MaterialTheme.typography.bodySmall) - Button(onClick = { viewModel.retryInitial() }) { Text("Retry") } - } else { - Text("Nothing here yet") + when { + viewModel.loading && viewModel.userRows.isEmpty() -> Box( + Modifier.fillMaxSize(), contentAlignment = Alignment.Center, + ) { androidx.compose.material3.CircularProgressIndicator() } + viewModel.error != null && viewModel.userRows.isEmpty() -> + Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Text("Could not load channels", color = MaterialTheme.colorScheme.error) + Text( + viewModel.error ?: "", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + androidx.compose.material3.Button(onClick = { viewModel.load(force = true) }) { + Text("Retry") } } } - else -> ChannelsList(items, viewModel, onOpenChannel) - } - } -} - -@Composable -private fun ChannelsList( - items: List, - viewModel: ChannelsViewModel, - onOpenChannel: (String) -> Unit, -) { - LazyColumn(modifier = Modifier.fillMaxSize().padding(vertical = 8.dp)) { - itemsIndexed(items) { index, channel -> - ChannelCard( - channel = channel, - onClick = { onOpenChannel("${channel.name}@${channel.host}") }, - ) - if (index >= items.size - PagedListViewModel.LOOKAHEAD) { - LaunchedEffect(index) { viewModel.loadMore() } - } - } - if (!viewModel.exhausted) { - item { - Box(Modifier.fillMaxWidth().padding(24.dp), contentAlignment = Alignment.Center) { - CircularProgressIndicator() + else -> { + // hand the initial focus to the first row exactly ONCE per screen visit: + // as stats stream in the rows re-sort, and re-focusing their first card + // would steal focus mid-navigation (user: "up jumps to the first row"). + val focusHandedOut = remember { mutableStateOf(false) } + LazyColumn(Modifier.fillMaxSize()) { + viewModel.userRows.forEach { group -> + item(key = "hdr-" + group.ownerName) { + RowHeader( + avatar = group.avatar, + label = group.label, + ) + } + item(key = "row-" + group.ownerName) { + ChannelRow( + group.channels, + onOpenChannel, + onOpenDrawer, + focused = !focusHandedOut.value && + group == viewModel.userRows.firstOrNull(), + onFocused = { focusHandedOut.value = true }, + stats = { viewModel.stats[it.name + "@" + it.host] }, + platformName = { viewModel.platformNames[it.host ?: ""] }, + ) + } } } } } } +/** Row header: user icon + "'s Channels". */ @Composable -private fun ChannelCard(channel: VideoChannelDto, onClick: () -> Unit) { - Card( - onClick = onClick, - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 6.dp), - colors = CardDefaults.colors(containerColor = MaterialTheme.colorScheme.surface), +private fun RowHeader(avatar: Avatar?, label: String) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.padding(start = 16.dp, top = 12.dp, bottom = 4.dp), + horizontalArrangement = Arrangement.spacedBy(10.dp), ) { - Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(12.dp)) { - val avatar = channel.avatars.maxByOrNull { it.width } - if (avatar != null) { - val url = avatar.fileUrl?.let { if (it.startsWith("http")) it else null } - ?: (AppGraph.tokenStore.baseUrl + avatar.path) - AsyncImage( - model = url, - contentDescription = channel.displayName, - contentScale = ContentScale.Crop, - modifier = Modifier.size(72.dp).clip(CircleShape).background(Color(0xFF222222)), - ) - } - Column(modifier = Modifier.padding(start = 12.dp)) { - Text( - text = channel.displayName.ifBlank { channel.name }, - style = MaterialTheme.typography.titleMedium, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - Text( - text = "${channel.host} · ${channel.name} · ${channel.videosCount} videos", - style = MaterialTheme.typography.bodySmall, - color = Color(0xFF8A8A8A), - maxLines = 1, - overflow = TextOverflow.Ellipsis, + if (avatar != null) { + AsyncImage( + model = coil.request.ImageRequest.Builder( + androidx.compose.ui.platform.LocalContext.current, ) + .data(absoluteAvatar(avatar)) + .size(80) + .build(), + contentDescription = null, + contentScale = ContentScale.Crop, + modifier = Modifier + .size(28.dp) + .clip(CircleShape) + .background(Color(0xFF222222)), + ) + } + Text(label, style = MaterialTheme.typography.titleMedium, color = Color.White) + } +} + +private fun absoluteAvatar(avatar: Avatar): String = + (avatar.fileUrl ?: avatar.path).let { + if (it.startsWith("http")) it + else (AppGraph.tokenStore.baseUrl ?: "") + (if (it.startsWith("/")) "" else "/") + it + } + +/** Horizontal row of channel cards, eased scroll-in; LEFT at row start -> drawer. */ +@Composable +private fun ChannelRow( + channels: List, + onOpenChannel: (String) -> Unit, + onOpenDrawer: () -> Unit = {}, + focused: Boolean, + onFocused: () -> Unit = {}, + stats: (VideoChannelDto) -> net.jeena.jtubetv.data.api.ChannelStats?, + platformName: (VideoChannelDto) -> String?, +) { + val rowState = androidx.compose.foundation.lazy.rememberLazyListState() + val focusRequesters = remember { HashMap() } + var focusedIndex by remember { mutableStateOf(-1) } + + LaunchedEffect(focusedIndex) { + if (focusedIndex > 0) { + val visible = rowState.layoutInfo.visibleItemsInfo + val target = visible.firstOrNull { it.index == focusedIndex } + val notFullyVisible = target == null || + target.offset < 0 || + target.offset + target.size > rowState.layoutInfo.viewportEndOffset + if (notFullyVisible) rowState.animateScrollToItem(focusedIndex) + } + } + if (focused) { + LaunchedEffect(channels.isNotEmpty()) { + if (channels.isNotEmpty()) { + if (runCatching { focusRequesters[0]?.requestFocus() }.isSuccess) onFocused() } } } + + LazyRow( + state = rowState, + contentPadding = PaddingValues(horizontal = 12.dp), + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + itemsIndexed(channels, key = { _, c -> c.name + "@" + c.host }) { index, channel -> + val fr = remember { FocusRequester() } + focusRequesters[index] = fr + ChannelCard( + channel = channel, + onClick = { onOpenChannel("${channel.name}@${channel.host}") }, + stats = stats(channel), + platformName = platformName(channel), + onLeftAtStart = if (index == 0) onOpenDrawer else null, + modifier = Modifier.focusRequester(fr), + ) + } + } +} + +/** + * Channel card: banner (center-cropped), round avatar bottom-left, channel name, + * "owner - platform" subtitle, then icon stats: videos | subscribers | plays. + */ +@Composable +fun ChannelCard( + channel: VideoChannelDto, + onClick: () -> Unit, + modifier: Modifier = Modifier, + stats: ChannelStats? = null, + platformName: String? = null, + onLeftAtStart: (() -> Unit)? = null, +) { + var cardFocused by remember { mutableStateOf(false) } + Card( + onClick = onClick, + modifier = modifier + .width(rowCardWidth()) + .padding(6.dp) + .dpadCenterActivatable(onClick) + .onFocusChanged { cardFocused = it.isFocused } + .onPreviewKeyEvent { ke -> + if (ke.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN && + ke.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_DPAD_LEFT && + onLeftAtStart != null + ) { + onLeftAtStart() + true + } else false + }, + colors = CardDefaults.colors( + containerColor = UnfocusedCardBg, + contentColor = Color.White, + focusedContainerColor = Color.White, + focusedContentColor = Color(0xFF101010), + ), + scale = CardDefaults.scale(focusedScale = 1f), + border = CardDefaults.border( + focusedBorder = Border(border = BorderStroke(3.dp, Color.White), shape = ContainerShape), + pressedBorder = Border(border = BorderStroke(3.dp, Color.White), shape = ContainerShape), + ), + ) { + Column { + Box( + modifier = Modifier + .fillMaxWidth() + .aspectRatio(16f / 9f) + .background(Color(0xFF222222)), + ) { + // banner, or the newest video's thumbnail for bannerless channels + val banner = channel.banners.maxByOrNull { it.width } + val coverUrl = banner?.let { absoluteBanner(it) } + ?: stats?.latestThumbUrl + if (coverUrl != null) { + AsyncImage( + model = coil.request.ImageRequest.Builder( + androidx.compose.ui.platform.LocalContext.current, + ) + .data(coverUrl) + .size(480, 270) // same key as prefetch + .build(), + contentDescription = channel.displayName, + contentScale = ContentScale.Crop, + modifier = Modifier.fillMaxWidth().aspectRatio(16f / 9f), + ) + } + val avatar = channel.avatars.maxByOrNull { it.width } + if (avatar != null) { + AsyncImage( + model = coil.request.ImageRequest.Builder( + androidx.compose.ui.platform.LocalContext.current, + ) + .data(absoluteAvatar(avatar)) + .size(80, 80) + .build(), + contentDescription = null, + contentScale = ContentScale.Crop, + modifier = Modifier + .align(Alignment.BottomStart) + .padding(8.dp) + .size(40.dp) + .clip(CircleShape) + .background(Color(0xFF333333)), + ) + } + } + Column( + modifier = Modifier.padding(10.dp), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Text( + text = channel.displayName.ifBlank { channel.name }, + style = MaterialTheme.typography.titleSmall, + maxLines = 1, + overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis, + color = if (cardFocused) Color(0xFF101010) else Color.White, + ) + Text( + text = (channel.ownerAccount?.displayName ?: "") + + (if (platformName != null) " - " + platformName else ""), + style = MaterialTheme.typography.bodySmall, + color = if (cardFocused) Color(0xFF6A6A6A) else Color(0xFF8A8A8A), + maxLines = 1, + overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis, + ) + Row( + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + StatWithIcon(Icons.Filled.VideoLibrary, stats?.videos?.toString() ?: "-", cardFocused) + StatWithIcon(Icons.Filled.Groups, channel.followersCount.toString(), cardFocused) + StatWithIcon(Icons.Filled.PlayArrow, stats?.plays?.toString() ?: "-", cardFocused) + } + } + } + } +} + +private fun absoluteBanner(banner: Avatar): String = + (banner.fileUrl ?: banner.path).let { + if (it.startsWith("http")) it + else (AppGraph.tokenStore.baseUrl ?: "") + (if (it.startsWith("/")) "" else "/") + it + } + +@Composable +private fun StatWithIcon( + icon: androidx.compose.ui.graphics.vector.ImageVector, + value: String, + focused: Boolean, +) { + val color = if (focused) Color(0xFF6A6A6A) else Color(0xFF8A8A8A) + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(3.dp), + ) { + androidx.tv.material3.Icon( + imageVector = icon, + contentDescription = null, + tint = color, + modifier = Modifier.size(13.dp), + ) + Text(value, style = MaterialTheme.typography.labelSmall, color = color) + } } \ No newline at end of file diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt index a4dc174..97aa411 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt @@ -11,12 +11,17 @@ import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -36,7 +41,12 @@ import net.jeena.jtubetv.data.api.VideoDto import net.jeena.jtubetv.ui.list.PagedListViewModel import net.jeena.jtubetv.ui.screens.list.VideoCard -private val ROW_CARD_WIDTH = 296.dp +/** Compact SmartTube-style card: ~4 and a bit visible per full-width row. */ +@Composable +fun rowCardWidth(): androidx.compose.ui.unit.Dp { + val windowWidth = androidx.compose.ui.platform.LocalConfiguration.current.screenWidthDp + return ((windowWidth / 4.35f) - 10).dp +} /** One "Continue watching" candidate: video + watched fraction (null = unknown yet). */ data class ContinueItem(val video: VideoDto, val progress: Float?) @@ -47,10 +57,20 @@ class HomeRowsViewModel(private val repository: PeerTubeRepository) : ViewModel( private set var continueLoading by mutableStateOf(true) private set + var subItems by mutableStateOf>(emptyList()) + private set private var loaded = false val recent = RecentVideosViewModel(repository) + private fun fetchSubs() { + viewModelScope.launch { + val subs = repository.subscriptionVideos(0, 12).getOrNull()?.data ?: emptyList() + subItems = subs + net.jeena.jtubetv.ui.list.ImagePrefetcher.videoThumbnails(subs) + } + } + /** History's newest entries + resume positions from the video detail endpoint. */ fun load() { if (loaded) return @@ -63,10 +83,12 @@ class HomeRowsViewModel(private val repository: PeerTubeRepository) : ViewModel( continueItems = emptyList() loaded = true fetchContinue() + fetchSubs() recent.refresh() } private fun fetchContinue() { + fetchSubs() viewModelScope.launch { continueLoading = true val history = repository.history(0, 12).getOrNull()?.takeIf { it.isNotEmpty() } @@ -88,6 +110,7 @@ class HomeRowsViewModel(private val repository: PeerTubeRepository) : ViewModel( }.awaitAll() continueItems = items continueLoading = false + net.jeena.jtubetv.ui.list.ImagePrefetcher.videoThumbnails(items.map { it.video }) } } @@ -102,6 +125,10 @@ class HomeRowsViewModel(private val repository: PeerTubeRepository) : ViewModel( /** Paged "New videos" row content. */ class RecentVideosViewModel(private val repository: PeerTubeRepository) : PagedListViewModel() { + override fun onChunkLoaded(chunk: List) { + net.jeena.jtubetv.ui.list.ImagePrefetcher.videoThumbnails(chunk) + } + override suspend fun fetch(start: Long, count: Int): Result> = repository.localVideos(start, count).map { it.data } @@ -125,8 +152,12 @@ fun HomeRowsScreen( onOpenVideo: (VideoDto) -> Unit, restoreToken: Int = 0, epoch: Int = 0, + onOpenDrawer: () -> Unit = {}, + upToTopBar: (() -> Unit)? = null, viewModel: HomeRowsViewModel = viewModel(key = "home$epoch", factory = HomeRowsViewModel.factory), ) { + val continueRestore = androidx.compose.runtime.remember { androidx.compose.runtime.mutableIntStateOf(-1) } + val recentRestore = androidx.compose.runtime.remember { androidx.compose.runtime.mutableIntStateOf(-1) } LaunchedEffect(Unit) { viewModel.load() } LaunchedEffect(restoreToken) { if (restoreToken > 0) viewModel.refresh() } val recentItems = viewModel.recent.items @@ -149,20 +180,17 @@ fun HomeRowsScreen( ) } } else { - LazyRow( - contentPadding = PaddingValues(horizontal = 12.dp), - horizontalArrangement = Arrangement.spacedBy(4.dp), - ) { - itemsIndexed(viewModel.continueItems) { _, item -> - VideoCard( - video = item.video, - onClick = { onOpenVideo(item.video) }, - modifier = Modifier.width(ROW_CARD_WIDTH), - showPrivacy = false, - progress = item.progress, - ) - } - } + FocusScrollRow( + videos = viewModel.continueItems.map { it.video }, + progressOf = { shortUUID -> + viewModel.continueItems.firstOrNull { it.video.shortUUID == shortUUID }?.progress + }, + onOpenVideo = onOpenVideo, + onLeftAtStart = onOpenDrawer, + clickedIndex = continueRestore, + restoreToken = restoreToken, + upToTopBar = upToTopBar, + ) } } item { @@ -184,23 +212,116 @@ fun HomeRowsScreen( ) } } else { - LazyRow( - contentPadding = PaddingValues(horizontal = 12.dp), - horizontalArrangement = Arrangement.spacedBy(4.dp), - ) { - itemsIndexed(recentItems) { index, video -> - VideoCard( - video = video, - onClick = { onOpenVideo(video) }, - modifier = Modifier.width(ROW_CARD_WIDTH), - showPrivacy = false, - ) - if (index >= recentItems.size - PagedListViewModel.LOOKAHEAD) { - LaunchedEffect(index) { viewModel.recent.loadMore() } - } + FocusScrollRow( + videos = recentItems, + progressOf = { null }, + onOpenVideo = onOpenVideo, + onLeftAtStart = onOpenDrawer, + clickedIndex = recentRestore, + restoreToken = restoreToken, + ) { index, video -> + if (index >= recentItems.size - PagedListViewModel.LOOKAHEAD) { + LaunchedEffect(index) { viewModel.recent.loadMore() } } } } } + if (viewModel.subItems.isNotEmpty()) { + item { + Text( + text = "New from your subscriptions", + style = MaterialTheme.typography.titleMedium, + color = Color.White, + modifier = Modifier.padding(start = 16.dp, top = 16.dp, bottom = 4.dp), + ) + } + item { + FocusScrollRow( + videos = viewModel.subItems, + progressOf = { null }, + onOpenVideo = onOpenVideo, + onLeftAtStart = { }, + ) + } + } } -} \ No newline at end of file +} +/** + * Horizontal card row with eased scrolling: when focus moves to a card outside the + * viewport, the row animates it to the left edge (SmartTube behaviour) instead of + * the abrupt jump the built-in lazy scroll produces. + */ +@Composable +fun FocusScrollRow( + videos: List, + progressOf: (String) -> Float?, + onOpenVideo: (VideoDto) -> Unit, + onLeftAtStart: () -> Unit, + clickedIndex: androidx.compose.runtime.MutableIntState? = null, // set on card click + restoreToken: Int = 0, // bumped when playback ends + upToTopBar: (() -> Unit)? = null, // first content row only + afterItem: @Composable (index: Int, video: VideoDto) -> Unit = { _, _ -> }, +) { + val rowState = rememberLazyListState() + val focusRequesters = remember { HashMap() } + var focusedIndex by remember { androidx.compose.runtime.mutableStateOf(-1) } + // BACK from playback: scroll to + focus the card that was opened (user request). + LaunchedEffect(restoreToken) { + if (restoreToken > 0) { + val target = clickedIndex?.intValue ?: -1 + if (target > 0) kotlinx.coroutines.delay(600) // let the refresh settle + if (target >= 0) { + runCatching { + rowState.scrollToItem((target - 1).coerceAtLeast(0)) + focusRequesters[target]?.requestFocus() + } + } + } + } + // On app start and destination switch: focus the FIRST card automatically + // (user request — otherwise invisible focus confuses "where am I"). + LaunchedEffect(videos.isNotEmpty()) { + if (videos.isNotEmpty() && focusedIndex == -1) { + kotlinx.coroutines.delay(150) // let images/measuring settle + runCatching { focusRequesters[0]?.requestFocus() } + } + } + LaunchedEffect(focusedIndex) { + if (focusedIndex > 0) { + val visible = rowState.layoutInfo.visibleItemsInfo + val target = visible.firstOrNull { it.index == focusedIndex } + // animate only when the focused card is not (fully) on screen + val notFullyVisible = target == null || + target.offset < 0 || + target.offset + (target.size / 2) > rowState.layoutInfo.viewportEndOffset + if (notFullyVisible) rowState.animateScrollToItem(focusedIndex) + } + } + LazyRow( + state = rowState, + contentPadding = PaddingValues(horizontal = 12.dp), + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + itemsIndexed(videos, key = { _, video -> "v" + video.id }) { index, video -> + val fr = remember { FocusRequester() } + focusRequesters[index] = fr + VideoCard( + video = video, + onClick = { + clickedIndex?.intValue = index + onOpenVideo(video) + }, + modifier = Modifier + .width(rowCardWidth()) + .focusRequester(fr), + showPrivacy = false, + compact = true, + progress = progressOf(video.shortUUID), + onLeftAtStart = if (index == 0) onLeftAtStart else null, + onUpToTopBar = upToTopBar, + onFocused = { focusedIndex = index }, + ) + afterItem(index, video) + } + } +} diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt index 9bcf9a6..b031715 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt @@ -1,38 +1,61 @@ package net.jeena.jtubetv.ui.screens +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.focusable +import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.List +import androidx.compose.material.icons.filled.AccountCircle import androidx.compose.material.icons.filled.History import androidx.compose.material.icons.filled.Logout -import androidx.compose.material.icons.filled.Subscriptions -import androidx.compose.material.icons.filled.Search -import androidx.compose.material.icons.filled.VideoLibrary import androidx.compose.material.icons.filled.PersonalVideo +import androidx.compose.material.icons.filled.Search +import androidx.compose.material.icons.filled.Subscriptions +import androidx.compose.material.icons.filled.VideoLibrary import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.type +import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.unit.dp import androidx.tv.material3.Icon -import androidx.tv.material3.NavigationDrawer -import androidx.tv.material3.NavigationDrawerItem import androidx.tv.material3.Text +import net.jeena.jtubetv.AppGraph import net.jeena.jtubetv.data.api.VideoDto import net.jeena.jtubetv.ui.AppViewModel import net.jeena.jtubetv.ui.list.ListSource import net.jeena.jtubetv.ui.screens.list.VideoListScreen -import androidx.activity.compose.BackHandler +import net.jeena.jtubetv.ui.screens.list.dpadCenterActivatable enum class Destination(val title: String) { Home("Home"), @@ -43,16 +66,24 @@ enum class Destination(val title: String) { History("History"), } -/** Home = sidebar (D-pad navigable) + content pane. The player renders as a - * fullscreen overlay: the list beneath stays composed, so its scroll position and - * focused card survive BACK (couch users don't want to re-navigate from the top). */ +/** + * Home = SmartTube-style: hidden menu, red round search + avatar in a top bar, + * full-width rows/list content. The menu drawer slides in when wanted (avatar or + * the search/BACK flows) and everything is key(epoch) so an account switch + * rebuilds all state. + */ @Composable fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.viewModel()) { val epoch by viewModel.sessionEpoch.collectAsState() var destination by rememberSaveable { mutableStateOf(Destination.Home) } var channelDetails by rememberSaveable { mutableStateOf(null) } // handle - var playingVideo by rememberSaveable { mutableStateOf(null) } // shortUUID + // NOT saveable: launching the app should never resume a half-watched player session. + var playingVideo by remember { mutableStateOf(null) } // shortUUID var restoreToken by rememberSaveable { mutableStateOf(0) } // increments when playback ends + var drawerOpen by rememberSaveable { mutableStateOf(false) } + val context = androidx.compose.ui.platform.LocalContext.current + var lastBackAt by rememberSaveable { mutableStateOf(0L) } + val searchFocus = remember { FocusRequester() } // After BACK from the player: bump the restore token so lists re-focus the opened // card and re-fetch positions (UX report BUG-3 + BUG-7). @@ -60,86 +91,71 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi if (playingVideo == null && restoreToken >= 1) restoreToken++ } - // Channel drilldown hides the sidebar; remote BACK must return to the channels list. - BackHandler(enabled = playingVideo == null && channelDetails != null) { + // BACK order (TV standard): player (own handler) → drawer close → channel + // drilldown → non-Home destination → Home; from Home: double-press exits. + BackHandler(enabled = drawerOpen && playingVideo == null) { + drawerOpen = false + runCatching { searchFocus.requestFocus() } + } + BackHandler(enabled = !drawerOpen && playingVideo == null && channelDetails != null) { channelDetails = null } + BackHandler(enabled = !drawerOpen && playingVideo == null && channelDetails == null) { + if (destination != Destination.Home) { + channelDetails = null + destination = Destination.Home + } else { + val now = System.currentTimeMillis() + if (now - lastBackAt < 2500) { + (context as? android.app.Activity)?.finish() + return@BackHandler + } + lastBackAt = now + android.widget.Toast.makeText(context, "Press BACK again to exit", android.widget.Toast.LENGTH_SHORT).show() + } + } - Box(modifier = Modifier.fillMaxSize()) { + Box( + modifier = Modifier + .fillMaxSize() + .onPreviewKeyEvent { ke -> + // Keyboard/scrcpy: Esc behaves like BACK for drawer + drilldowns + // (the player consumes Esc itself when playing). + val native = ke.nativeKeyEvent + if (native.action == android.view.KeyEvent.ACTION_DOWN && + native.keyCode == android.view.KeyEvent.KEYCODE_ESCAPE && + playingVideo == null + ) { + when { + drawerOpen -> { drawerOpen = false; true } + channelDetails != null -> { channelDetails = null; true } + else -> false + } + } else false + }, + ) { androidx.compose.runtime.key(epoch) { - if (destination == Destination.Channels && channelDetails != null) { - androidx.compose.foundation.layout.Box( + Column { + // SmartTube-style top bar: red round search + avatar opening the menu. + TopBar( + onSearchClick = { destination = Destination.Search; channelDetails = null }, + onAccountClick = { drawerOpen = !drawerOpen }, + searchFocus = searchFocus, + ) + Box( modifier = Modifier .fillMaxSize() - // TV overscan safety margins (list content, not the player). - .padding(horizontal = 32.dp), + // TV overscan safety margins on the content pane. + .padding(start = 8.dp, end = 32.dp, top = 8.dp), ) { - VideoListScreen( - source = ListSource.Channel(channelDetails!!, channelDetails!!), - onOpenVideo = { playingVideo = it.shortUUID }, - restoreToken = restoreToken, - epoch = epoch, - ) - } - } else { - NavigationDrawer(drawerContent = { - androidx.compose.foundation.layout.Column( - modifier = Modifier.width(220.dp).padding(vertical = 16.dp), - ) { - Text( - text = "JTube TV", - modifier = Modifier.padding(start = 28.dp, bottom = 16.dp), - style = androidx.tv.material3.MaterialTheme.typography.headlineSmall, - color = androidx.compose.ui.graphics.Color.White, - ) - Destination.entries.forEach { dest -> - NavigationDrawerItem( - selected = dest == destination, - onClick = { - destination = dest - channelDetails = null - }, - leadingContent = { - Icon(imageVector = dest.icon(), contentDescription = null) - }, - content = { Text(dest.title) }, - ) - } - val signOutContext = androidx.compose.ui.platform.LocalContext.current - var lastSignOutTap by remember { mutableStateOf(0L) } - NavigationDrawerItem( - selected = false, - onClick = { - val now = System.currentTimeMillis() - if (now - lastSignOutTap < 3000) { - viewModel.logout() - } else { - lastSignOutTap = now - android.widget.Toast.makeText( - signOutContext, - "Press again to sign out", - android.widget.Toast.LENGTH_SHORT, - ).show() - } - }, - leadingContent = { - Icon(imageVector = Icons.Filled.Logout, contentDescription = null) - }, - content = { Text("Sign out") }, - ) - } - }) { - androidx.compose.foundation.layout.Box( - modifier = Modifier - .fillMaxSize() - // TV overscan safety margins on the content pane. - .padding(start = 8.dp, end = 32.dp, top = 16.dp), - ) { when (destination) { Destination.Home -> HomeRowsScreen( onOpenVideo = { playingVideo = it.shortUUID }, + restoreToken = restoreToken, epoch = epoch, + onOpenDrawer = { drawerOpen = true }, + upToTopBar = { runCatching { searchFocus.requestFocus() } }, ) Destination.MyVideos -> VideoListScreen( @@ -147,10 +163,13 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi onOpenVideo = { playingVideo = it.shortUUID }, restoreToken = restoreToken, epoch = epoch, + onOpenDrawer = { drawerOpen = true }, + upToTopBar = { runCatching { searchFocus.requestFocus() } }, ) Destination.Channels -> ChannelsScreen( onOpenChannel = { handle -> channelDetails = handle }, epoch = epoch, + onOpenDrawer = { drawerOpen = true }, ) Destination.Search -> VideoListScreen( @@ -158,13 +177,16 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi onOpenVideo = { playingVideo = it.shortUUID }, restoreToken = restoreToken, epoch = epoch, + onOpenDrawer = { drawerOpen = true }, + upToTopBar = { runCatching { searchFocus.requestFocus() } }, ) Destination.Subscriptions -> - VideoListScreen( - source = ListSource.Subscriptions, + SubscriptionRowsScreen( onOpenVideo = { playingVideo = it.shortUUID }, restoreToken = restoreToken, epoch = epoch, + onOpenDrawer = { drawerOpen = true }, + upToTopBar = { runCatching { searchFocus.requestFocus() } }, ) Destination.History -> VideoListScreen( @@ -172,11 +194,27 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi onOpenVideo = { playingVideo = it.shortUUID }, restoreToken = restoreToken, epoch = epoch, + onOpenDrawer = { drawerOpen = true }, + upToTopBar = { runCatching { searchFocus.requestFocus() } }, ) } - } } } + } + + // Slide-in menu drawer (SmartTube style: hidden until wanted). + if (drawerOpen) { + MenuDrawer( + selected = destination, + onSelect = { + destination = it + channelDetails = null + drawerOpen = false + }, + onSignOut = { viewModel.logout() }, + onDismiss = { drawerOpen = false }, + ) + } if (playingVideo != null) { PlayerScreen( @@ -184,11 +222,10 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi onBack = { playingVideo = null }, ) } - } } } -private fun Destination.icon(): androidx.compose.ui.graphics.vector.ImageVector = +private fun Destination.icon(): ImageVector = when (this) { Destination.Home -> Icons.Filled.VideoLibrary Destination.MyVideos -> Icons.Filled.PersonalVideo @@ -196,4 +233,241 @@ private fun Destination.icon(): androidx.compose.ui.graphics.vector.ImageVector Destination.Search -> Icons.Filled.Search Destination.Subscriptions -> Icons.Filled.Subscriptions Destination.History -> Icons.Filled.History - } \ No newline at end of file + } + +/** Top bar: red round search + account avatar (opens the menu), SmartTube-style. */ +@Composable +private fun TopBar( + onSearchClick: () -> Unit, + onAccountClick: () -> Unit, + searchFocus: FocusRequester, + modifier: Modifier = Modifier, +) { + Row( + modifier = modifier + .fillMaxWidth() + .padding(horizontal = 24.dp, vertical = 10.dp), + horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(16.dp), + ) { + RoundTopButton( + bg = Color(0xFFCE2B2B), + icon = Icons.Filled.Search, + desc = "Search", + onClick = onSearchClick, + focusRequester = searchFocus, + ) + // "Who is logged in" — account button: avatar circle + display name (SmartTube). + val accountFocused = remember { mutableStateOf(false) } + Row( + modifier = Modifier + .onFocusChanged { accountFocused.value = it.isFocused } + .background(Color.Transparent) + .then( + if (accountFocused.value) Modifier.border(3.dp, Color.White, CircleShape) + else Modifier + ) + .focusable() + .dpadCenterActivatable(onAccountClick) + .clickable(onClick = onAccountClick), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(8.dp), + ) { + val avatarUrl = AppGraph.tokenStore.userAvatarUrl + if (avatarUrl != null) { + coil.compose.AsyncImage( + model = coil.request.ImageRequest.Builder(androidx.compose.ui.platform.LocalContext.current) + .data(avatarUrl) + .size(96) + .build(), + contentDescription = "Account", + modifier = Modifier + .size(44.dp) + .clip(CircleShape) + .background(Color(0xFF262626)), + ) + } else { + Box( + modifier = Modifier + .size(44.dp) + .clip(CircleShape) + .background(Color(0xFF262626)), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = Icons.Filled.AccountCircle, + contentDescription = "Account", + tint = Color(0xFFCCCCCC), + ) + } + } + Text( + text = AppGraph.tokenStore.userDisplayName + ?: AppGraph.tokenStore.username?.substringBefore('@') ?: "Account", + color = Color(0xFFB0B0B0), + style = androidx.compose.material3.MaterialTheme.typography.bodyMedium, + modifier = Modifier.padding(end = 8.dp), + ) + } + Spacer(modifier = Modifier.weight(1f)) + Text( + text = "JTube TV", + color = Color(0xFF9A9A9A), + style = androidx.compose.material3.MaterialTheme.typography.titleMedium, + modifier = Modifier.align(Alignment.CenterVertically), + ) + } +} + +@Composable +private fun RoundTopButton( + bg: Color, + icon: ImageVector, + desc: String, + onClick: () -> Unit, + focusRequester: FocusRequester? = null, +) { + var focused by remember { mutableStateOf(false) } + Box( + modifier = Modifier + .size(44.dp) + .clip(CircleShape) + .onFocusChanged { focused = it.isFocused } + .background(bg) + .then( + if (focused) Modifier.border( + 3.dp, Color.White, CircleShape + ) else Modifier + ) + .then(if (focusRequester != null) Modifier.focusRequester(focusRequester) else Modifier) + .focusable() + .dpadCenterActivatable(onClick) + .clickable(onClick = onClick), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = icon, + contentDescription = desc, + tint = Color.White, + ) + } +} + +/** + * Slide-in menu drawer: destination list + sign out, readable on a dark background + * (UX report: unselected grey was illegible). Selected item gets the red accent. + */ +@Composable +private fun MenuDrawer( + selected: Destination, + onSelect: (Destination) -> Unit, + onSignOut: () -> Unit, + onDismiss: () -> Unit, + modifier: Modifier = Modifier, +) { + val drawerFocus = remember { FocusRequester() } + LaunchedEffect(Unit) { runCatching { drawerFocus.requestFocus() } } + val signOutContext = androidx.compose.ui.platform.LocalContext.current + var lastSignOutTap by remember { mutableStateOf(0L) } + Row(modifier = modifier.fillMaxSize()) { + Column( + modifier = Modifier + .width(240.dp) + .fillMaxSize() + .background(Color(0xFF111111)) + .padding(vertical = 24.dp) + .onPreviewKeyEvent { ke -> + // RIGHT from the drawer closes it; focus returns to the top bar. + if (ke.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN && + ke.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_DPAD_RIGHT + ) { + onDismiss() + true + } else false + }, + ) { + Text( + text = "JTube TV", + color = Color.White, + style = androidx.compose.material3.MaterialTheme.typography.headlineSmall, + modifier = Modifier.padding(start = 28.dp, bottom = 20.dp), + ) + Destination.entries.forEachIndexed { index, dest -> + MenuDrawerItem( + icon = dest.icon(), + label = dest.title, + selected = dest == selected, + onClick = { onSelect(dest) }, + modifier = if (index == 0) Modifier.focusRequester(drawerFocus) else Modifier, + ) + } + Spacer(modifier = Modifier.weight(1f)) + MenuDrawerItem( + icon = Icons.Filled.Logout, + label = "Sign out", + selected = false, + onClick = { + if (System.currentTimeMillis() - lastSignOutTap < 3000) { + onSignOut() + } else { + lastSignOutTap = System.currentTimeMillis() + android.widget.Toast.makeText( + signOutContext, + "Press again to sign out", + android.widget.Toast.LENGTH_SHORT, + ).show() + } + }, + modifier = Modifier, + ) + } + // tap/click outside closes the drawer + Box( + modifier = Modifier + .weight(1f) + .fillMaxSize() + .pointerInput(Unit) { detectTapGestures { onDismiss() } }, + ) + } +} + +@Composable +private fun MenuDrawerItem( + icon: ImageVector, + label: String, + selected: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier, +) { + val focusManager = androidx.compose.ui.platform.LocalFocusManager.current + var focused by remember { mutableStateOf(false) } + val labelColor = when { + focused -> Color(0xFF101010) + selected -> Color(0xFFE0E0E0) + else -> Color(0xFFB0B0B0) + } + Row( + modifier = modifier + .fillMaxWidth() + .onFocusChanged { focused = it.isFocused } + .background( + when { + focused -> Color.White + selected -> Color(0x33CE2B2B) + else -> Color.Transparent + } + ) + .focusable() + .dpadCenterActivatable(onClick) + .clickable(onClick = onClick) + .padding(horizontal = 24.dp, vertical = 14.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(14.dp), + ) { + Icon(imageVector = icon, contentDescription = null, tint = labelColor) + Text( + text = label, + color = labelColor, + style = androidx.compose.material3.MaterialTheme.typography.bodyLarge, + ) + } +} \ No newline at end of file diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/PlayerScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/PlayerScreen.kt index 7e27467..6c21ee1 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/PlayerScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/PlayerScreen.kt @@ -1,12 +1,22 @@ package net.jeena.jtubetv.ui.screens +import android.net.Uri +import android.os.Handler +import android.os.Looper +import android.view.KeyEvent +import android.view.ViewGroup +import android.widget.Toast import androidx.activity.compose.BackHandler import androidx.compose.foundation.background import androidx.compose.foundation.focusable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text @@ -15,17 +25,20 @@ import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.key.type +import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp -import android.widget.Toast -import androidx.activity.compose.BackHandler import androidx.compose.ui.viewinterop.AndroidView import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider @@ -33,7 +46,6 @@ import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewmodel.compose.viewModel import androidx.media3.common.MediaItem import androidx.media3.common.MimeTypes -import androidx.media3.common.PlaybackException import androidx.media3.common.Player import androidx.media3.datasource.DataSource import androidx.media3.datasource.DefaultDataSource @@ -46,10 +58,9 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import net.jeena.jtubetv.AppGraph +import net.jeena.jtubetv.data.PeerTubeRepository import net.jeena.jtubetv.data.api.VideoDetailDto import net.jeena.jtubetv.data.auth.TokenStore -import net.jeena.jtubetv.data.PeerTubeRepository -import android.net.Uri sealed interface PlayerUiState { data object Loading : PlayerUiState @@ -58,7 +69,7 @@ sealed interface PlayerUiState { val playUrl: String, val isHls: Boolean, val fileToken: String? = null, - /** If the server has a stored position, show "Resuming at …" on start. */ + /** Server-recorded position; resume unless (almost) finished. */ val resumeAtSeconds: Int? = null, ) : PlayerUiState data class Error(val message: String) : PlayerUiState @@ -78,7 +89,7 @@ class PlayerViewModel( fun load(shortUuid: String) { currentShortUuid = shortUuid viewModelScope.launch { - // Freshen the token before media requests hit it (triggers refresh on 401). + // Freshen the token before media requests hit it (refresh on 401 via authenticator). repository.me() val result = repository.video(shortUuid, userHistory = true) result.fold( @@ -87,9 +98,8 @@ class PlayerViewModel( if (play == null) { _state.value = PlayerUiState.Error("No playable stream found") } else { - // Non-public media may need a short-lived file token instead of - // (or in addition to) the Bearer header — matters on instances - // whose object-storage bucket rejects anonymous requests. + // Non-public media may need a short-lived file token — matters on + // instances whose object-storage bucket rejects anonymous requests. var token: String? = null if (detail.privacy?.id != 1) { token = repository.videoToken(detail.shortUUID).getOrNull() @@ -106,14 +116,7 @@ class PlayerViewModel( } } - fun currentUrl(): String? = (_state.value as? PlayerUiState.Ready)?.playUrl - fun isInstanceMedia(): Boolean { - val url = currentUrl() ?: return false - val base = tokenStore.baseUrl?.removePrefix("https://")?.removePrefix("http://")?.substringBefore('/') - return url.substringAfter("://").substringBefore('/') == base - } - - /** Send the position once more when leaving playback (avoids losing up to 20 s). */ + /** Sends a final watching report (on exit / periodic), so positions never go stale. */ fun persistExit(shortUuid: String, currentTimeSeconds: Int) { viewModelScope.launch { repository.reportWatching(shortUuid, currentTimeSeconds) } } @@ -124,6 +127,12 @@ class PlayerViewModel( load(uuid) } + /** Bearer only for instance-served media — never sent to storage third parties. */ + fun isInstanceMedia(url: String): Boolean { + val baseHost = tokenStore.baseUrl?.substringAfter("://")?.substringBefore('/') + return baseHost != null && url.substringAfter("://").substringBefore('/') == baseHost + } + companion object { fun factory(repository: PeerTubeRepository, tokenStore: TokenStore): ViewModelProvider.Factory = object : ViewModelProvider.Factory { @@ -135,17 +144,18 @@ class PlayerViewModel( } /** - * Fullscreen ExoPlayer that actually accepts the remote (UX report BUG-2): the focus - * lives on a Compose key handler — CENTER toggles play/pause, LEFT/RIGHT seek ±10 s, - * other keys show the controller. The player is an overlay; BACK restores the list - * underneath (BUG-3) and sends a final watching report (BUG-6). + * Fullscreen ExoPlayer that accepts the remote (UX report BUG-2): focus lives on a + * Compose key handler — OK toggles play/pause, LEFT/RIGHT seek ±10 s, anything else + * shows the controller. No controller flash on start (user request); when paused an + * info overlay (channel, title, views, date) appears instead. BACK sends a final + * watching report and returns to the list (BUG-3/6). */ @Composable fun PlayerScreen( shortUuid: String, onBack: () -> Unit, viewModel: PlayerViewModel = viewModel( - key = shortUuid, + key = "player$shortUuid", factory = PlayerViewModel.factory(AppGraph.repository, AppGraph.tokenStore), ), ) { @@ -184,7 +194,7 @@ private fun PlayerError(message: String, viewModel: PlayerViewModel, onBack: () color = MaterialTheme.colorScheme.onSurface, style = MaterialTheme.typography.titleMedium, ) - androidx.compose.material3.Text( + Text( message, color = Color(0xFF8A8A8A), style = MaterialTheme.typography.bodySmall, @@ -201,7 +211,6 @@ private fun PlayerError(message: String, viewModel: PlayerViewModel, onBack: () Toast.makeText(context, "Back to the list", Toast.LENGTH_SHORT).show() onBack() }, - modifier = Modifier.focusable(), ) { Text("Close") } } } @@ -212,7 +221,8 @@ internal fun friendlyMediaError(message: String): String = message.contains("Unable to resolve", ignoreCase = true) -> "Can't reach the server — check the connection" message.contains("404") -> "This doesn't look like a PeerTube instance" - message.contains("401") || message.contains("403") -> "Not allowed to watch this video — try signing in again" + message.contains("401") || message.contains("403") -> + "Not allowed to watch this video — try signing in again" message.contains("connect", ignoreCase = true) -> "Can't reach the server — check your connection" else -> "Playback error" } @@ -226,24 +236,29 @@ private fun PlayerSurface( ) { val context = LocalContext.current val keyFocus = remember { FocusRequester() } + var paused by remember { mutableStateOf(false) } + var playerViewRef by remember { mutableStateOf(null) } + val player = remember { - // Bearer headers only for instance-served media; never send the user's token to - // third-party storage hosts (UX report BUG-9). The file token is appended per - // request (incl. variant playlists + segments) via ResolvingDataSource. - val hostIsInstance = isInstanceHost(s.playUrl, AppGraph.tokenStore.baseUrl) + val hostIsInstance = viewModel.isInstanceMedia(s.playUrl) val headers = if (hostIsInstance && AppGraph.tokenStore.accessToken != null) { mapOf("Authorization" to "Bearer ${AppGraph.tokenStore.accessToken}") } else emptyMap() val http = DefaultHttpDataSource.Factory() .setAllowCrossProtocolRedirects(true) .setDefaultRequestProperties(headers) - val resolving = ResolvingDataSource.Factory(http as androidx.media3.datasource.HttpDataSource.Factory) { dataSpec -> - val token = s.fileToken ?: return@Factory dataSpec - val uri = dataSpec.uri.buildUpon() - .appendQueryParameter("videoFileToken", token) - .build() - dataSpec.buildUpon().setUri(uri).build() - } + val resolving = ResolvingDataSource.Factory( + http, + object : ResolvingDataSource.Resolver { + override fun resolveDataSpec(dataSpec: androidx.media3.datasource.DataSpec): androidx.media3.datasource.DataSpec { + val token = s.fileToken ?: return dataSpec + val uri = dataSpec.uri.buildUpon() + .appendQueryParameter("videoFileToken", token) + .build() + return dataSpec.buildUpon().setUri(uri).build() + } + }, + ) val dataSource: DataSource.Factory = DefaultDataSource.Factory(context, resolving) ExoPlayer.Builder(context) .setMediaSourceFactory(DefaultMediaSourceFactory(dataSource)) @@ -257,33 +272,44 @@ private fun PlayerSurface( .setUri(s.playUrl) .setMimeType(if (s.isHls) MimeTypes.APPLICATION_M3U8 else MimeTypes.VIDEO_MP4) .build() - player.setMediaItem(item) - s.resumeAtSeconds?.let { - player.setMediaItem(item, it * 1000L) + val resume = s.resumeAtSeconds + if (resume != null) { + player.setMediaItem(item, resume * 1000L) Toast.makeText( context, - "Resuming at ${it / 60}:${"%02d".format(it % 60)}", + "Resuming at " + resume / 60 + ":" + "%02d".format(resume % 60), Toast.LENGTH_LONG, ).show() - } ?: player.setMediaItem(item) + } else { + player.setMediaItem(item) + } player.prepare() player.playWhenReady = true + player.addListener(object : Player.Listener { + override fun onIsPlayingChanged(isPlaying: Boolean) { + paused = !isPlaying + if (!isPlaying) playerViewRef?.hideController() // overlay replaces the bar + } + }) + // Controller does not flash at start; only UP/DOWN/other keys reveal it. + playerViewRef?.hideController() onDispose { viewModel.persistExit(shortUuid, (player.currentPosition / 1000).toInt()) player.release() } } - // Single Handler instance; leaks were caused by constructing a second one to remove (BUG-8). + // Single handler for the periodic watch report (the old code leaked one per video). DisposableEffect(player) { var lastReported = 0L - val handler = android.os.Handler(android.os.Looper.getMainLooper()) + val handler = Handler(Looper.getMainLooper()) val runnable = object : Runnable { override fun run() { if (player.isPlaying) { val now = System.currentTimeMillis() val position = player.currentPosition - if (position >= 5_000 && now - lastReported >= 20_000) { + val sinceLast = now - lastReported + if (position >= 5_000 && sinceLast >= 20_000) { viewModel.persistExit(shortUuid, (position / 1000).toInt()) lastReported = now } @@ -295,52 +321,152 @@ private fun PlayerSurface( onDispose { handler.removeCallbacks(runnable) } } - val handleKey: (android.view.KeyEvent) -> Boolean = { event -> - if (event.action == android.view.KeyEvent.ACTION_DOWN) { + val handleKey: (KeyEvent) -> Boolean = { event -> + if (event.action == KeyEvent.ACTION_DOWN) { when (event.keyCode) { - android.view.KeyEvent.KEYCODE_DPAD_CENTER, - android.view.KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, - -> { + // scrcpy/keyboard users: Esc = back (Ctrl+B relies on the mod binding) + KeyEvent.KEYCODE_ESCAPE, KeyEvent.KEYCODE_BACK -> { + onBack() + true + } + KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE -> { player.playWhenReady = !player.playWhenReady true } - android.view.KeyEvent.KEYCODE_DPAD_LEFT, android.view.KeyEvent.KEYCODE_MEDIA_REWIND -> { + KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_MEDIA_REWIND -> { player.seekTo((player.currentPosition - 10_000).coerceAtLeast(0)) true } - android.view.KeyEvent.KEYCODE_DPAD_RIGHT, android.view.KeyEvent.KEYCODE_MEDIA_FAST_FORWARD -> { + KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_MEDIA_FAST_FORWARD -> { player.seekTo(player.currentPosition + 10_000) true } - else -> false // UP/DOWN etc.: show the controller + else -> false } } else false } - AndroidView( - factory = { ctx -> - PlayerView(ctx).apply { - useController = true - this.player = player - controllerShowTimeoutMs = 4000 - isFocusable = false - descendantFocusability = android.view.ViewGroup.FOCUS_BLOCK_DESCENDANTS - } - }, - update = { }, + Box( modifier = Modifier .fillMaxSize() .background(Color.Black) .focusRequester(keyFocus) .focusable() - .onPreviewKeyEvent { event -> - handleKey(event.nativeKeyEvent) + .onPreviewKeyEvent { ke -> + val handled = handleKey(ke.nativeKeyEvent) + if (!handled) { + // UP/DOWN etc. reveal the controls briefly + playerViewRef?.showController() + true + } else { + if (player.playWhenReady) playerViewRef?.hideController() + true + } }, - ) + ) { + AndroidView( + factory = { ctx -> + PlayerView(ctx).apply { + useController = true + this.player = player + isFocusable = false + descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS + playerViewRef = this + } + }, + modifier = Modifier.fillMaxSize(), + ) + // Paused → info overlay with channel/title/views/date (user request). + if (paused) PauseOverlay(s.detail, player, Modifier.align(Alignment.BottomCenter)) + } } -private fun isInstanceHost(url: String, baseUrl: String?): Boolean { - val urlHost = url.substringAfter("://").substringBefore('/') - val baseHost = baseUrl?.substringAfter("://")?.substringBefore('/') - return baseHost != null && urlHost == baseHost +/** Info panel while paused: channel (icon + name), title, views, upload date, position. */ +@Composable +private fun PauseOverlay(detail: VideoDetailDto, player: ExoPlayer, modifier: Modifier = Modifier) { + val positionText = "%d:%02d".format(player.currentPosition / 60000, (player.currentPosition / 1000) % 60) + Row( + modifier = modifier + .fillMaxWidth() + .background(Color(0xB3000000)) + .padding(20.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + val avatar = detail.channel.avatars.maxByOrNull { it.width } + if (avatar != null) { + coil.compose.AsyncImage( + model = AppGraph.repository.absoluteUrl(avatar.fileUrl ?: avatar.path), + contentDescription = null, + contentScale = ContentScale.Crop, + modifier = Modifier + .size(64.dp) + .clip(CircleShape), + ) + } + Column( + modifier = Modifier + .weight(1f) + .padding(start = 16.dp), + ) { + Text( + text = detail.name, + color = Color.White, + style = MaterialTheme.typography.titleLarge, + maxLines = 2, + ) + Text( + text = detail.channel.displayName, + color = Color(0xFFCCCCCC), + style = MaterialTheme.typography.bodyMedium, + ) + Text( + text = formatViews(detail.views) + " · " + formatAge(detail.publishedAt), + color = Color(0xFF9A9A9A), + style = MaterialTheme.typography.bodySmall, + ) + } + Column(horizontalAlignment = Alignment.End) { + Text( + text = positionText + " · " + formatDuration(detail.duration), + color = Color(0xFFCCCCCC), + style = MaterialTheme.typography.bodyMedium, + ) + Text(text = "Paused", color = Color(0xFFCE2B2B), style = MaterialTheme.typography.labelLarge) + } + } +} + +private fun formatViews(views: Long): String = + when { + views >= 1_000_000 -> "%.1fM views".format(views / 1_000_000.0) + views >= 1_000 -> "%.1fK views".format(views / 1_000.0) + views == 1L -> "1 view" + else -> "$views views" + } + +private fun formatAge(iso: String?): String { + if (iso.isNullOrBlank()) return "" + return try { + val age = java.time.Duration.between(java.time.Instant.parse(iso), java.time.Instant.now()) + val days = age.toDays() + when { + days >= 365 -> "${days / 365}y ago" + days >= 30 -> "${days / 30}mo ago" + days >= 1 -> "${days}d ago" + age.toHours() >= 1 -> "${age.toHours()}h ago" + else -> "just now" + } + } catch (e: java.time.format.DateTimeParseException) { + "" + } +} + +private fun formatDuration(seconds: Int): String { + val h = seconds / 3600 + val m = (seconds % 3600) / 60 + val s = seconds % 60 + return when { + h > 0 -> "%d:%02d:%02d".format(h, m, s) + else -> "%d:%02d".format(m, s) + } } \ No newline at end of file diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/SetupScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/SetupScreen.kt index 3f4fc88..a41f989 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/SetupScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/SetupScreen.kt @@ -28,6 +28,7 @@ import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.platform.LocalClipboardManager import androidx.compose.ui.unit.dp import kotlinx.coroutines.flow.StateFlow +import net.jeena.jtubetv.ui.screens.list.dpadCenterActivatable /** * Feature 0: ask for instance URL + credentials once. The password is used only for @@ -164,9 +165,6 @@ fun SetupScreen( Text(message.value ?: localError.value!!, color = MaterialTheme.colorScheme.error) } Button( - // Deliberately always focusable: on TV a permanently disabled button - // is unreachable and leaves the user stuck without feedback (UX review). - // Validation happens on press with an inline message instead. onClick = { when { url.value.isBlank() || username.value.isBlank() || password.value.isBlank() -> @@ -178,7 +176,20 @@ fun SetupScreen( } }, enabled = !busy.value, - modifier = Modifier.fillMaxWidth(), + modifier = Modifier + .fillMaxWidth() + .dpadCenterActivatable( + onClick = { + when { + url.value.isBlank() || username.value.isBlank() || password.value.isBlank() -> + localError.value = "All fields are required" + else -> { + localError.value = null + onLogin(url.value, username.value, password.value) + } + } + }, + ), ) { if (busy.value) { CircularProgressIndicator(Modifier.width(20.dp)) diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/SubscriptionsScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/SubscriptionsScreen.kt new file mode 100644 index 0000000..d6e7eff --- /dev/null +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/SubscriptionsScreen.kt @@ -0,0 +1,170 @@ +package net.jeena.jtubetv.ui.screens + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.unit.dp +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewmodel.compose.viewModel +import coil.compose.AsyncImage +import net.jeena.jtubetv.AppGraph +import net.jeena.jtubetv.data.api.Avatar +import net.jeena.jtubetv.data.api.VideoChannelSummary +import net.jeena.jtubetv.data.api.VideoDto +import net.jeena.jtubetv.ui.list.ImagePrefetcher +import net.jeena.jtubetv.ui.list.PagedListViewModel + +/** + * Subscriptions, SmartTube-style: the feed grouped by channel — one row per + * channel, newest-first within the row, row header = channel avatar + name. + * Card sizes match the Home rows exactly. + */ +class SubscriptionRowsViewModel( + private val repository: net.jeena.jtubetv.data.PeerTubeRepository = AppGraph.repository, +) : PagedListViewModel() { + + override fun onChunkLoaded(chunk: List) { + ImagePrefetcher.videoThumbnails(chunk) + } + + override suspend fun fetch(start: Long, count: Int): Result> = + repository.subscriptionVideos(start, count).map { it.data } +} + +private data class SubGroup( + val channel: VideoChannelSummary, + val startIndex: Int, + val videos: List, +) + +private fun buildGroups(items: List): List { + val groups = mutableListOf() + items.forEachIndexed { index, video -> + val last = groups.lastOrNull() + val same = last != null && + last.channel.name == video.channel.name && + last.channel.host == video.channel.host + if (same) { + groups[groups.lastIndex] = last!!.copy(videos = last.videos + video) + } else { + groups += SubGroup(video.channel, index, listOf(video)) + } + } + return groups +} + +@Composable +fun SubscriptionRowsScreen( + onOpenVideo: (VideoDto) -> Unit, + restoreToken: Int = 0, + epoch: Int = 0, + onOpenDrawer: () -> Unit = {}, + upToTopBar: (() -> Unit)? = null, + viewModel: SubscriptionRowsViewModel = viewModel( + key = "subsrows$epoch", + factory = object : ViewModelProvider.Factory { + @Suppress("UNCHECKED_CAST") + override fun create(modelClass: Class): T = + SubscriptionRowsViewModel() as T + }, + ), +) { + val items = viewModel.items + LaunchedEffect(Unit) { if (items.isEmpty()) viewModel.loadMore(force = true) } + LaunchedEffect(restoreToken) { if (restoreToken > 0) viewModel.refresh() } + + if (items.isEmpty()) { + Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + if (viewModel.initialError != null) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Text("Could not load subscriptions", color = MaterialTheme.colorScheme.error) + Text( + viewModel.initialError ?: "", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + androidx.compose.material3.Button(onClick = { viewModel.retryInitial() }) { + Text("Retry") + } + } + } else { + androidx.compose.material3.CircularProgressIndicator() + } + } + return + } + + val groups = remember(items) { buildGroups(items) } + + LazyColumn(Modifier.fillMaxSize()) { + groups.forEach { group -> + item(key = "subrowhead" + group.channel.name + "@" + group.channel.host + group.startIndex) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.padding(start = 16.dp, top = 12.dp, bottom = 4.dp), + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + val avatar = group.channel.avatars.maxByOrNull { it.width } + if (avatar != null) { + AsyncImage( + model = coil.request.ImageRequest.Builder( + androidx.compose.ui.platform.LocalContext.current, + ) + .data(avatar.fileUrl + ?: (AppGraph.tokenStore.baseUrl ?: "") + avatar.path) + .size(80) + .build(), + contentDescription = null, + contentScale = ContentScale.Crop, + modifier = Modifier + .size(28.dp) + .clip(CircleShape) + .background(Color(0xFF222222)), + ) + } + Text( + text = group.channel.displayName.ifBlank { group.channel.name }, + style = MaterialTheme.typography.titleMedium, + color = Color.White, + ) + } + } + item(key = "subrow" + group.channel.name + "@" + group.channel.host + group.startIndex) { + FocusScrollRow( + videos = group.videos, + progressOf = { null }, + onOpenVideo = onOpenVideo, + onLeftAtStart = onOpenDrawer, + upToTopBar = upToTopBar.takeIf { group == groups.firstOrNull() }, + ) { rowIndex, _ -> + if (group.startIndex + rowIndex >= items.size - PagedListViewModel.LOOKAHEAD) { + viewModel.loadMore() + } + } + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/FocusKeys.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/FocusKeys.kt new file mode 100644 index 0000000..7088eb4 --- /dev/null +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/FocusKeys.kt @@ -0,0 +1,29 @@ +package net.jeena.jtubetv.ui.screens.list + +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.composed +import androidx.compose.ui.input.key.onPreviewKeyEvent + +/** + * Compose `clickable` handles Enter/Space but NOT the TV's DPAD_CENTER; whether + * CENTER works depends on each device's input translation (works on some emulators, + * not on others — see the API-34 ATD case). This modifier consumes CENTER *first* + * (preview/tunneling) so the click fires exactly once, on every device. + */ +fun Modifier.dpadCenterActivatable(onClick: () -> Unit): Modifier = composed { + onPreviewKeyEvent { ke -> + if (ke.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) { + val code = ke.nativeKeyEvent.keyCode + val activates = code == android.view.KeyEvent.KEYCODE_DPAD_CENTER || + code == android.view.KeyEvent.KEYCODE_ENTER || + code == android.view.KeyEvent.KEYCODE_NUMPAD_ENTER || + code == android.view.KeyEvent.KEYCODE_SPACE + if (activates) { + onClick() + true // consumed in preview -> the platform/card path never double-fires + } else false + } else false + } +} \ No newline at end of file diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoCard.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoCard.kt index 8d67b29..5d4e1a9 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoCard.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoCard.kt @@ -3,6 +3,7 @@ package net.jeena.jtubetv.ui.screens.list import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth @@ -12,13 +13,24 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.key.type import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp +import androidx.compose.foundation.BorderStroke +import androidx.tv.material3.Border import androidx.tv.material3.Card import androidx.tv.material3.CardDefaults import coil.compose.AsyncImage @@ -43,24 +55,71 @@ fun VideoCard( modifier: Modifier = Modifier, showPrivacy: Boolean = true, progress: Float? = null, + /** Compact = row in the SmartTube home: single-line title, smaller. */ + compact: Boolean = false, + /** LEFT (only on the row's first card) can open the menu drawer. */ + onLeftAtStart: (() -> Unit)? = null, + /** Explicit UP-target for the first content row (focus search misses the top bar). */ + onUpToTopBar: (() -> Unit)? = null, + /** Notifies the row wrapper when this card gains focus (for eased scrolling). */ + onFocused: (() -> Unit)? = null, ) { + var cardFocused by remember { androidx.compose.runtime.mutableStateOf(false) } Card( onClick = onClick, modifier = modifier - .fillMaxWidth() - .height(268.dp) - .padding(6.dp), - colors = CardDefaults.colors(containerColor = MaterialTheme.colorScheme.surface), + .padding(6.dp) + .dpadCenterActivatable(onClick) + .onFocusChanged { + cardFocused = it.isFocused + if (it.isFocused) onFocused?.invoke() + } + .onPreviewKeyEvent { ke -> + val direction = ke.key + if (ke.type == androidx.compose.ui.input.key.KeyEventType.KeyDown) { + when { + direction == androidx.compose.ui.input.key.Key.DirectionLeft && onLeftAtStart != null -> { + onLeftAtStart(); true + } + direction == androidx.compose.ui.input.key.Key.DirectionUp && onUpToTopBar != null -> { + onUpToTopBar(); true + } + else -> false + } + } else false + }, + colors = CardDefaults.colors( + containerColor = UnfocusedCardBg, + contentColor = Color.White, + // SmartTube look: focused card turns white with dark text, no size change. + focusedContainerColor = Color.White, + focusedContentColor = Color(0xFF101010), + ), + scale = CardDefaults.scale(focusedScale = 1f), + border = CardDefaults.border( + focusedBorder = Border( + border = BorderStroke(3.dp, Color.White), + shape = ContainerShape, + ), + pressedBorder = Border( + border = BorderStroke(3.dp, Color.White), + shape = ContainerShape, + ), + ), ) { Box( modifier = Modifier .fillMaxWidth() - .height(158.dp) + .aspectRatio(16f / 9f) .background(Color(0xFF222222)), ) { video.thumbnailPath?.takeIf { it.isNotBlank() }?.let { path -> + val req = coil.request.ImageRequest.Builder(androidx.compose.ui.platform.LocalContext.current) + .data(AppGraph.repository.absoluteUrl(path)) + .size(480, 270) // ~2x the drawn thumb; avoids decoding 1080p+ jpegs + .build() AsyncImage( - model = AppGraph.repository.absoluteUrl(path), + model = req, contentDescription = video.name, contentScale = ContentScale.Crop, modifier = Modifier @@ -105,10 +164,12 @@ fun VideoCard( Text( text = video.name, style = MaterialTheme.typography.titleSmall, - maxLines = 2, - minLines = 2, + maxLines = if (compact) 1 else 2, + minLines = if (compact) 1 else 2, overflow = TextOverflow.Ellipsis, + color = if (cardFocused) Color(0xFF101010) else Color.White, ) + Row( horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically, @@ -116,7 +177,7 @@ fun VideoCard( Text( text = video.channel.displayName.ifBlank { video.channel.name }, style = MaterialTheme.typography.bodySmall, - color = Color(0xFFB8B8B8), + color = if (cardFocused) Color(0xFF6A6A6A) else Color(0xFFB8B8B8), maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false), @@ -145,7 +206,7 @@ fun VideoCard( text = formatAge(video.publishedAt) + if (video.views > 0) " · " + formatViews(video.views) else "", style = MaterialTheme.typography.bodySmall, - color = Color(0xFF8A8A8A), + color = if (cardFocused) Color(0xFF6A6A6A) else Color(0xFF8A8A8A), ) } } @@ -161,6 +222,10 @@ internal fun formatDuration(seconds: Int): String { } } +/** Card palette (SmartTube-style): near-black idle, white + dark text on focus. */ +internal val UnfocusedCardBg = Color(0xFF171717) +internal val ContainerShape = RoundedCornerShape(10.dp) + internal fun formatViews(views: Long): String = when { views >= 1_000_000 -> "%.1fM views".format(Locale.US, views / 1_000_000.0) diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt index 7adcbce..02e43b3 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt @@ -33,6 +33,7 @@ import androidx.lifecycle.viewmodel.compose.viewModel import net.jeena.jtubetv.R import net.jeena.jtubetv.data.api.VideoDto import net.jeena.jtubetv.ui.list.PagedListViewModel +import net.jeena.jtubetv.ui.screens.rowCardWidth import net.jeena.jtubetv.ui.list.ListSource import net.jeena.jtubetv.ui.list.VideoListItem import net.jeena.jtubetv.ui.list.VideoListViewModel @@ -43,6 +44,8 @@ fun VideoListScreen( onOpenVideo: (VideoDto) -> Unit, restoreToken: Int = 0, epoch: Int = 0, + onOpenDrawer: () -> Unit = {}, + upToTopBar: (() -> Unit)? = null, viewModel: VideoListViewModel = viewModel( key = "v$epoch:" + sourceKey(source), factory = VideoListViewModel.factory(source), @@ -58,7 +61,7 @@ fun VideoListScreen( // Which card was opened last — re-focus it when playback ends (UX report BUG-3). var lastOpenedIndex by androidx.compose.runtime.saveable.rememberSaveable(epoch) { mutableStateOf(-1) } LaunchedEffect(items.isNotEmpty(), source) { - if (items.isNotEmpty()) runCatching { initialFocus.requestFocus() } + if (items.isNotEmpty()) runCatching { requesters[0]?.requestFocus() ?: initialFocus.requestFocus() } } LaunchedEffect(restoreToken) { if (restoreToken > 0) { @@ -66,7 +69,7 @@ fun VideoListScreen( viewModel.refresh() } // focus the card that was playing; fall back to the first card - val target = requesters[lastOpenedIndex] ?: initialFocus + val target = requesters[lastOpenedIndex] ?: requesters[0] ?: initialFocus runCatching { target.requestFocus() } lastOpenedIndex = -1 } @@ -119,11 +122,12 @@ fun VideoListScreen( } LazyVerticalGrid( - columns = GridCells.Fixed(2), + // Same card size as the Home rows: ~4 fit per row (user request). + columns = GridCells.Adaptive(rowCardWidth() - 12.dp), state = gridState, modifier = Modifier.fillMaxSize().padding(vertical = 8.dp), ) { - itemsIndexed(items) { index, item -> + itemsIndexed(items, key = { _, item -> itemStableKey(item) }) { index, item -> val video: VideoDto = when (item) { is VideoListItem.HistoryEntry -> item.history.video is VideoListItem.Video -> item.video @@ -135,9 +139,11 @@ fun VideoListScreen( video = video, onClick = { lastOpenedIndex = index; onOpenVideo(video) }, showPrivacy = source is ListSource.MyVideos, + compact = true, + onLeftAtStart = if (index == 0) onOpenDrawer else null, + onUpToTopBar = upToTopBar?.takeIf { index < 4 }, modifier = Modifier - .focusRequester(fr) - .also { if (index == 0) Modifier.focusRequester(initialFocus) }, + .focusRequester(fr), ) if (index >= items.size - PagedListViewModel.LOOKAHEAD) { LaunchedEffect(index) { viewModel.loadMore() } @@ -188,6 +194,12 @@ private fun SearchHeader(viewModel: VideoListViewModel) { } } +private fun itemStableKey(item: VideoListItem): String = + when (item) { + is VideoListItem.Video -> "v" + item.video.id + is VideoListItem.HistoryEntry -> "h" + item.history.video.id + } + private fun sourceKey(source: ListSource): String = when (source) { is ListSource.Channel -> "channel:${source.handle}" else -> source::class.java.simpleName diff --git a/app/src/main/res/drawable/app_banner.xml b/app/src/main/res/drawable/app_banner.xml index 29ba394..5d78e70 100644 --- a/app/src/main/res/drawable/app_banner.xml +++ b/app/src/main/res/drawable/app_banner.xml @@ -7,16 +7,43 @@ - - - - + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/icon_foreground.xml b/app/src/main/res/drawable/icon_foreground.xml index 74dc88e..28febb9 100644 --- a/app/src/main/res/drawable/icon_foreground.xml +++ b/app/src/main/res/drawable/icon_foreground.xml @@ -5,13 +5,42 @@ android:viewportWidth="108" android:viewportHeight="108"> + android:scaleX="0.6" + android:scaleY="0.6" + android:translateX="27.5" + android:translateY="26.5"> + android:fillColor="#F2690D" + android:pathData="M60.2698 33.1237 c 0.2377 5.131 -7.2718 9.1005 -16.0739 9.6703 -8.8564 0.5733 -16.5815 -2.4078 -16.8896 -7.2214 -0.1502 -2.3457 1.4619 -4.9221 4.4079 -7.0758 2.9454 -2.1532 6.9675 -3.6913 11.2701 -4.1138 4.3242 -0.4245 8.5766 0.3156 11.9031 2.0468 3.3097 1.7224 5.2671 4.2043 5.3824 6.6939 z" /> + + android:pathData="M15.0279 42.3829 c 14.4103 -2.9379 34.4644 -4.7509 48.0973 -4.21 5.1043 0.2025 9.3683 4.8586 9.1618 9.7687 -0.2835 6.7398 -1.0404 18.8371 -1.477 25.8761 -0.3086 4.9748 -4.3214 9.3362 -8.8365 9.4034 -14.5318 0.2161 -28.9546 -0.025 -43.8451 0.6671 -4.5318 0.2106 -8.7268 -3.2379 -9.2264 -7.5956 C 7.993 68.3645 6.7849 60.7535 5.9079 52.9211 c -0.4974 -4.4414 3.7431 -9.442 9.1201 -10.5382 z" /> + + + + + + + + \ No newline at end of file diff --git a/scripts/bridge-emulator.sh b/scripts/bridge-emulator.sh new file mode 100755 index 0000000..5fc8ed2 --- /dev/null +++ b/scripts/bridge-emulator.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# +# bridge-emulator.sh — (host-side) expose the emulator's adbd to the LAN so agents +# inside the container/other machines can use it: binds :5557 -> 127.0.0.1:5601. +# The emulator console transport (emulator-5600) stays local-only; this bridges the +# adbd TCP port 5601. +set -euo pipefail +ADBD_PORT=5601 +BRIDGE_PORT=5557 + +# start emulator if not running +ADB="${ANDROID_SDK_ROOT:-$HOME/Android/Sdk}/platform-tools/adb" +if ! "$ADB" devices | grep -q "emulator-5600.*device"; then + echo "emulator-5600 not running — starting it…" + ADB_VENDOR_KEYS="$HOME/.android/adbkey" setsid nohup \ + "${ANDROID_SDK_ROOT:-$HOME/Android/Sdk}/emulator/emulator" -avd jtubesc -port 5600 \ + -no-window -gpu swiftshader_indirect -no-snapshot -no-audio -no-boot-anim \ + > /tmp/jtube-emu.log 2>&1 < /dev/null & + echo "waiting for boot (log: /tmp/jtube-emu.log)…" + for i in $(seq 1 60); do + ok=$("$ADB" -s emulator-5600 shell getprop sys.boot_completed 2>/dev/null | tr -d '\r') + [ "$ok" = "1" ] && { echo "BOOTED"; break; } + sleep 5 + done +fi + +# keep JTube TV installed + running +APK="$HOME/Projects/jtube-tv/app/build/outputs/apk/debug/app-debug.apk" +if [ -f "$APK" ]; then + "$ADB" -s emulator-5600 install -r "$APK" >/dev/null && echo "JTube TV installed" + "$ADB" -s emulator-5600 shell am start -n net.jeena.jtubetv/.MainActivity && echo "app started" +fi + +# the bridge (bind all LAN addresses) +if ! ss -tln 2>/dev/null | grep -q ":$BRIDGE_PORT"; then + setsid nohup socat TCP-LISTEN:$BRIDGE_PORT,bind=0.0.0.0,fork,reuseaddr \ + TCP:127.0.0.1:$ADBD_PORT > /tmp/jtube-bridge.log 2>&1 < /dev/null & + echo "bridge: :$BRIDGE_PORT -> 127.0.0.1:$ADBD_PORT (pid $!)" +fi + +echo "From this host: adb connect localhost:$BRIDGE_PORT" +echo "From other machines: adb connect rutherford:$BRIDGE_PORT" \ No newline at end of file diff --git a/scripts/emulator-seed.sh b/scripts/emulator-seed.sh new file mode 100755 index 0000000..7a4bd91 --- /dev/null +++ b/scripts/emulator-seed.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# +# emulator-seed.sh — (container-side) log the freshly booted emulated device into the +# JTube test account via the debug-only seed intent. Usage: +# ./emulator-seed.sh emulator-5568 [serial] +set -euo pipefail +SERIAL="${1:-emulator-5568}" +ADB="${ANDROID_HOME:-$HOME/Android/Sdk}/platform-tools/adb" +[ -x "$ADB" ] && ADB="$ADB" || ADB="$(which adb)" + +# credentials from the encrypted store +eval "$(sops -d --output-type dotenv "$HOME/.agents/secrets/jtube.env" | sed 's/^/export /')" + +# kill + cold start so onCreate (the debug seeder) actually runs +"$ADB" -s "$SERIAL" shell am force-stop net.jeena.jtubetv 2>/dev/null || true +"$ADB" -s "$SERIAL" install -r "$HOME/Projects/jtube-tv/app/build/outputs/apk/debug/app-debug.apk" 2>&1 | tail -1 + +"$ADB" -s "$SERIAL" shell am start -a android.intent.action.MAIN \ + -n net.jeena.jtubetv/.MainActivity \ + --es jtube_url "$JTUBE_URL" \ + --es jtube_user "$JTUBE_USER" \ + --es jtube_pass "$JTUBE_PASS" + +sleep 12 +"$ADB" -s "$SERIAL" shell uiautomator dump /sdcard/ui.xml > /dev/null 2>&1 +"$ADB" -s "$SERIAL" shell cat /sdcard/ui.xml | python3 -c " +import sys, re +xml = sys.stdin.read() +texts = [m.group(1) for m in re.finditer(r'text=\"([^\"]{2,40})\"', xml)] +foc = re.search(r']*focused=\"true\"[^>]*>', xml) +print('logged in as:', texts[0] if texts else '?') +print('rows/screens:', texts[1:8])" \ No newline at end of file diff --git a/scripts/fps-check.sh b/scripts/fps-check.sh new file mode 100755 index 0000000..6cda1fd --- /dev/null +++ b/scripts/fps-check.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +# +# fps-check.sh — measure UI smoothness of JTube TV on a device while programmatically +# scrolling the home rows the same way a remote would move focus. +# +# Usage: fps-check.sh [serial] default serial: emulator-5554 +# Prereqs: app installed + logged in, on the Home destination. +set -u +DEV="${1:-emulator-5554}" +ADB=~/Android/Sdk/platform-tools/adb + +echo "device $DEV: resetting frame stats" +$ADB -s "$DEV" shell am force-stop net.jeena.jtubetv +sleep 1 +$ADB -s "$DEV" shell am start -n net.jeena.jtubetv/.MainActivity >/dev/null +sleep 15 # give images time to load + settle + +# from top bar (search focused) DOWN into the first row, then traverse right across +# the row: each RIGHT triggers one (animated) row scroll. +$ADB -s "$DEV" shell input keyevent KEYCODE_DPAD_DOWN; sleep 1 +$ADB -s "$DEV" shell dumpsys gfxinfo net.jeena.jtubetv reset > /dev/null +for i in $(seq 1 12); do + $ADB -s "$DEV" shell input keyevent KEYCODE_DPAD_RIGHT + sleep 1.2 +done +$ADB -s "$DEV" shell input keyevent KEYCODE_DPAD_DOWN; sleep 1.5 +for i in $(seq 1 6); do + $ADB -s "$DEV" shell input keyevent KEYCODE_DPAD_LEFT + sleep 1.2 +done + +echo "--- gfxinfo (home rows scrolling, 18 focus moves) ---" +$ADB -s "$DEV" shell dumpsys gfxinfo net.jeena.jtubetv | python3 -c " +import sys, re +out = sys.stdin.read() +m = re.search(r'\*\* Graphics info\s*\n(.*)', out, re.S) +block = m.group(1) if m else out +def grab(name): + mm = re.search(name + r'[^\d]*(\S+)', block) + return mm.group(1) if mm else '?' +total = grab('Total frames rendered') +janky = grab('Janky frames') +print('Total frames rendered:', total) +print('Janky frames:', janky) +p50, p90, p95, p99 = grab('50th percentile'), grab('90th percentile'), grab('95th percentile'), grab('99th percentile') +print('frame time percentiles (ms): p50=%s p90=%s p95=%s p99=%s' % (p50, p90, p95, p99)) +" \ No newline at end of file diff --git a/scripts/start-emulator.sh b/scripts/start-emulator.sh new file mode 100755 index 0000000..c10e04c --- /dev/null +++ b/scripts/start-emulator.sh @@ -0,0 +1,123 @@ +#!/usr/bin/env bash +# +# start-emulator.sh — boot the JTube TV test emulator on the HOST (not inside the +# agent container), with GPU acceleration and a window. Use this when the app should +# be tested over scrcpy (ATD/system quirks make scrcpy fail against headless +# in-container emulators) or when you simply want to watch it. +# +# Boots on console :5600 (adbd :5601); the agent container bridges +# rutherford:5556 -> 127.0.0.1:5601 with socat, so after this script the emulator is +# reachable from anywhere as: +# +# adb connect rutherford:5556 && scrcpy -s rutherford:5556 +# +# An RSA authorization popup appears on the emulator window on first connect — +# click "Always allow"/OK. +set -euo pipefail + +SDK="${ANDROID_SDK_ROOT:-$HOME/Android/Sdk}" +EMU="$SDK/emulator/emulator" +ADB="$SDK/platform-tools/adb" +SDKM="$SDK/cmdline-tools/latest/bin/sdkmanager" +AVDM="$SDK/cmdline-tools/latest/bin/avdmanager" +AVD="${1:-jtubesc}" +PORT=5600 +IMAGE="system-images;android-36;android-tv;x86_64" + +[ -x "$EMU" ] || { echo "emulator not found at $EMU — install Android SDK cmdline-tools first"; exit 1; } + +# --- bootstrap: java, system image, AVD ------------------------------------- +if ! command -v java >/dev/null; then + echo "no java on PATH — required by sdkmanager/AVD tools" + echo " install it (Arch): sudo pacman -S --noconfirm jdk21-openjdk" + echo " then re-run this script" + exit 1 +fi + +if ! "$SDKM" --list_installed 2>/dev/null | grep -q "$IMAGE"; then + echo "installing $IMAGE (~1.5 GB, once)…" + yes | "$SDKM" "$IMAGE" > /dev/null + echo "installed" +fi + +if [ ! -f "$HOME/.android/avd/$AVD.ini" ]; then + echo "creating AVD '$AVD'…" + echo no | "$AVDM" create avd -n "$AVD" -k "$IMAGE" -d tv_1080p > /dev/null +fi + +# --- free stale emulator instances holding our port -------------------------- +for pid in $(ps aux | awk '/[q]emu-system-x86_64/ {print $2}' 2>/dev/null); do + if tr '\0' ' ' < "/proc/$pid/cmdline" 2>/dev/null | grep -q "\-port $PORT"; then + echo "Killing stale emulator pid $pid" + kill -9 "$pid" 2>/dev/null || true + fi +done +sleep 1 + +ACCEL=() +WINDOWED=1 +if [ -n "${WAYLAND_DISPLAY:-}${DISPLAY:-}" ]; then + echo "desktop session detected — emulator window + GPU host" +else + WINDOWED=0 + ACCEL+=(-no-window) + echo "headless (no display) — running without a window, swiftshader rendering" +fi +if [ -e /dev/kvm ]; then + [ $WINDOWED -eq 1 ] && ACCEL+=(-accel kvm) + echo "/dev/kvm found — hardware acceleration on" +fi + +echo "Booting AVD '$AVD' …" +setsid nohup "$EMU" -avd "$AVD" -port "$PORT" -gpu host "${ACCEL[@]:-}" \ + -no-snapshot > /tmp/jtube-emu.log 2>&1 < /dev/null & +echo "emulator PID $! — log: /tmp/jtube-emu.log" + +for i in $(seq 1 90); do + ok=$("$ADB" -s "emulator-$PORT" shell getprop sys.boot_completed 2>/dev/null | tr -d '\r') + [ "$ok" = "1" ] && { echo "BOOTED"; break; } + sleep 5 +done + +# --- authorize remote adb clients headlessly --------------------------------- +# The host console transport is always trusted; use it to whitelist client keys +# so `adb connect rutherford:5556` from other machines works without a popup. +# Drop extra public keys into /tmp/jtube-adbkeys/ (one per file), e.g. from +# Chester: cat ~/.android/adbkey.pub > /tmp/jtube-adbkeys/chester.pub +"$ADB" -s "emulator-$PORT" root > /dev/null 2>&1 || true +for key_file in "$HOME/.android/adbkey.pub" /tmp/jtube-adbkeys/*.pub; do + [ -f "$key_file" ] || continue + "$ADB" -s "emulator-$PORT" push "$key_file" "/data/misc/adb/adb_keys" > /dev/null 2>&1 || \ + "$ADB" -s "emulator-$PORT" shell "cat > /data/misc/adb/adb_keys" < "$key_file" || { + echo "could not whitelist $key_file"; + } +done +"$ADB" -s "emulator-$PORT" shell "setprop service.adb.tcp.port 5601; stop adbd; start adbd" > /dev/null 2>&1 || true + +# --- the bridge: advertise adbd on the LAN as :5556 --------------------------- +if ! ss -tln 2>/dev/null | grep -q ":5556"; then + if command -v socat > /dev/null; then + setsid nohup socat TCP-LISTEN:5556,bind=0.0.0.0,fork,reuseaddr TCP:127.0.0.1:$((PORT+1)) > /tmp/jtube-socat.log 2>&1 < /dev/null & + echo "socat bridge listening on :5556 (pid $!)" + else + echo "install socat for the remote bridge: sudo pacman -S --noconfirm socat" + fi +fi + +# Keep the JTube TV app current + running so scrcpy lands on it. +APK="$HOME/Projects/jtube-tv/app/build/outputs/apk/debug/app-debug.apk" +if [ -f "$APK" ]; then + echo "Installing JTube TV…" + "$ADB" -s "emulator-$PORT" install -r "$APK" >/dev/null && echo "installed" + "$ADB" -s "emulator-$PORT" shell am start -n net.jeena.jtubetv/.MainActivity && echo "app started" +fi + +cat <