StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
Add third-party licenses and notices for included libraries
David Nashash3db4dfc24a3a
diff --git a/.github/workflows/beta.yml b/.github/workflows/beta.ymlindex 078844db..dc15f700 100644--- a/.github/workflows/beta.yml+++ b/.github/workflows/beta.yml@@ -79,6 +79,8 @@ jobs:run: chmod +x gradlew- name: Build beta APK+ env:+ OPENSUBTITLES_API_KEY: ${{ secrets.OPENSUBTITLES_API_KEY }}run: ./gradlew --console=plain :app:assembleBeta- name: Prepare beta artifactdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 9fd93577..bb5b0ba4 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -87,6 +87,8 @@ jobs:run: ./gradlew --console=plain :app:assembleDebugAndroidTest :data:assembleDebugAndroidTest- name: Build release APK+ env:+ OPENSUBTITLES_API_KEY: ${{ secrets.OPENSUBTITLES_API_KEY }}run: ./gradlew --console=plain :app:assembleRelease- name: Prepare release artifactdiff --git a/README.md b/README.mdindex 5ec6e696..03134adb 100644--- a/README.md+++ b/README.md@@ -29,15 +29,16 @@ Built for Android TV first, StreamVault focuses on the things generic IPTV apps</p><p align="center">- <a href="https://github.com/Davidona/StreamVault-IPTV/raw/master/docs/images/Home.png"><img src="docs/images/Home.png" alt="Home" width="19%" /></a>- <a href="https://github.com/Davidona/StreamVault-IPTV/raw/master/docs/images/LiveTV.png"><img src="docs/images/LiveTV.png" alt="Live TV" width="19%" /></a>- <a href="https://github.com/Davidona/StreamVault-IPTV/raw/master/docs/images/ChannelView.png"><img src="docs/images/ChannelView.png" alt="Channel Preview" width="19%" /></a>- <a href="https://github.com/Davidona/StreamVault-IPTV/raw/master/docs/images/Guide.png"><img src="docs/images/Guide.png" alt="Guide" width="19%" /></a>- <a href="https://github.com/Davidona/StreamVault-IPTV/raw/master/docs/images/Settings.png"><img src="docs/images/Settings.png" alt="Settings" width="19%" /></a>+ <a href="https://github.com/Davidona/StreamVault-IPTV/raw/master/docs/images/Sports.png"><img src="docs/images/Sports.png" alt="Sports" width="88%" /></a></p><p align="center">- <a href="https://github.com/Davidona/StreamVault-IPTV/raw/master/docs/images/SeriesEpisodes.png"><img src="docs/images/SeriesEpisodes.png" alt="Series Episodes" width="32%" /></a>+ <a href="https://github.com/Davidona/StreamVault-IPTV/raw/master/docs/images/ChannelView.png"><img src="docs/images/ChannelView.png" alt="Channel Preview" width="44%" /></a>+ <a href="https://github.com/Davidona/StreamVault-IPTV/raw/master/docs/images/Guide.png"><img src="docs/images/Guide.png" alt="Guide" width="44%" /></a>+</p>++<p align="center">+ <a href="https://github.com/Davidona/StreamVault-IPTV/raw/master/docs/images/SeriesEpisodes.png"><img src="docs/images/SeriesEpisodes.png" alt="Series Episodes" width="44%" /></a></p>## Highlightsdiff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex 371afc9e..d5f45a4d 100644--- a/app/build.gradle.kts+++ b/app/build.gradle.kts@@ -45,6 +45,7 @@ fun localProp(key: String): String =// Public app configuration; OAuth user credentials are never build inputs.val traktClientId = providers.environmentVariable("TRAKT_CLIENT_ID").orNull ?: localProp("trakt.client.id")val traktRedirectUri = providers.environmentVariable("TRAKT_REDIRECT_URI").orNull ?: localProp("trakt.redirect.uri")+val opensubtitlesApiKey = providers.environmentVariable("OPENSUBTITLES_API_KEY").orNullval traktCallback = runCatching { URI(traktRedirectUri) }.getOrNull()fun buildStringLiteral(value: String): String = "\"" + value.replace("\\", "\\\\").replace("\"", "\\\"") + "\""@@ -78,8 +79,8 @@ android {applicationId = "com.streamvault.app"minSdk = 25targetSdk = 36- versionCode = 21- versionName = "1.0.19"+ versionCode = 22+ versionName = "1.2.0"testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"buildConfigField("String", "TRAKT_CLIENT_ID", buildStringLiteral(traktClientId))buildConfigField("String", "TRAKT_REDIRECT_URI", buildStringLiteral(traktRedirectUri))@@ -90,7 +91,7 @@ android {}buildConfigField("String", "OFFICIAL_APPLICATION_ID", "\"com.streamvault.app\"")buildConfigField("String", "OFFICIAL_SIGNING_CERT_SHA256", "\"$officialSigningCertSha256\"")- buildConfigField("String", "OPENSUBTITLES_API_KEY", "\"\"")+ buildConfigField("String", "OPENSUBTITLES_API_KEY", buildStringLiteral(opensubtitlesApiKey.orEmpty()))buildConfigField("String", "APP_UPDATE_CHANNEL", "\"stable\"")buildConfigField("long", "BUILD_TIMESTAMP_UTC", "0L")ndk {@@ -135,7 +136,7 @@ android {buildConfigField("String","OPENSUBTITLES_API_KEY",- "\"${localProp("opensubtitles.api.key").replace("\\", "\\\\").replace("\"", "\\\"")}\""+ buildStringLiteral(opensubtitlesApiKey ?: localProp("opensubtitles.api.key")))}create("beta") {diff --git a/app/src/main/assets/licenses/APSL-2.0.txt b/app/src/main/assets/licenses/APSL-2.0.txtnew file mode 100644index 00000000..2d2d2cf9--- /dev/null+++ b/app/src/main/assets/licenses/APSL-2.0.txt@@ -0,0 +1,102 @@+APPLE PUBLIC SOURCE LICENSE+Version 2.0 - August 6, 2003++Please read this License carefully before downloading this software. By downloading or using this software, you are agreeing to be bound by the terms of this License. If you do not or cannot agree to the terms of this License, please do not download or use the software.++Apple Note: In January 2007, Apple changed its corporate name from "Apple Computer, Inc." to "Apple Inc." This change has been reflected below and copyright years updated, but no other changes have been made to the APSL 2.0.++1. General; Definitions. This License applies to any program or other work which Apple Inc. ("Apple") makes publicly available and which contains a notice placed by Apple identifying such program or work as "Original Code" and stating that it is subject to the terms of this Apple Public Source License version 2.0 ("License"). As used in this License:++ 1.1 "Applicable Patent Rights" mean: (a) in the case where Apple is the grantor of rights, (i) claims of patents that are now or hereafter acquired, owned by or assigned to Apple and (ii) that cover subject matter contained in the Original Code, but only to the extent necessary to use, reproduce and/or distribute the Original Code without infringement; and (b) in the case where You are the grantor of rights, (i) claims of patents that are now or hereafter acquired, owned by or assigned to You and (ii) that cover subject matter in Your Modifications, taken alone or in combination with Original Code.++ 1.2 "Contributor" means any person or entity that creates or contributes to the creation of Modifications.++ 1.3 "Covered Code" means the Original Code, Modifications, the combination of Original Code and any Modifications, and/or any respective portions thereof.++ 1.4 "Externally Deploy" means: (a) to sublicense, distribute or otherwise make Covered Code available, directly or indirectly, to anyone other than You; and/or (b) to use Covered Code, alone or as part of a Larger Work, in any way to provide a service, including but not limited to delivery of content, through electronic communication with a client other than You.++ 1.5 "Larger Work" means a work which combines Covered Code or portions thereof with code not governed by the terms of this License.++ 1.6 "Modifications" mean any addition to, deletion from, and/or change to, the substance and/or structure of the Original Code, any previous Modifications, the combination of Original Code and any previous Modifications, and/or any respective portions thereof. When code is released as a series of files, a Modification is: (a) any addition to or deletion from the contents of a file containing Covered Code; and/or (b) any new file or other representation of computer program statements that contains any part of Covered Code.++ 1.7 "Original Code" means (a) the Source Code of a program or other work as originally made available by Apple under this License, including the Source Code of any updates or upgrades to such programs or works made available by Apple under this License, and that has been expressly identified by Apple as such in the header file(s) of such work; and (b) the object code compiled from such Source Code and originally made available by Apple under this License++ 1.8 "Source Code" means the human readable form of a program or other work that is suitable for making modifications to it, including all modules it contains, plus any associated interface definition files, scripts used to control compilation and installation of an executable (object code).++ 1.9 "You" or "Your" means an individual or a legal entity exercising rights under this License. For legal entities, "You" or "Your" includes any entity which controls, is controlled by, or is under common control with, You, where "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of fifty percent (50%) or more of the outstanding shares or beneficial ownership of such entity.++2. Permitted Uses; Conditions & Restrictions. Subject to the terms and conditions of this License, Apple hereby grants You, effective on the date You accept this License and download the Original Code, a world-wide, royalty-free, non-exclusive license, to the extent of Apple's Applicable Patent Rights and copyrights covering the Original Code, to do the following:++ 2.1 Unmodified Code. You may use, reproduce, display, perform, internally distribute within Your organization, and Externally Deploy verbatim, unmodified copies of the Original Code, for commercial or non-commercial purposes, provided that in each instance:++ (a) You must retain and reproduce in all copies of Original Code the copyright and other proprietary notices and disclaimers of Apple as they appear in the Original Code, and keep intact all notices in the Original Code that refer to this License; and++ (b) You must include a copy of this License with every copy of Source Code of Covered Code and documentation You distribute or Externally Deploy, and You may not offer or impose any terms on such Source Code that alter or restrict this License or the recipients' rights hereunder, except as permitted under Section 6.++ 2.2 Modified Code. You may modify Covered Code and use, reproduce, display, perform, internally distribute within Your organization, and Externally Deploy Your Modifications and Covered Code, for commercial or non-commercial purposes, provided that in each instance You also meet all of these conditions:++ (a) You must satisfy all the conditions of Section 2.1 with respect to the Source Code of the Covered Code;++ (b) You must duplicate, to the extent it does not already exist, the notice in Exhibit A in each file of the Source Code of all Your Modifications, and cause the modified files to carry prominent notices stating that You changed the files and the date of any change; and++ (c) If You Externally Deploy Your Modifications, You must make Source Code of all Your Externally Deployed Modifications either available to those to whom You have Externally Deployed Your Modifications, or publicly available. Source Code of Your Externally Deployed Modifications must be released under the terms set forth in this License, including the license grants set forth in Section 3 below, for as long as you Externally Deploy the Covered Code or twelve (12) months from the date of initial External Deployment, whichever is longer. You should preferably distribute the Source Code of Your Externally Deployed Modifications electronically (e.g. download from a web site).++ 2.3 Distribution of Executable Versions. In addition, if You Externally Deploy Covered Code (Original Code and/or Modifications) in object code, executable form only, You must include a prominent notice, in the code itself as well as in related documentation, stating that Source Code of the Covered Code is available under the terms of this License with information on how and where to obtain such Source Code.++ 2.4 Third Party Rights. You expressly acknowledge and agree that although Apple and each Contributor grants the licenses to their respective portions of the Covered Code set forth herein, no assurances are provided by Apple or any Contributor that the Covered Code does not infringe the patent or other intellectual property rights of any other entity. Apple and each Contributor disclaim any liability to You for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, You hereby assume sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow You to distribute the Covered Code, it is Your responsibility to acquire that license before distributing the Covered Code.++3. Your Grants. In consideration of, and as a condition to, the licenses granted to You under this License, You hereby grant to any person or entity receiving or distributing Covered Code under this License a non-exclusive, royalty-free, perpetual, irrevocable license, under Your Applicable Patent Rights and other intellectual property rights (other than patent) owned or controlled by You, to use, reproduce, display, perform, modify, sublicense, distribute and Externally Deploy Your Modifications of the same scope and extent as Apple's licenses under Sections 2.1 and 2.2 above.++4. Larger Works. You may create a Larger Work by combining Covered Code with other code not governed by the terms of this License and distribute the Larger Work as a single product. In each such instance, You must make sure the requirements of this License are fulfilled for the Covered Code or any portion thereof.++5. Limitations on Patent License. Except as expressly stated in Section 2, no other patent rights, express or implied, are granted by Apple herein. Modifications and/or Larger Works may require additional patent licenses from Apple which Apple may grant in its sole discretion.++6. Additional Terms. You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations and/or other rights consistent with the scope of the license granted herein ("Additional Terms") to one or more recipients of Covered Code. However, You may do so only on Your own behalf and as Your sole responsibility, and not on behalf of Apple or any Contributor. You must obtain the recipient's agreement that any such Additional Terms are offered by You alone, and You hereby agree to indemnify, defend and hold Apple and every Contributor harmless for any liability incurred by or claims asserted against Apple or such Contributor by reason of any such Additional Terms.++7. Versions of the License. Apple may publish revised and/or new versions of this License from time to time. Each version will be given a distinguishing version number. Once Original Code has been published under a particular version of this License, You may continue to use it under the terms of that version. You may also choose to use such Original Code under the terms of any subsequent version of this License published by Apple. No one other than Apple has the right to modify the terms applicable to Covered Code created under this License.++8. NO WARRANTY OR SUPPORT. The Covered Code may contain in whole or in part pre-release, untested, or not fully tested works. The Covered Code may contain errors that could cause failures or loss of data, and may be incomplete or contain inaccuracies. You expressly acknowledge and agree that use of the Covered Code, or any portion thereof, is at Your sole and entire risk. THE COVERED CODE IS PROVIDED "AS IS" AND WITHOUT WARRANTY, UPGRADES OR SUPPORT OF ANY KIND AND APPLE AND APPLE'S LICENSOR(S) (COLLECTIVELY REFERRED TO AS "APPLE" FOR THE PURPOSES OF SECTIONS 8 AND 9) AND ALL CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND/OR CONDITIONS, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES AND/OR CONDITIONS OF MERCHANTABILITY, OF SATISFACTORY QUALITY, OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY, OF QUIET ENJOYMENT, AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. APPLE AND EACH CONTRIBUTOR DOES NOT WARRANT AGAINST INTERFERENCE WITH YOUR ENJOYMENT OF THE COVERED CODE, THAT THE FUNCTIONS CONTAINED IN THE COVERED CODE WILL MEET YOUR REQUIREMENTS, THAT THE OPERATION OF THE COVERED CODE WILL BE UNINTERRUPTED OR ERROR-FREE, OR THAT DEFECTS IN THE COVERED CODE WILL BE CORRECTED. NO ORAL OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE, AN APPLE AUTHORIZED REPRESENTATIVE OR ANY CONTRIBUTOR SHALL CREATE A WARRANTY. You acknowledge that the Covered Code is not intended for use in the operation of nuclear facilities, aircraft navigation, communication systems, or air traffic control machines in which case the failure of the Covered Code could lead to death, personal injury, or severe physical or environmental damage.++9. LIMITATION OF LIABILITY. TO THE EXTENT NOT PROHIBITED BY LAW, IN NO EVENT SHALL APPLE OR ANY CONTRIBUTOR BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES ARISING OUT OF OR RELATING TO THIS LICENSE OR YOUR USE OR INABILITY TO USE THE COVERED CODE, OR ANY PORTION THEREOF, WHETHER UNDER A THEORY OF CONTRACT, WARRANTY, TORT (INCLUDING NEGLIGENCE), PRODUCTS LIABILITY OR OTHERWISE, EVEN IF APPLE OR SUCH CONTRIBUTOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES AND NOTWITHSTANDING THE FAILURE OF ESSENTIAL PURPOSE OF ANY REMEDY. SOME JURISDICTIONS DO NOT ALLOW THE LIMITATION OF LIABILITY OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS LIMITATION MAY NOT APPLY TO YOU. In no event shall Apple's total liability to You for all damages (other than as may be required by applicable law) under this License exceed the amount of fifty dollars ($50.00).++10. Trademarks. This License does not grant any rights to use the trademarks or trade names "Apple", "Mac", "Mac OS", "QuickTime", "QuickTime Streaming Server" or any other trademarks, service marks, logos or trade names belonging to Apple (collectively "Apple Marks") or to any trademark, service mark, logo or trade name belonging to any Contributor. You agree not to use any Apple Marks in or as part of the name of products derived from the Original Code or to endorse or promote products derived from the Original Code other than as expressly permitted by and in strict compliance at all times with Apple's third party trademark usage guidelines which are posted at http://www.apple.com/legal/guidelinesfor3rdparties.html.++11. Ownership. Subject to the licenses granted under this License, each Contributor retains all rights, title and interest in and to any Modifications made by such Contributor. Apple retains all rights, title and interest in and to the Original Code and any Modifications made by or on behalf of Apple ("Apple Modifications"), and such Apple Modifications will not be automatically subject to this License. Apple may, at its sole discretion, choose to license such Apple Modifications under this License, or on different terms from those contained in this License or may choose not to license them at all.++12. Termination.++ 12.1 Termination. This License and the rights granted hereunder will terminate:++ (a) automatically without notice from Apple if You fail to comply with any term(s) of this License and fail to cure such breach within 30 days of becoming aware of such breach;++ (b) immediately in the event of the circumstances described in Section 13.5(b); or++ (c) automatically without notice from Apple if You, at any time during the term of this License, commence an action for patent infringement against Apple; provided that Apple did not first commence an action for patent infringement against You in that instance.++ 12.2 Effect of Termination. Upon termination, You agree to immediately stop any further use, reproduction, modification, sublicensing and distribution of the Covered Code. All sublicenses to the Covered Code which have been properly granted prior to termination shall survive any termination of this License. Provisions which, by their nature, should remain in effect beyond the termination of this License shall survive, including but not limited to Sections 3, 5, 8, 9, 10, 11, 12.2 and 13. No party will be liable to any other for compensation, indemnity or damages of any sort solely as a result of terminating this License in accordance with its terms, and termination of this License will be without prejudice to any other right or remedy of any party.++13. Miscellaneous.++ 13.1 Government End Users. The Covered Code is a "commercial item" as defined in FAR 2.101. Government software and technical data rights in the Covered Code include only those rights customarily provided to the public as defined in this License. This customary commercial license in technical data and software is provided in accordance with FAR 12.211 (Technical Data) and 12.212 (Computer Software) and, for Department of Defense purchases, DFAR 252.227-7015 (Technical Data -- Commercial Items) and 227.7202-3 (Rights in Commercial Computer Software or Computer Software Documentation). Accordingly, all U.S. Government End Users acquire Covered Code with only those rights set forth herein.++ 13.2 Relationship of Parties. This License will not be construed as creating an agency, partnership, joint venture or any other form of legal association between or among You, Apple or any Contributor, and You will not represent to the contrary, whether expressly, by implication, appearance or otherwise.++ 13.3 Independent Development. Nothing in this License will impair Apple's right to acquire, license, develop, have others develop for it, market and/or distribute technology or products that perform the same or similar functions as, or otherwise compete with, Modifications, Larger Works, technology or products that You may develop, produce, market or distribute.++ 13.4 Waiver; Construction. Failure by Apple or any Contributor to enforce any provision of this License will not be deemed a waiver of future enforcement of that or any other provision. Any law or regulation which provides that the language of a contract shall be construed against the drafter will not apply to this License.++ 13.5 Severability. (a) If for any reason a court of competent jurisdiction finds any provision of this License, or portion thereof, to be unenforceable, that provision of the License will be enforced to the maximum extent permissible so as to effect the economic benefits and intent of the parties, and the remainder of this License will continue in full force and effect. (b) Notwithstanding the foregoing, if applicable law prohibits or restricts You from fully and/or specifically complying with Sections 2 and/or 3 or prevents the enforceability of either of those Sections, this License will immediately terminate and You must immediately discontinue any use of the Covered Code and destroy all copies of it that are in your possession or control.++ 13.6 Dispute Resolution. Any litigation or other dispute resolution between You and Apple relating to this License shall take place in the Northern District of California, and You and Apple hereby consent to the personal jurisdiction of, and venue in, the state and federal courts within that District with respect to this License. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded.++ 13.7 Entire Agreement; Governing Law. This License constitutes the entire agreement between the parties with respect to the subject matter hereof. This License shall be governed by the laws of the United States and the State of California, except that body of California law concerning conflicts of law.++ Where You are located in the province of Quebec, Canada, the following clause applies: The parties hereby confirm that they have requested that this License and all related documents be drafted in English. Les parties ont exigé que le présent contrat et tous les documents connexes soient rédigés en anglais.++EXHIBIT A.++"Portions Copyright (c) 1999-2007 Apple Inc. All Rights Reserved.++This file contains Original Code and/or Modifications of Original Code as defined in and that are subject to the Apple Public Source License Version 2.0 (the 'License'). You may not use this file except in compliance with the License. Please obtain a copy of the License at http://www.opensource.apple.com/apsl/ and read it before using this file.++The Original Code and all software distributed under the License are distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the specific language governing rights and limitations under the License."diff --git a/app/src/main/assets/licenses/Apache-2.0.txt b/app/src/main/assets/licenses/Apache-2.0.txtnew file mode 100644index 00000000..137069b8--- /dev/null+++ b/app/src/main/assets/licenses/Apache-2.0.txt@@ -0,0 +1,73 @@+Apache License+Version 2.0, January 2004+http://www.apache.org/licenses/++TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++1. Definitions.++"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.++"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.++"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.++"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.++"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.++"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.++"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).++"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.++"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."++"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.++2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.++3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.++4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:++ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.++ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.++5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.++6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.++7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.++8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.++9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.++END OF TERMS AND CONDITIONS++APPENDIX: How to apply the Apache License to your work.++To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.++Copyright [yyyy] [name of copyright owner]++Licensed under the Apache License, Version 2.0 (the "License");+you may not use this file except in compliance with the License.+You may obtain a copy of the License at++http://www.apache.org/licenses/LICENSE-2.0++Unless required by applicable law or agreed to in writing, software+distributed under the License is distributed on an "AS IS" BASIS,+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+See the License for the specific language governing permissions and+limitations under the License.diff --git a/app/src/main/assets/licenses/BouncyCastle-LICENSE.html b/app/src/main/assets/licenses/BouncyCastle-LICENSE.htmlnew file mode 100644index 00000000..c300d616--- /dev/null+++ b/app/src/main/assets/licenses/BouncyCastle-LICENSE.html@@ -0,0 +1,22 @@+<html>+<body bgcolor=#ffffff>++Copyright (c) 2000-2023 The Legion of the Bouncy Castle Inc. (https://www.bouncycastle.org)+<p>+Permission is hereby granted, free of charge, to any person obtaining a copy of this software+and associated documentation files (the "Software"), to deal in the Software without restriction,+including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,+and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,+subject to the following conditions:+<p>+The above copyright notice and this permission notice shall be included in all copies or substantial+portions of the Software.+<p>+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,+INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR+PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR+OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER+DEALINGS IN THE SOFTWARE.+</body>+</html>diff --git a/app/src/main/assets/licenses/FFmpeg-LGPL-2.1.txt b/app/src/main/assets/licenses/FFmpeg-LGPL-2.1.txtnew file mode 100644index 00000000..40924c2a--- /dev/null+++ b/app/src/main/assets/licenses/FFmpeg-LGPL-2.1.txt@@ -0,0 +1,502 @@+ GNU LESSER GENERAL PUBLIC LICENSE+ Version 2.1, February 1999++ Copyright (C) 1991, 1999 Free Software Foundation, Inc.+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++[This is the first released version of the Lesser GPL. It also counts+ as the successor of the GNU Library Public License, version 2, hence+ the version number 2.1.]++ Preamble++ The licenses for most software are designed to take away your+freedom to share and change it. By contrast, the GNU General Public+Licenses are intended to guarantee your freedom to share and change+free software--to make sure the software is free for all its users.++ This license, the Lesser General Public License, applies to some+specially designated software packages--typically libraries--of the+Free Software Foundation and other authors who decide to use it. You+can use it too, but we suggest you first think carefully about whether+this license or the ordinary General Public License is the better+strategy to use in any particular case, based on the explanations below.++ When we speak of free software, we are referring to freedom of use,+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 this service if you wish); that you receive source code or can get+it if you want it; that you can change the software and use pieces of+it in new free programs; and that you are informed that you can do+these things.++ To protect your rights, we need to make restrictions that forbid+distributors to deny you these rights or to ask you to surrender these+rights. These restrictions translate to certain responsibilities for+you if you distribute copies of the library or if you modify it.++ For example, if you distribute copies of the library, whether gratis+or for a fee, you must give the recipients all the rights that we gave+you. You must make sure that they, too, receive or can get the source+code. If you link other code with the library, you must provide+complete object files to the recipients, so that they can relink them+with the library after making changes to the library and recompiling+it. And you must show them these terms so they know their rights.++ We protect your rights with a two-step method: (1) we copyright the+library, and (2) we offer you this license, which gives you legal+permission to copy, distribute and/or modify the library.++ To protect each distributor, we want to make it very clear that+there is no warranty for the free library. Also, if the library is+modified by someone else and passed on, the recipients should know+that what they have is not the original version, so that the original+author's reputation will not be affected by problems that might be+introduced by others.++ Finally, software patents pose a constant threat to the existence of+any free program. We wish to make sure that a company cannot+effectively restrict the users of a free program by obtaining a+restrictive license from a patent holder. Therefore, we insist that+any patent license obtained for a version of the library must be+consistent with the full freedom of use specified in this license.++ Most GNU software, including some libraries, is covered by the+ordinary GNU General Public License. This license, the GNU Lesser+General Public License, applies to certain designated libraries, and+is quite different from the ordinary General Public License. We use+this license for certain libraries in order to permit linking those+libraries into non-free programs.++ When a program is linked with a library, whether statically or using+a shared library, the combination of the two is legally speaking a+combined work, a derivative of the original library. The ordinary+General Public License therefore permits such linking only if the+entire combination fits its criteria of freedom. The Lesser General+Public License permits more lax criteria for linking other code with+the library.++ We call this license the "Lesser" General Public License because it+does Less to protect the user's freedom than the ordinary General+Public License. It also provides other free software developers Less+of an advantage over competing non-free programs. These disadvantages+are the reason we use the ordinary General Public License for many+libraries. However, the Lesser license provides advantages in certain+special circumstances.++ For example, on rare occasions, there may be a special need to+encourage the widest possible use of a certain library, so that it becomes+a de-facto standard. To achieve this, non-free programs must be+allowed to use the library. A more frequent case is that a free+library does the same job as widely used non-free libraries. In this+case, there is little to gain by limiting the free library to free+software only, so we use the Lesser General Public License.++ In other cases, permission to use a particular library in non-free+programs enables a greater number of people to use a large body of+free software. For example, permission to use the GNU C Library in+non-free programs enables many more people to use the whole GNU+operating system, as well as its variant, the GNU/Linux operating+system.++ Although the Lesser General Public License is Less protective of the+users' freedom, it does ensure that the user of a program that is+linked with the Library has the freedom and the wherewithal to run+that program using a modified version of the Library.++ The precise terms and conditions for copying, distribution and+modification follow. Pay close attention to the difference between a+"work based on the library" and a "work that uses the library". The+former contains code derived from the library, whereas the latter must+be combined with the library in order to run.++ GNU LESSER GENERAL PUBLIC LICENSE+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION++ 0. This License Agreement applies to any software library or other+program which contains a notice placed by the copyright holder or+other authorized party saying it may be distributed under the terms of+this Lesser General Public License (also called "this License").+Each licensee is addressed as "you".++ A "library" means a collection of software functions and/or data+prepared so as to be conveniently linked with application programs+(which use some of those functions and data) to form executables.++ The "Library", below, refers to any such software library or work+which has been distributed under these terms. A "work based on the+Library" means either the Library or any derivative work under+copyright law: that is to say, a work containing the Library or a+portion of it, either verbatim or with modifications and/or translated+straightforwardly into another language. (Hereinafter, translation is+included without limitation in the term "modification".)++ "Source code" for a work means the preferred form of the work for+making modifications to it. For a library, complete source code means+all the source code for all modules it contains, plus any associated+interface definition files, plus the scripts used to control compilation+and installation of the library.++ Activities other than copying, distribution and modification are not+covered by this License; they are outside its scope. The act of+running a program using the Library is not restricted, and output from+such a program is covered only if its contents constitute a work based+on the Library (independent of the use of the Library in a tool for+writing it). Whether that is true depends on what the Library does+and what the program that uses the Library does.++ 1. You may copy and distribute verbatim copies of the Library's+complete source code as you receive it, in any medium, provided that+you conspicuously and appropriately publish on each copy an+appropriate copyright notice and disclaimer of warranty; keep intact+all the notices that refer to this License and to the absence of any+warranty; and distribute a copy of this License along with the+Library.++ You may charge a fee for the physical act of transferring a copy,+and you may at your option offer warranty protection in exchange for a+fee.++ 2. You may modify your copy or copies of the Library or any portion+of it, thus forming a work based on the Library, and copy and+distribute such modifications or work under the terms of Section 1+above, provided that you also meet all of these conditions:++ a) The modified work must itself be a software library.++ b) You must cause the files modified to carry prominent notices+ stating that you changed the files and the date of any change.++ c) You must cause the whole of the work to be licensed at no+ charge to all third parties under the terms of this License.++ d) If a facility in the modified Library refers to a function or a+ table of data to be supplied by an application program that uses+ the facility, other than as an argument passed when the facility+ is invoked, then you must make a good faith effort to ensure that,+ in the event an application does not supply such function or+ table, the facility still operates, and performs whatever part of+ its purpose remains meaningful.++ (For example, a function in a library to compute square roots has+ a purpose that is entirely well-defined independent of the+ application. Therefore, Subsection 2d requires that any+ application-supplied function or table used by this function must+ be optional: if the application does not supply it, the square+ root function must still compute square roots.)++These requirements apply to the modified work as a whole. If+identifiable sections of that work are not derived from the Library,+and can be reasonably considered independent and separate works in+themselves, then this License, and its terms, do not apply to those+sections when you distribute them as separate works. But when you+distribute the same sections as part of a whole which is a work based+on the Library, the distribution of the whole must be on the terms of+this License, whose permissions for other licensees extend to the+entire whole, and thus to each and every part regardless of who wrote+it.++Thus, it is not the intent of this section to claim rights or contest+your rights to work written entirely by you; rather, the intent is to+exercise the right to control the distribution of derivative or+collective works based on the Library.++In addition, mere aggregation of another work not based on the Library+with the Library (or with a work based on the Library) on a volume of+a storage or distribution medium does not bring the other work under+the scope of this License.++ 3. You may opt to apply the terms of the ordinary GNU General Public+License instead of this License to a given copy of the Library. To do+this, you must alter all the notices that refer to this License, so+that they refer to the ordinary GNU General Public License, version 2,+instead of to this License. (If a newer version than version 2 of the+ordinary GNU General Public License has appeared, then you can specify+that version instead if you wish.) Do not make any other change in+these notices.++ Once this change is made in a given copy, it is irreversible for+that copy, so the ordinary GNU General Public License applies to all+subsequent copies and derivative works made from that copy.++ This option is useful when you wish to copy part of the code of+the Library into a program that is not a library.++ 4. You may copy and distribute the Library (or a portion or+derivative of it, under Section 2) in object code or executable form+under the terms of Sections 1 and 2 above provided that you accompany+it with the complete corresponding machine-readable source code, which+must be distributed under the terms of Sections 1 and 2 above on a+medium customarily used for software interchange.++ If distribution of object code is made by offering access to copy+from a designated place, then offering equivalent access to copy the+source code from the same place satisfies the requirement to+distribute the source code, even though third parties are not+compelled to copy the source along with the object code.++ 5. A program that contains no derivative of any portion of the+Library, but is designed to work with the Library by being compiled or+linked with it, is called a "work that uses the Library". Such a+work, in isolation, is not a derivative work of the Library, and+therefore falls outside the scope of this License.++ However, linking a "work that uses the Library" with the Library+creates an executable that is a derivative of the Library (because it+contains portions of the Library), rather than a "work that uses the+library". The executable is therefore covered by this License.+Section 6 states terms for distribution of such executables.++ When a "work that uses the Library" uses material from a header file+that is part of the Library, the object code for the work may be a+derivative work of the Library even though the source code is not.+Whether this is true is especially significant if the work can be+linked without the Library, or if the work is itself a library. The+threshold for this to be true is not precisely defined by law.++ If such an object file uses only numerical parameters, data+structure layouts and accessors, and small macros and small inline+functions (ten lines or less in length), then the use of the object+file is unrestricted, regardless of whether it is legally a derivative+work. (Executables containing this object code plus portions of the+Library will still fall under Section 6.)++ Otherwise, if the work is a derivative of the Library, you may+distribute the object code for the work under the terms of Section 6.+Any executables containing that work also fall under Section 6,+whether or not they are linked directly with the Library itself.++ 6. As an exception to the Sections above, you may also combine or+link a "work that uses the Library" with the Library to produce a+work containing portions of the Library, and distribute that work+under terms of your choice, provided that the terms permit+modification of the work for the customer's own use and reverse+engineering for debugging such modifications.++ You must give prominent notice with each copy of the work that the+Library is used in it and that the Library and its use are covered by+this License. You must supply a copy of this License. If the work+during execution displays copyright notices, you must include the+copyright notice for the Library among them, as well as a reference+directing the user to the copy of this License. Also, you must do one+of these things:++ a) Accompany the work with the complete corresponding+ machine-readable source code for the Library including whatever+ changes were used in the work (which must be distributed under+ Sections 1 and 2 above); and, if the work is an executable linked+ with the Library, with the complete machine-readable "work that+ uses the Library", as object code and/or source code, so that the+ user can modify the Library and then relink to produce a modified+ executable containing the modified Library. (It is understood+ that the user who changes the contents of definitions files in the+ Library will not necessarily be able to recompile the application+ to use the modified definitions.)++ b) Use a suitable shared library mechanism for linking with the+ Library. A suitable mechanism is one that (1) uses at run time a+ copy of the library already present on the user's computer system,+ rather than copying library functions into the executable, and (2)+ will operate properly with a modified version of the library, if+ the user installs one, as long as the modified version is+ interface-compatible with the version that the work was made with.++ c) Accompany the work with a written offer, valid for at+ least three years, to give the same user the materials+ specified in Subsection 6a, above, for a charge no more+ than the cost of performing this distribution.++ d) If distribution of the work is made by offering access to copy+ from a designated place, offer equivalent access to copy the above+ specified materials from the same place.++ e) Verify that the user has already received a copy of these+ materials or that you have already sent this user a copy.++ For an executable, the required form of the "work that uses the+Library" must include any data and utility programs needed for+reproducing the executable from it. However, as a special exception,+the materials to be distributed need not include anything that is+normally distributed (in either source or binary form) with the major+components (compiler, kernel, and so on) of the operating system on+which the executable runs, unless that component itself accompanies+the executable.++ It may happen that this requirement contradicts the license+restrictions of other proprietary libraries that do not normally+accompany the operating system. Such a contradiction means you cannot+use both them and the Library together in an executable that you+distribute.++ 7. You may place library facilities that are a work based on the+Library side-by-side in a single library together with other library+facilities not covered by this License, and distribute such a combined+library, provided that the separate distribution of the work based on+the Library and of the other library facilities is otherwise+permitted, and provided that you do these two things:++ a) Accompany the combined library with a copy of the same work+ based on the Library, uncombined with any other library+ facilities. This must be distributed under the terms of the+ Sections above.++ b) Give prominent notice with the combined library of the fact+ that part of it is a work based on the Library, and explaining+ where to find the accompanying uncombined form of the same work.++ 8. You may not copy, modify, sublicense, link with, or distribute+the Library except as expressly provided under this License. Any+attempt otherwise to copy, modify, sublicense, link with, or+distribute the Library is void, and will automatically terminate your+rights under this License. However, parties who have received copies,+or rights, from you under this License will not have their licenses+terminated so long as such parties remain in full compliance.++ 9. You are not required to accept this License, since you have not+signed it. However, nothing else grants you permission to modify or+distribute the Library or its derivative works. These actions are+prohibited by law if you do not accept this License. Therefore, by+modifying or distributing the Library (or any work based on the+Library), you indicate your acceptance of this License to do so, and+all its terms and conditions for copying, distributing or modifying+the Library or works based on it.++ 10. Each time you redistribute the Library (or any work based on the+Library), the recipient automatically receives a license from the+original licensor to copy, distribute, link with or modify the Library+subject to these terms and conditions. You may not impose any further+restrictions on the recipients' exercise of the rights granted herein.+You are not responsible for enforcing compliance by third parties with+this License.++ 11. If, as a consequence of a court judgment or allegation of patent+infringement or for any other reason (not limited to patent issues),+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+distribute so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you+may not distribute the Library at all. For example, if a patent+license would not permit royalty-free redistribution of the Library by+all those who receive copies directly or indirectly through you, then+the only way you could satisfy both it and this License would be to+refrain entirely from distribution of the Library.++If any portion of this section is held invalid or unenforceable under any+particular circumstance, the balance of the section is intended to apply,+and the section as a whole is intended to apply in other circumstances.++It is not the purpose of this section to induce you to infringe any+patents or other property right claims or to contest validity of any+such claims; this section has the sole purpose of protecting the+integrity of the free software distribution system which is+implemented by public license practices. Many people have made+generous contributions to the wide range of software distributed+through that system in reliance on consistent application of that+system; it is up to the author/donor to decide if he or she is willing+to distribute software through any other system and a licensee cannot+impose that choice.++This section is intended to make thoroughly clear what is believed to+be a consequence of the rest of this License.++ 12. If the distribution and/or use of the Library is restricted in+certain countries either by patents or by copyrighted interfaces, the+original copyright holder who places the Library under this License may add+an explicit geographical distribution limitation excluding those countries,+so that distribution is permitted only in or among countries not thus+excluded. In such case, this License incorporates the limitation as if+written in the body of this License.++ 13. The Free Software Foundation may publish revised and/or new+versions of the Lesser 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 Library+specifies a version number of this License which applies to it and+"any later version", you have the option of following the terms and+conditions either of that version or of any later version published by+the Free Software Foundation. If the Library does not specify a+license version number, you may choose any version ever published by+the Free Software Foundation.++ 14. If you wish to incorporate parts of the Library into other free+programs whose distribution conditions are incompatible with these,+write to the author to ask for permission. For software which is+copyrighted by the Free Software Foundation, write to the Free+Software Foundation; we sometimes make exceptions for this. Our+decision will be guided by the two goals of preserving the free status+of all derivatives of our free software and of promoting the sharing+and reuse of software generally.++ NO WARRANTY++ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR+OTHER PARTIES PROVIDE THE LIBRARY "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+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY+AND/OR REDISTRIBUTE THE LIBRARY 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+LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH+DAMAGES.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Libraries++ If you develop a new library, and you want it to be of the greatest+possible use to the public, we recommend making it free software that+everyone can redistribute and change. You can do so by permitting+redistribution under these terms (or, alternatively, under the terms of the+ordinary General Public License).++ To apply these terms, attach the following notices to the library. It is+safest to attach them to the start of each source file to most effectively+convey the exclusion of warranty; and each file should have at least the+"copyright" line and a pointer to where the full notice is found.++ <one line to give the library's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ This library is free software; you can redistribute it and/or+ modify it under the terms of the GNU Lesser General Public+ License as published by the Free Software Foundation; either+ version 2.1 of the License, or (at your option) any later version.++ This library 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+ Lesser General Public License for more details.++ You should have received a copy of the GNU Lesser General Public+ License along with this library; if not, write to the Free Software+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA++Also add information on how to contact you by electronic and paper mail.++You should also get your employer (if you work as a programmer) or your+school, if any, to sign a "copyright disclaimer" for the library, if+necessary. Here is a sample; alter the names:++ Yoyodyne, Inc., hereby disclaims all copyright interest in the+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.++ <signature of Ty Coon>, 1 April 1990+ Ty Coon, President of Vice++That's all there is to it!diff --git a/app/src/main/assets/licenses/GPL-2.0.txt b/app/src/main/assets/licenses/GPL-2.0.txtnew file mode 100644index 00000000..17cb2864--- /dev/null+++ b/app/src/main/assets/licenses/GPL-2.0.txt@@ -0,0 +1,117 @@+GNU GENERAL PUBLIC LICENSE+Version 2, June 1991++Copyright (C) 1989, 1991 Free Software Foundation, Inc.+51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA++Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.++Preamble++The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) 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 this service 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 make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.++For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. 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.++We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.++Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.++Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.++The precise terms and conditions for copying, distribution and modification follow.++TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION++0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".++Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.++1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.++You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.++2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:++ a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.++ b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.++ c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)++These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.++Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.++In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.++3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:++ a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,++ b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,++ c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)++The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.++If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.++4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.++5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.++6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.++7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.++If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.++It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.++This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.++8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.++9. The Free Software Foundation may publish revised and/or new versions of the 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 a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.++10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.++NO WARRANTY++11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.++12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE 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.++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 convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.++ one line to give the program's name and an idea of what it does. Copyright (C) yyyy name of author++ 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 2 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail.++If the program is interactive, make it output a short notice like this when it starts in an interactive mode:++ Gnomovision version 69, Copyright (C) year name of author Gnomovision 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, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.++You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:++ Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker.++signature of Ty Coon, 1 April 1989 Ty Coon, President of Vicediff --git a/app/src/main/assets/licenses/SLF4J-MIT.txt b/app/src/main/assets/licenses/SLF4J-MIT.txtnew file mode 100644index 00000000..1a3d0532--- /dev/null+++ b/app/src/main/assets/licenses/SLF4J-MIT.txt@@ -0,0 +1,24 @@+Copyright (c) 2004-2022 QOS.ch Sarl (Switzerland)+All rights reserved.++Permission is hereby granted, free of charge, to any person obtaining+a copy of this software and associated documentation files (the+"Software"), to deal in the Software without restriction, including+without limitation the rights to use, copy, modify, merge, publish,+distribute, sublicense, and/or sell copies of the Software, and to+permit persons to whom the Software is furnished to do so, subject to+the following conditions:++The above copyright notice and this permission notice shall be+included in all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.+++diff --git a/app/src/main/assets/licenses/THIRD-PARTY-NOTICES.txt b/app/src/main/assets/licenses/THIRD-PARTY-NOTICES.txtnew file mode 100644index 00000000..e924e804--- /dev/null+++ b/app/src/main/assets/licenses/THIRD-PARTY-NOTICES.txt@@ -0,0 +1,51 @@+THIRD-PARTY SOFTWARE NOTICES++This app includes third-party software. Each component remains under its own license; these terms are separate from the StreamVault project license.++jcifs-ng 2.1.10+License: GNU Lesser General Public License 2.1 or later.+License text: jcifs-ng-LGPL-2.1.txt and GPL-2.0.txt.+Corresponding source: https://github.com/AgNO3/jcifs-ng/tree/jcifs-ng-2.1.10++Bouncy Castle Provider (bcprov-jdk18on) 1.76+Dependency: jcifs-ng 2.1.10.+License: Bouncy Castle License.+License text: BouncyCastle-LICENSE.html.+Corresponding source: https://github.com/bcgit/bc-java/tree/r1rv76++SLF4J API 1.7.36+Dependency: jcifs-ng 2.1.10.+License: MIT.+License text: SLF4J-MIT.txt.+Corresponding source: https://github.com/qos-ch/slf4j/tree/v_1.7.36++AndroidX Media3 libraries, including the FFmpeg decoder wrapper 1.11.0+Copyright (C) 2016 The Android Open Source Project.+License: Apache License 2.0.+License text: Apache-2.0.txt.+Corresponding source: https://github.com/androidx/media/tree/2bc207851df311340767e913931ca7b28cab1794/libraries/decoder_ffmpeg++Other packaged app libraries, including non-Media3 AndroidX, Kotlin/Kotlinx, Dagger/Hilt, OkHttp/Retrofit, Gson, Coil, ZXing, and core-library desugaring+License: Apache License 2.0.+License text: Apache-2.0.txt.+Versions are recorded in the app's Gradle catalog and module declarations.++FFmpeg decoder libraries+License target: GNU Lesser General Public License 2.1 or later, according to the recorded LGPL-compatible build configuration.+License text: FFmpeg-LGPL-2.1.txt and GPL-2.0.txt.+Corresponding source: https://github.com/FFmpeg/FFmpeg/tree/ba69be84a1ceabfb39127831ad8da0fd7cb471f3+The Media3 decoder README at the source revision above describes building the FFmpeg libraries and decoder AAR. Build provenance is recorded at https://github.com/Davidona/StreamVault-IPTV/blob/master/player/libs/media3-decoder-ffmpeg-1.11.0.properties.++libtorrent4j 2.0.6-26+License: MIT.+License text: libtorrent4j-MIT.txt.+Corresponding source: https://github.com/aldenml/libtorrent4j/tree/v2.0.6-26++libtorrent native library+License: BSD-3-Clause.+License and bundled component notices: libtorrent-BSD-3-Clause.txt.+Corresponding source: https://github.com/arvidn/libtorrent/tree/ed88357b4cdf7ae9d4b35aa77e654afbe2b7b11c++The libtorrent notice bundle includes an Apple route.h notice under the Apple Public Source License 2.0. The license text is provided as APSL-2.0.txt.++The source for StreamVault is published at https://github.com/Davidona/StreamVault-IPTV. For detailed source references and rebuild notes, see https://github.com/Davidona/StreamVault-IPTV/blob/master/docs/THIRD-PARTY-LICENSES.md.diff --git a/app/src/main/assets/licenses/jcifs-ng-LGPL-2.1.txt b/app/src/main/assets/licenses/jcifs-ng-LGPL-2.1.txtnew file mode 100644index 00000000..19e30718--- /dev/null+++ b/app/src/main/assets/licenses/jcifs-ng-LGPL-2.1.txt@@ -0,0 +1,504 @@+ GNU LESSER GENERAL PUBLIC LICENSE+ Version 2.1, February 1999++ Copyright (C) 1991, 1999 Free Software Foundation, Inc.+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++(This is the first released version of the Lesser GPL. It also counts+ as the successor of the GNU Library Public License, version 2, hence+ the version number 2.1.)++ Preamble++ The licenses for most software are designed to take away your+freedom to share and change it. By contrast, the GNU General Public+Licenses are intended to guarantee your freedom to share and change+free software--to make sure the software is free for all its users.++ This license, the Lesser General Public License, applies to some+specially designated software packages--typically libraries--of the+Free Software Foundation and other authors who decide to use it. You+can use it too, but we suggest you first think carefully about whether+this license or the ordinary General Public License is the better+strategy to use in any particular case, based on the explanations below.++ When we speak of free software, we are referring to freedom of use,+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 this service if you wish); that you receive source code or can get+it if you want it; that you can change the software and use pieces of+it in new free programs; and that you are informed that you can do+these things.++ To protect your rights, we need to make restrictions that forbid+distributors to deny you these rights or to ask you to surrender these+rights. These restrictions translate to certain responsibilities for+you if you distribute copies of the library or if you modify it.++ For example, if you distribute copies of the library, whether gratis+or for a fee, you must give the recipients all the rights that we gave+you. You must make sure that they, too, receive or can get the source+code. If you link other code with the library, you must provide+complete object files to the recipients, so that they can relink them+with the library after making changes to the library and recompiling+it. And you must show them these terms so they know their rights.++ We protect your rights with a two-step method: (1) we copyright the+library, and (2) we offer you this license, which gives you legal+permission to copy, distribute and/or modify the library.++ To protect each distributor, we want to make it very clear that+there is no warranty for the free library. Also, if the library is+modified by someone else and passed on, the recipients should know+that what they have is not the original version, so that the original+author's reputation will not be affected by problems that might be+introduced by others.++ Finally, software patents pose a constant threat to the existence of+any free program. We wish to make sure that a company cannot+effectively restrict the users of a free program by obtaining a+restrictive license from a patent holder. Therefore, we insist that+any patent license obtained for a version of the library must be+consistent with the full freedom of use specified in this license.++ Most GNU software, including some libraries, is covered by the+ordinary GNU General Public License. This license, the GNU Lesser+General Public License, applies to certain designated libraries, and+is quite different from the ordinary General Public License. We use+this license for certain libraries in order to permit linking those+libraries into non-free programs.++ When a program is linked with a library, whether statically or using+a shared library, the combination of the two is legally speaking a+combined work, a derivative of the original library. The ordinary+General Public License therefore permits such linking only if the+entire combination fits its criteria of freedom. The Lesser General+Public License permits more lax criteria for linking other code with+the library.++ We call this license the "Lesser" General Public License because it+does Less to protect the user's freedom than the ordinary General+Public License. It also provides other free software developers Less+of an advantage over competing non-free programs. These disadvantages+are the reason we use the ordinary General Public License for many+libraries. However, the Lesser license provides advantages in certain+special circumstances.++ For example, on rare occasions, there may be a special need to+encourage the widest possible use of a certain library, so that it becomes+a de-facto standard. To achieve this, non-free programs must be+allowed to use the library. A more frequent case is that a free+library does the same job as widely used non-free libraries. In this+case, there is little to gain by limiting the free library to free+software only, so we use the Lesser General Public License.++ In other cases, permission to use a particular library in non-free+programs enables a greater number of people to use a large body of+free software. For example, permission to use the GNU C Library in+non-free programs enables many more people to use the whole GNU+operating system, as well as its variant, the GNU/Linux operating+system.++ Although the Lesser General Public License is Less protective of the+users' freedom, it does ensure that the user of a program that is+linked with the Library has the freedom and the wherewithal to run+that program using a modified version of the Library.++ The precise terms and conditions for copying, distribution and+modification follow. Pay close attention to the difference between a+"work based on the library" and a "work that uses the library". The+former contains code derived from the library, whereas the latter must+be combined with the library in order to run.++ GNU LESSER GENERAL PUBLIC LICENSE+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION++ 0. This License Agreement applies to any software library or other+program which contains a notice placed by the copyright holder or+other authorized party saying it may be distributed under the terms of+this Lesser General Public License (also called "this License").+Each licensee is addressed as "you".++ A "library" means a collection of software functions and/or data+prepared so as to be conveniently linked with application programs+(which use some of those functions and data) to form executables.++ The "Library", below, refers to any such software library or work+which has been distributed under these terms. A "work based on the+Library" means either the Library or any derivative work under+copyright law: that is to say, a work containing the Library or a+portion of it, either verbatim or with modifications and/or translated+straightforwardly into another language. (Hereinafter, translation is+included without limitation in the term "modification".)++ "Source code" for a work means the preferred form of the work for+making modifications to it. For a library, complete source code means+all the source code for all modules it contains, plus any associated+interface definition files, plus the scripts used to control compilation+and installation of the library.++ Activities other than copying, distribution and modification are not+covered by this License; they are outside its scope. The act of+running a program using the Library is not restricted, and output from+such a program is covered only if its contents constitute a work based+on the Library (independent of the use of the Library in a tool for+writing it). Whether that is true depends on what the Library does+and what the program that uses the Library does.++ 1. You may copy and distribute verbatim copies of the Library's+complete source code as you receive it, in any medium, provided that+you conspicuously and appropriately publish on each copy an+appropriate copyright notice and disclaimer of warranty; keep intact+all the notices that refer to this License and to the absence of any+warranty; and distribute a copy of this License along with the+Library.++ You may charge a fee for the physical act of transferring a copy,+and you may at your option offer warranty protection in exchange for a+fee.++ 2. You may modify your copy or copies of the Library or any portion+of it, thus forming a work based on the Library, and copy and+distribute such modifications or work under the terms of Section 1+above, provided that you also meet all of these conditions:++ a) The modified work must itself be a software library.++ b) You must cause the files modified to carry prominent notices+ stating that you changed the files and the date of any change.++ c) You must cause the whole of the work to be licensed at no+ charge to all third parties under the terms of this License.++ d) If a facility in the modified Library refers to a function or a+ table of data to be supplied by an application program that uses+ the facility, other than as an argument passed when the facility+ is invoked, then you must make a good faith effort to ensure that,+ in the event an application does not supply such function or+ table, the facility still operates, and performs whatever part of+ its purpose remains meaningful.++ (For example, a function in a library to compute square roots has+ a purpose that is entirely well-defined independent of the+ application. Therefore, Subsection 2d requires that any+ application-supplied function or table used by this function must+ be optional: if the application does not supply it, the square+ root function must still compute square roots.)++These requirements apply to the modified work as a whole. If+identifiable sections of that work are not derived from the Library,+and can be reasonably considered independent and separate works in+themselves, then this License, and its terms, do not apply to those+sections when you distribute them as separate works. But when you+distribute the same sections as part of a whole which is a work based+on the Library, the distribution of the whole must be on the terms of+this License, whose permissions for other licensees extend to the+entire whole, and thus to each and every part regardless of who wrote+it.++Thus, it is not the intent of this section to claim rights or contest+your rights to work written entirely by you; rather, the intent is to+exercise the right to control the distribution of derivative or+collective works based on the Library.++In addition, mere aggregation of another work not based on the Library+with the Library (or with a work based on the Library) on a volume of+a storage or distribution medium does not bring the other work under+the scope of this License.++ 3. You may opt to apply the terms of the ordinary GNU General Public+License instead of this License to a given copy of the Library. To do+this, you must alter all the notices that refer to this License, so+that they refer to the ordinary GNU General Public License, version 2,+instead of to this License. (If a newer version than version 2 of the+ordinary GNU General Public License has appeared, then you can specify+that version instead if you wish.) Do not make any other change in+these notices.++ Once this change is made in a given copy, it is irreversible for+that copy, so the ordinary GNU General Public License applies to all+subsequent copies and derivative works made from that copy.++ This option is useful when you wish to copy part of the code of+the Library into a program that is not a library.++ 4. You may copy and distribute the Library (or a portion or+derivative of it, under Section 2) in object code or executable form+under the terms of Sections 1 and 2 above provided that you accompany+it with the complete corresponding machine-readable source code, which+must be distributed under the terms of Sections 1 and 2 above on a+medium customarily used for software interchange.++ If distribution of object code is made by offering access to copy+from a designated place, then offering equivalent access to copy the+source code from the same place satisfies the requirement to+distribute the source code, even though third parties are not+compelled to copy the source along with the object code.++ 5. A program that contains no derivative of any portion of the+Library, but is designed to work with the Library by being compiled or+linked with it, is called a "work that uses the Library". Such a+work, in isolation, is not a derivative work of the Library, and+therefore falls outside the scope of this License.++ However, linking a "work that uses the Library" with the Library+creates an executable that is a derivative of the Library (because it+contains portions of the Library), rather than a "work that uses the+library". The executable is therefore covered by this License.+Section 6 states terms for distribution of such executables.++ When a "work that uses the Library" uses material from a header file+that is part of the Library, the object code for the work may be a+derivative work of the Library even though the source code is not.+Whether this is true is especially significant if the work can be+linked without the Library, or if the work is itself a library. The+threshold for this to be true is not precisely defined by law.++ If such an object file uses only numerical parameters, data+structure layouts and accessors, and small macros and small inline+functions (ten lines or less in length), then the use of the object+file is unrestricted, regardless of whether it is legally a derivative+work. (Executables containing this object code plus portions of the+Library will still fall under Section 6.)++ Otherwise, if the work is a derivative of the Library, you may+distribute the object code for the work under the terms of Section 6.+Any executables containing that work also fall under Section 6,+whether or not they are linked directly with the Library itself.++ 6. As an exception to the Sections above, you may also combine or+link a "work that uses the Library" with the Library to produce a+work containing portions of the Library, and distribute that work+under terms of your choice, provided that the terms permit+modification of the work for the customer's own use and reverse+engineering for debugging such modifications.++ You must give prominent notice with each copy of the work that the+Library is used in it and that the Library and its use are covered by+this License. You must supply a copy of this License. If the work+during execution displays copyright notices, you must include the+copyright notice for the Library among them, as well as a reference+directing the user to the copy of this License. Also, you must do one+of these things:++ a) Accompany the work with the complete corresponding+ machine-readable source code for the Library including whatever+ changes were used in the work (which must be distributed under+ Sections 1 and 2 above); and, if the work is an executable linked+ with the Library, with the complete machine-readable "work that+ uses the Library", as object code and/or source code, so that the+ user can modify the Library and then relink to produce a modified+ executable containing the modified Library. (It is understood+ that the user who changes the contents of definitions files in the+ Library will not necessarily be able to recompile the application+ to use the modified definitions.)++ b) Use a suitable shared library mechanism for linking with the+ Library. A suitable mechanism is one that (1) uses at run time a+ copy of the library already present on the user's computer system,+ rather than copying library functions into the executable, and (2)+ will operate properly with a modified version of the library, if+ the user installs one, as long as the modified version is+ interface-compatible with the version that the work was made with.++ c) Accompany the work with a written offer, valid for at+ least three years, to give the same user the materials+ specified in Subsection 6a, above, for a charge no more+ than the cost of performing this distribution.++ d) If distribution of the work is made by offering access to copy+ from a designated place, offer equivalent access to copy the above+ specified materials from the same place.++ e) Verify that the user has already received a copy of these+ materials or that you have already sent this user a copy.++ For an executable, the required form of the "work that uses the+Library" must include any data and utility programs needed for+reproducing the executable from it. However, as a special exception,+the materials to be distributed need not include anything that is+normally distributed (in either source or binary form) with the major+components (compiler, kernel, and so on) of the operating system on+which the executable runs, unless that component itself accompanies+the executable.++ It may happen that this requirement contradicts the license+restrictions of other proprietary libraries that do not normally+accompany the operating system. Such a contradiction means you cannot+use both them and the Library together in an executable that you+distribute.++ 7. You may place library facilities that are a work based on the+Library side-by-side in a single library together with other library+facilities not covered by this License, and distribute such a combined+library, provided that the separate distribution of the work based on+the Library and of the other library facilities is otherwise+permitted, and provided that you do these two things:++ a) Accompany the combined library with a copy of the same work+ based on the Library, uncombined with any other library+ facilities. This must be distributed under the terms of the+ Sections above.++ b) Give prominent notice with the combined library of the fact+ that part of it is a work based on the Library, and explaining+ where to find the accompanying uncombined form of the same work.++ 8. You may not copy, modify, sublicense, link with, or distribute+the Library except as expressly provided under this License. Any+attempt otherwise to copy, modify, sublicense, link with, or+distribute the Library is void, and will automatically terminate your+rights under this License. However, parties who have received copies,+or rights, from you under this License will not have their licenses+terminated so long as such parties remain in full compliance.++ 9. You are not required to accept this License, since you have not+signed it. However, nothing else grants you permission to modify or+distribute the Library or its derivative works. These actions are+prohibited by law if you do not accept this License. Therefore, by+modifying or distributing the Library (or any work based on the+Library), you indicate your acceptance of this License to do so, and+all its terms and conditions for copying, distributing or modifying+the Library or works based on it.++ 10. Each time you redistribute the Library (or any work based on the+Library), the recipient automatically receives a license from the+original licensor to copy, distribute, link with or modify the Library+subject to these terms and conditions. You may not impose any further+restrictions on the recipients' exercise of the rights granted herein.+You are not responsible for enforcing compliance by third parties with+this License.++ 11. If, as a consequence of a court judgment or allegation of patent+infringement or for any other reason (not limited to patent issues),+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+distribute so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you+may not distribute the Library at all. For example, if a patent+license would not permit royalty-free redistribution of the Library by+all those who receive copies directly or indirectly through you, then+the only way you could satisfy both it and this License would be to+refrain entirely from distribution of the Library.++If any portion of this section is held invalid or unenforceable under any+particular circumstance, the balance of the section is intended to apply,+and the section as a whole is intended to apply in other circumstances.++It is not the purpose of this section to induce you to infringe any+patents or other property right claims or to contest validity of any+such claims; this section has the sole purpose of protecting the+integrity of the free software distribution system which is+implemented by public license practices. Many people have made+generous contributions to the wide range of software distributed+through that system in reliance on consistent application of that+system; it is up to the author/donor to decide if he or she is willing+to distribute software through any other system and a licensee cannot+impose that choice.++This section is intended to make thoroughly clear what is believed to+be a consequence of the rest of this License.++ 12. If the distribution and/or use of the Library is restricted in+certain countries either by patents or by copyrighted interfaces, the+original copyright holder who places the Library under this License may add+an explicit geographical distribution limitation excluding those countries,+so that distribution is permitted only in or among countries not thus+excluded. In such case, this License incorporates the limitation as if+written in the body of this License.++ 13. The Free Software Foundation may publish revised and/or new+versions of the Lesser 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 Library+specifies a version number of this License which applies to it and+"any later version", you have the option of following the terms and+conditions either of that version or of any later version published by+the Free Software Foundation. If the Library does not specify a+license version number, you may choose any version ever published by+the Free Software Foundation.++ 14. If you wish to incorporate parts of the Library into other free+programs whose distribution conditions are incompatible with these,+write to the author to ask for permission. For software which is+copyrighted by the Free Software Foundation, write to the Free+Software Foundation; we sometimes make exceptions for this. Our+decision will be guided by the two goals of preserving the free status+of all derivatives of our free software and of promoting the sharing+and reuse of software generally.++ NO WARRANTY++ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR+OTHER PARTIES PROVIDE THE LIBRARY "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+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY+AND/OR REDISTRIBUTE THE LIBRARY 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+LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH+DAMAGES.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Libraries++ If you develop a new library, and you want it to be of the greatest+possible use to the public, we recommend making it free software that+everyone can redistribute and change. You can do so by permitting+redistribution under these terms (or, alternatively, under the terms of the+ordinary General Public License).++ To apply these terms, attach the following notices to the library. It is+safest to attach them to the start of each source file to most effectively+convey the exclusion of warranty; and each file should have at least the+"copyright" line and a pointer to where the full notice is found.++ {description}+ Copyright (C) {year} {fullname}++ This library is free software; you can redistribute it and/or+ modify it under the terms of the GNU Lesser General Public+ License as published by the Free Software Foundation; either+ version 2.1 of the License, or (at your option) any later version.++ This library 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+ Lesser General Public License for more details.++ You should have received a copy of the GNU Lesser General Public+ License along with this library; if not, write to the Free Software+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301+ USA++Also add information on how to contact you by electronic and paper mail.++You should also get your employer (if you work as a programmer) or your+school, if any, to sign a "copyright disclaimer" for the library, if+necessary. Here is a sample; alter the names:++ Yoyodyne, Inc., hereby disclaims all copyright interest in the+ library `Frob' (a library for tweaking knobs) written by James Random+ Hacker.++ {signature of Ty Coon}, 1 April 1990+ Ty Coon, President of Vice++That's all there is to it!diff --git a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.ktindex dee7d782..1f92d27a 100644--- a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt+++ b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt@@ -120,6 +120,8 @@ import com.streamvault.domain.manager.PortableVirtualGroupReferenceimport com.streamvault.domain.manager.RecordingManagerimport com.streamvault.domain.manager.ScheduledRecordingBackupimport com.streamvault.domain.manager.ProviderCredentials+import com.streamvault.domain.manager.SportsProviderBackup+import com.streamvault.domain.manager.SportsProviderCredentialsBackupimport com.streamvault.domain.model.AppTopLevelDestinationimport com.streamvault.domain.model.AppHomeDashboardShelfimport com.streamvault.domain.model.ActiveLiveSource@@ -146,6 +148,17 @@ import com.streamvault.domain.model.StalkerProfileVerificationimport com.streamvault.domain.model.StalkerProtocolFamilyimport com.streamvault.domain.model.StalkerProtocolPreferenceimport com.streamvault.domain.model.StalkerTransportMode+import com.streamvault.domain.sports.provider.SportsEventSourceMode+import com.streamvault.domain.sports.provider.SportsEventSourcePreference+import com.streamvault.domain.sports.provider.SportsScoreSourceMode+import com.streamvault.domain.sports.provider.SportsScoreSourcePreference+import com.streamvault.domain.sports.provider.SportsStandingsSourceMode+import com.streamvault.domain.sports.provider.SportsStandingsSourcePreference+import com.streamvault.domain.sports.provider.SportsMetadataSourceMode+import com.streamvault.domain.sports.provider.SportsMetadataSourcePreference+import com.streamvault.domain.sports.provider.SportsProviderConfig+import com.streamvault.domain.sports.provider.SportsProviderCredentials+import com.streamvault.domain.sports.provider.SportsProviderStoreimport com.streamvault.data.remote.stremio.StremioAddonUrlimport com.streamvault.domain.repository.CategoryRepositoryimport dagger.hilt.android.qualifiers.ApplicationContext@@ -211,7 +224,8 @@ class BackupManagerImpl @Inject constructor(private val pendingBackupRestoreCoordinator: PendingBackupRestoreCoordinator? = null,private val playbackQualityPreferenceDao: PlaybackQualityPreferenceDao? = null,private val stremioAddonDao: StremioAddonDao? = null,- private val stremioPlaybackHistoryDao: StremioPlaybackHistoryDao? = null+ private val stremioPlaybackHistoryDao: StremioPlaybackHistoryDao? = null,+ private val sportsProviderStore: SportsProviderStore? = null) : BackupManager {internal suspend fun automaticSyncPreferenceBackup(providerEntities: List<ProviderEntity>): Map<String, String> {@@ -229,6 +243,17 @@ class BackupManagerImpl @Inject constructor(try {val parentalPinBackup = preferencesRepository.exportParentalPinBackup()val providerEntities = providerDao.getAll().first()+ val sportsStore = sportsProviderStore+ val sportsProviderConfigs = sportsStore?.configurations()+ val sportsProviderCredentials = sportsProviderConfigs.orEmpty().mapNotNull { config ->+ sportsStore?.credentials(config.instanceId)?.let { credentials ->+ SportsProviderCredentialsBackup(+ instanceId = config.instanceId,+ secret = credentials.secret,+ username = credentials.username+ )+ }+ }// 1. Gather Dataval prefs = buildMap<String, String> {@@ -245,6 +270,7 @@ class BackupManagerImpl @Inject constructor("appTopLevelDestinations",preferencesRepository.appTopLevelDestinations.first().joinToString(",") { it.storageValue })+ putAll(sportsSourcePreferenceBackup())put("appHomeDashboardShelves",preferencesRepository.appHomeDashboardShelves.first().joinToString(",") { it.storageValue }@@ -843,6 +869,8 @@ class BackupManagerImpl @Inject constructor(portableProviderPreferences = portableProviderPreferences,recordingStorage = recordingStorage,providerCredentials = providerCredentials.takeIf { it.isNotEmpty() },+ sportsProviders = sportsProviderConfigs?.map(SportsProviderConfig::toBackup),+ sportsProviderCredentials = sportsProviderCredentials.takeIf { it.isNotEmpty() },epgSources = epgSourceDao?.getAllSync()?.map { it.toDomain() },providerEpgAssignments = providerEpgAssignments,manualEpgMappings = null,@@ -932,6 +960,9 @@ class BackupManagerImpl @Inject constructor(val existingStremioHistoryKeys = stremioPlaybackHistoryDao?.getAll()?.mapTo(hashSetOf()) { it.contentKey }.orEmpty()+ val existingSportsProviderIds = sportsProviderStore?.configurations()+ ?.mapTo(hashSetOf()) { it.instanceId }+ .orEmpty()val existingProtectedCategories = existingProviders.flatMap { provider ->categoryRepository.getCategories(provider.id).first().filter { it.isUserProtected }@@ -992,6 +1023,9 @@ class BackupManagerImpl @Inject constructor(}}val providerConflicts = backupData.providers.orEmpty().count { it.backupIdentity() in providersByIdentity }+ val sportsProviderConflicts = backupData.sportsProviders.orEmpty().count {+ it.instanceId in existingSportsProviderIds+ }val groupConflicts = if (backupData.portableCustomGroups != null) {backupData.portableCustomGroups.orEmpty().count { group ->val targetProviderId = existingProviders.findUnambiguousPortableProvider(group.provider)?.id@@ -1067,7 +1101,7 @@ class BackupManagerImpl @Inject constructor(Result.success(BackupPreview(version = backupData.version,- providerCount = backupData.providers.orEmpty().size,+ providerCount = backupData.providers.orEmpty().size + backupData.sportsProviders.orEmpty().size,favoriteCount = if (backupData.portableFavorites != null || backupData.portableCustomGroups != null) {@@ -1087,7 +1121,7 @@ class BackupManagerImpl @Inject constructor(preferenceCount = backupData.preferences.orEmpty().size,protectedCategoryCount = backupData.protectedCategories.orEmpty().size,scheduledRecordingCount = backupData.scheduledRecordings.orEmpty().normalizedRecurringBackups().size,- providerConflicts = providerConflicts,+ providerConflicts = providerConflicts + sportsProviderConflicts,favoriteConflicts = favoriteConflicts,groupConflicts = groupConflicts,historyConflicts = historyConflicts + backupData.stremioPlaybackHistory.orEmpty().count {@@ -1143,6 +1177,7 @@ class BackupManagerImpl @Inject constructor(val skippedSections = mutableListOf<String>()val failedSections = mutableListOf<String>()val unresolvedReferences = mutableListOf<String>()+ var restoreSportsSourceReferences = plan.importProvidersif (!checkpoint.roomComplete) {val roomCheckpoint = checkpoint.copy(@@ -1186,6 +1221,26 @@ class BackupManagerImpl @Inject constructor(skippedSections += skippedRoomSections(backupData, plan)}+ if (backupData.sportsProviders != null) {+ if (plan.importProviders) {+ try {+ restoreSportsProviders(+ providers = backupData.sportsProviders.orEmpty(),+ credentials = backupData.sportsProviderCredentials.orEmpty(),+ conflictStrategy = plan.conflictStrategy+ )+ importedSections += "Providers"+ skippedSections.remove("Providers")+ } catch (_: Exception) {+ restoreSportsSourceReferences = false+ failedSections += "Providers"+ }+ } else {+ restoreSportsSourceReferences = false+ skippedSections += "Providers"+ }+ }+if (plan.importPreferences) {val preferences = backupData.preferencesval portablePreferences = backupData.portableProviderPreferences@@ -1201,7 +1256,11 @@ class BackupManagerImpl @Inject constructor(restoreCheckpointPreferenceSnapshot(snapshot)}preferences?.let {- restorePreferences(it, skipProviderScopedReferences = portablePreferences != null)+ restorePreferences(+ it,+ skipProviderScopedReferences = portablePreferences != null,+ skipSportsProviderReferences = !restoreSportsSourceReferences+ )}val preferenceUnresolved = portablePreferences?.let { portable ->restorePortableProviderPreferences(@@ -1525,7 +1584,7 @@ class BackupManagerImpl @Inject constructor(}private fun importedRoomSections(backupData: BackupData, plan: BackupImportPlan): List<String> = buildList {- if (plan.importProviders && backupData.providers != null) add("Providers")+ if (plan.importProviders && (backupData.providers != null || backupData.sportsProviders != null)) add("Providers")if (plan.importProviders && backupData.combinedM3uProfiles != null) add("Combined M3U Profiles")if (plan.importProviders && backupData.epgSources != null && epgSourceDao != null) add("EPG Sources")if (plan.importSavedLibrary) add("Saved Library")@@ -1534,7 +1593,7 @@ class BackupManagerImpl @Inject constructor(}private fun skippedRoomSections(backupData: BackupData, plan: BackupImportPlan): List<String> = buildList {- if (!plan.importProviders || backupData.providers == null) add("Providers")+ if (!plan.importProviders || (backupData.providers == null && backupData.sportsProviders == null)) add("Providers")if (!plan.importProviders || backupData.combinedM3uProfiles == null) add("Combined M3U Profiles")if (!plan.importProviders || backupData.epgSources == null || epgSourceDao == null) add("EPG Sources")if (!plan.importSavedLibrary) add("Saved Library")@@ -1608,6 +1667,13 @@ class BackupManagerImpl @Inject constructor(writeNamedJsonField(jsonWriter, "providers", backupData.providers, PROVIDER_LIST_TYPE)writeNamedJsonField(jsonWriter, "providerSnapshots", backupData.providerSnapshots, PROVIDER_SNAPSHOT_LIST_TYPE)writeNamedJsonField(jsonWriter, "providerCredentials", backupData.providerCredentials, PROVIDER_CREDENTIALS_LIST_TYPE)+ writeNamedJsonField(jsonWriter, "sportsProviders", backupData.sportsProviders, SPORTS_PROVIDER_BACKUP_LIST_TYPE)+ writeNamedJsonField(+ jsonWriter,+ "sportsProviderCredentials",+ backupData.sportsProviderCredentials,+ SPORTS_PROVIDER_CREDENTIALS_BACKUP_LIST_TYPE+ )writeNamedJsonField(jsonWriter, "favorites", backupData.favorites, FAVORITE_LIST_TYPE)writeNamedJsonField(jsonWriter, "virtualGroups", backupData.virtualGroups, VIRTUAL_GROUP_LIST_TYPE)writeNamedJsonField(jsonWriter, "playbackHistory", backupData.playbackHistory, PLAYBACK_HISTORY_LIST_TYPE)@@ -1804,6 +1870,8 @@ class BackupManagerImpl @Inject constructor(var providers: List<com.streamvault.domain.model.LegacyProvider>? = nullvar providerSnapshots: List<ProviderBackupSnapshot>? = nullvar providerCredentials: List<ProviderCredentials>? = null+ var sportsProviders: List<SportsProviderBackup>? = null+ var sportsProviderCredentials: List<SportsProviderCredentialsBackup>? = nullvar favorites: List<com.streamvault.domain.model.Favorite>? = nullvar virtualGroups: List<com.streamvault.domain.model.VirtualGroup>? = nullvar playbackHistory: List<com.streamvault.domain.model.PlaybackHistory>? = null@@ -1869,6 +1937,14 @@ class BackupManagerImpl @Inject constructor(readLimitedArray(reader, PROVIDER_SNAPSHOT_TYPE, MAX_PROVIDERS, "provider snapshots")"providerCredentials" -> providerCredentials =readLimitedArray(reader, PROVIDER_CREDENTIALS_TYPE, MAX_PROVIDERS, "provider credentials")+ "sportsProviders" -> sportsProviders =+ readLimitedArray(reader, SPORTS_PROVIDER_BACKUP_TYPE, MAX_PROVIDERS, "providers")+ "sportsProviderCredentials" -> sportsProviderCredentials = readLimitedArray(+ reader,+ SPORTS_PROVIDER_CREDENTIALS_BACKUP_TYPE,+ MAX_PROVIDERS,+ "provider credentials"+ )"favorites" -> favorites = readLimitedArray(reader, FAVORITE_TYPE, MAX_SECTION_ITEMS, "favorites")"virtualGroups" -> virtualGroups =readLimitedArray(reader, VIRTUAL_GROUP_TYPE, MAX_SECTION_ITEMS, "groups")@@ -1983,6 +2059,8 @@ class BackupManagerImpl @Inject constructor(providers = providers,providerSnapshots = providerSnapshots,providerCredentials = providerCredentials,+ sportsProviders = sportsProviders,+ sportsProviderCredentials = sportsProviderCredentials,favorites = favorites,virtualGroups = virtualGroups,playbackHistory = playbackHistory,@@ -2523,6 +2601,18 @@ class BackupManagerImpl @Inject constructor(require(data.providers.orEmpty().size <= MAX_PROVIDERS) { "Backup has too many providers" }require(data.providerSnapshots.orEmpty().size <= MAX_PROVIDERS) { "Backup has too many provider snapshots" }require(data.providerCredentials.orEmpty().size <= MAX_PROVIDERS) { "Backup has too many provider credentials" }+ require(data.sportsProviders.orEmpty().size <= MAX_PROVIDERS) { "Backup has too many providers" }+ require(data.sportsProviderCredentials.orEmpty().size <= MAX_PROVIDERS) {+ "Backup has too many provider credentials"+ }+ val sportsProviderIds = data.sportsProviders.orEmpty().map { backup ->+ backup.toSportsProviderConfig()+ backup.instanceId+ }+ require(sportsProviderIds.distinct().size == sportsProviderIds.size)+ val sportsCredentialIds = data.sportsProviderCredentials.orEmpty().map { it.instanceId }+ require(sportsCredentialIds.distinct().size == sportsCredentialIds.size)+ require(sportsCredentialIds.all { it in sportsProviderIds })data.providerSnapshots.orEmpty().forEach { it.configuration() }require(data.favorites.orEmpty().size <= MAX_SECTION_ITEMS) { "Backup has too many favorites" }require(data.virtualGroups.orEmpty().size <= MAX_SECTION_ITEMS) { "Backup has too many groups" }@@ -3389,6 +3479,8 @@ class BackupManagerImpl @Inject constructor(providers.isNullOrEmpty() &&providerSnapshots.isNullOrEmpty() &&providerCredentials.isNullOrEmpty() &&+ sportsProviders.isNullOrEmpty() &&+ sportsProviderCredentials.isNullOrEmpty() &&favorites.isNullOrEmpty() &&virtualGroups.isNullOrEmpty() &&playbackHistory.isNullOrEmpty() &&@@ -3432,6 +3524,7 @@ class BackupManagerImpl @Inject constructor(put("defaultViewMode", preferencesRepository.defaultViewMode.first().orEmpty())put("appLandingDestination", preferencesRepository.appLandingDestination.first().storageValue)put("appTopLevelDestinations", preferencesRepository.appTopLevelDestinations.first().joinToString(",") { it.storageValue })+ putAll(sportsSourcePreferenceBackup())put("appHomeDashboardShelves", preferencesRepository.appHomeDashboardShelves.first().joinToString(",") { it.storageValue })put("remoteShortcutPreferences", gson.toJson(preferencesRepository.remoteShortcutPreferences.first()))put("liveTvCategoryFilters", preferencesRepository.liveTvCategoryFilters.first().joinToString("\n"))@@ -3592,6 +3685,23 @@ class BackupManagerImpl @Inject constructor(}}+ private suspend fun sportsSourcePreferenceBackup(): Map<String, String> {+ val events = preferencesRepository.eventSourcePreference.first()+ val scores = preferencesRepository.scoreSourcePreference.first()+ val standings = preferencesRepository.standingsSourcePreference.first()+ val metadata = preferencesRepository.metadataSourcePreference.first()+ return mapOf(+ "sportsEventSourceMode" to events.mode.name,+ "sportsEventSourceInstanceId" to events.providerInstanceId.orEmpty(),+ "sportsScoreSourceMode" to scores.mode.name,+ "sportsScoreSourceInstanceId" to scores.providerInstanceId.orEmpty(),+ "sportsStandingsSourceMode" to standings.mode.name,+ "sportsStandingsSourceInstanceId" to standings.providerInstanceId.orEmpty(),+ "sportsMetadataSourceMode" to metadata.mode.name,+ "sportsMetadataSourceInstanceId" to metadata.providerInstanceId.orEmpty()+ )+ }+private suspend fun restoreCheckpointPreferenceSnapshot(snapshot: Map<String, String>) {restorePreferences(snapshot)snapshot[RESTORE_SNAPSHOT_CHANNEL_PREFERENCES]?.let { encoded ->@@ -4001,7 +4111,8 @@ class BackupManagerImpl @Inject constructor(private suspend fun restorePreferences(prefs: Map<String, String>,- skipProviderScopedReferences: Boolean = false+ skipProviderScopedReferences: Boolean = false,+ skipSportsProviderReferences: Boolean = false) {prefs["automaticSyncDefaults"]?.let { encoded ->val settings = gson.fromJson(encoded, com.streamvault.domain.sync.AutomaticSyncSettings::class.java)@@ -4053,6 +4164,7 @@ class BackupManagerImpl @Inject constructor(preferencesRepository.setAppTopLevelDestinations(destinations)}}+ if (!skipSportsProviderReferences) restoreSportsSourcePreferences(prefs)if (prefs.containsKey("appHomeDashboardShelves")) {val shelves = prefs["appHomeDashboardShelves"].orEmpty()@@ -4415,6 +4527,100 @@ class BackupManagerImpl @Inject constructor(}}+ private suspend fun restoreSportsSourcePreferences(prefs: Map<String, String>) {+ val validId = Regex("[A-Za-z0-9][A-Za-z0-9._-]{0,127}")+ val eventMode: SportsEventSourceMode? = prefs["sportsEventSourceMode"]+ ?.let { raw -> SportsEventSourceMode.entries.firstOrNull { it.name == raw } }+ when (eventMode) {+ SportsEventSourceMode.AUTOMATIC ->+ preferencesRepository.setEventSourcePreference(SportsEventSourcePreference.AUTOMATIC)+ SportsEventSourceMode.EPG ->+ preferencesRepository.setEventSourcePreference(SportsEventSourcePreference.EPG)+ SportsEventSourceMode.PROVIDER -> prefs["sportsEventSourceInstanceId"]+ ?.takeIf(validId::matches)+ ?.let { instanceId -> preferencesRepository.setEventSourcePreference(SportsEventSourcePreference.provider(instanceId)) }+ null -> Unit+ }++ val scoreMode: SportsScoreSourceMode? = prefs["sportsScoreSourceMode"]+ ?.let { raw -> SportsScoreSourceMode.entries.firstOrNull { it.name == raw } }+ when (scoreMode) {+ SportsScoreSourceMode.AUTOMATIC ->+ preferencesRepository.setScoreSourcePreference(SportsScoreSourcePreference.AUTOMATIC)+ SportsScoreSourceMode.OFF ->+ preferencesRepository.setScoreSourcePreference(SportsScoreSourcePreference.OFF)+ SportsScoreSourceMode.PROVIDER -> prefs["sportsScoreSourceInstanceId"]+ ?.takeIf(validId::matches)+ ?.let { instanceId -> preferencesRepository.setScoreSourcePreference(SportsScoreSourcePreference.provider(instanceId)) }+ null -> Unit+ }++ val standingsMode: SportsStandingsSourceMode? = prefs["sportsStandingsSourceMode"]+ ?.let { raw -> SportsStandingsSourceMode.entries.firstOrNull { it.name == raw } }+ when (standingsMode) {+ SportsStandingsSourceMode.AUTOMATIC ->+ preferencesRepository.setStandingsSourcePreference(SportsStandingsSourcePreference.AUTOMATIC)+ SportsStandingsSourceMode.OFF ->+ preferencesRepository.setStandingsSourcePreference(SportsStandingsSourcePreference.OFF)+ SportsStandingsSourceMode.PROVIDER -> prefs["sportsStandingsSourceInstanceId"]+ ?.takeIf(validId::matches)+ ?.let { instanceId -> preferencesRepository.setStandingsSourcePreference(SportsStandingsSourcePreference.provider(instanceId)) }+ null -> Unit+ }++ val metadataMode: SportsMetadataSourceMode? = prefs["sportsMetadataSourceMode"]+ ?.let { raw -> SportsMetadataSourceMode.entries.firstOrNull { it.name == raw } }+ when (metadataMode) {+ SportsMetadataSourceMode.AUTOMATIC ->+ preferencesRepository.setMetadataSourcePreference(SportsMetadataSourcePreference.AUTOMATIC)+ SportsMetadataSourceMode.OFF ->+ preferencesRepository.setMetadataSourcePreference(SportsMetadataSourcePreference.OFF)+ SportsMetadataSourceMode.PROVIDER -> prefs["sportsMetadataSourceInstanceId"]+ ?.takeIf(validId::matches)+ ?.let { instanceId -> preferencesRepository.setMetadataSourcePreference(SportsMetadataSourcePreference.provider(instanceId)) }+ null -> Unit+ }+ }++ private suspend fun restoreSportsProviders(+ providers: List<SportsProviderBackup>,+ credentials: List<SportsProviderCredentialsBackup>,+ conflictStrategy: BackupConflictStrategy+ ) {+ val store = checkNotNull(sportsProviderStore)+ val configsById = store.configurations().associateByTo(linkedMapOf()) { it.instanceId }+ val credentialsById = credentials.associateBy { it.instanceId }+ providers.forEach { backup ->+ val imported = backup.toSportsProviderConfig()+ val existing = configsById[imported.instanceId]+ if (existing != null && conflictStrategy == BackupConflictStrategy.KEEP_EXISTING) {+ return@forEach+ }+ val restoredCredentials = credentialsById[imported.instanceId]?.let { saved ->+ SportsProviderCredentials(secret = saved.secret, username = saved.username)+ }+ val existingCredentials = existing?.let { store.credentials(it.instanceId) }+ val credentialsChanged = when {+ existingCredentials == null -> restoredCredentials != null+ restoredCredentials == null -> true+ else -> existingCredentials.secret != restoredCredentials.secret ||+ existingCredentials.username != restoredCredentials.username+ }+ if (existing != null && (existing.typeId != imported.typeId || restoredCredentials == null)) {+ store.remove(imported.instanceId)+ }+ val cacheRevision = when {+ existing == null -> 0L+ existing.typeId != imported.typeId -> 0L+ existing.toBackup() == backup && !credentialsChanged -> existing.cacheRevision+ else -> Math.addExact(existing.cacheRevision, 1L)+ }+ val config = imported.copy(cacheRevision = cacheRevision)+ store.save(config, restoredCredentials)+ configsById[config.instanceId] = config+ }+ }+private suspend fun restoreRemoteShortcutPreferences(encoded: String) {val restored = runCatching {gson.fromJson(@@ -6174,6 +6380,28 @@ private fun com.streamvault.domain.model.LegacyProvider.toSecureEntityForBackup(credentialCrypto: CredentialCrypto) = copy(password = credentialCrypto.encryptIfNeeded(password)).toEntity()+private fun SportsProviderConfig.toBackup(): SportsProviderBackup = SportsProviderBackup(+ instanceId = instanceId,+ typeId = typeId,+ configurationVersion = configurationVersion,+ enabled = enabled,+ priority = priority,+ baseUrl = baseUrl,+ eventLeagueIds = eventLeagueIds,+ customDefinitionJson = customDefinitionJson+)++private fun SportsProviderBackup.toSportsProviderConfig(): SportsProviderConfig = SportsProviderConfig(+ instanceId = instanceId,+ typeId = typeId,+ configurationVersion = configurationVersion,+ enabled = enabled,+ priority = priority,+ baseUrl = baseUrl,+ eventLeagueIds = eventLeagueIds,+ customDefinitionJson = customDefinitionJson+)+private fun Provider.toBackupCredentials(): ProviderCredentials? {if (username.isBlank() || password.isBlank()) return nullreturn ProviderCredentials(@@ -6265,7 +6493,7 @@ private const val RESTORE_SNAPSHOT_PRESET_2 = "__restore_snapshot_preset_2"private const val RESTORE_SNAPSHOT_PRESET_3 = "__restore_snapshot_preset_3"private const val RESTORE_SNAPSHOT_CHANNEL_PREFERENCES = "__restore_snapshot_channel_preferences"private const val RESTORE_SNAPSHOT_PLAYBACK_QUALITY_PREFERENCES = "__restore_snapshot_playback_quality_preferences"-private const val CURRENT_BACKUP_VERSION = 17+private const val CURRENT_BACKUP_VERSION = 18private const val RESTORE_SECTION_FAVORITES = "FAVORITES"private const val RESTORE_SECTION_CUSTOM_GROUPS = "CUSTOM_GROUPS"private const val RESTORE_SECTION_PLAYBACK_HISTORY = "PLAYBACK_HISTORY"@@ -6290,6 +6518,8 @@ private val MAP_STRING_STRING_TYPE: Type = object : TypeToken<Map<String, Stringprivate val PROVIDER_TYPE: Type = com.streamvault.domain.model.LegacyProvider::class.javaprivate val PROVIDER_SNAPSHOT_TYPE: Type = ProviderBackupSnapshot::class.javaprivate val PROVIDER_CREDENTIALS_TYPE: Type = ProviderCredentials::class.java+private val SPORTS_PROVIDER_BACKUP_TYPE: Type = SportsProviderBackup::class.java+private val SPORTS_PROVIDER_CREDENTIALS_BACKUP_TYPE: Type = SportsProviderCredentialsBackup::class.javaprivate val FAVORITE_TYPE: Type = com.streamvault.domain.model.Favorite::class.javaprivate val VIRTUAL_GROUP_TYPE: Type = com.streamvault.domain.model.VirtualGroup::class.javaprivate val PLAYBACK_HISTORY_TYPE: Type = com.streamvault.domain.model.PlaybackHistory::class.java@@ -6314,6 +6544,9 @@ private val STRING_TYPE: Type = String::class.javaprivate val PROVIDER_LIST_TYPE: Type = object : TypeToken<List<com.streamvault.domain.model.LegacyProvider>>() {}.typeprivate val PROVIDER_SNAPSHOT_LIST_TYPE: Type = object : TypeToken<List<ProviderBackupSnapshot>>() {}.typeprivate val PROVIDER_CREDENTIALS_LIST_TYPE: Type = object : TypeToken<List<ProviderCredentials>>() {}.type+private val SPORTS_PROVIDER_BACKUP_LIST_TYPE: Type = object : TypeToken<List<SportsProviderBackup>>() {}.type+private val SPORTS_PROVIDER_CREDENTIALS_BACKUP_LIST_TYPE: Type =+ object : TypeToken<List<SportsProviderCredentialsBackup>>() {}.typeprivate val EPG_SOURCE_TYPE: Type = com.streamvault.domain.model.EpgSource::class.javaprivate val EPG_SOURCE_LIST_TYPE: Type =object : TypeToken<List<com.streamvault.domain.model.EpgSource>>() {}.typediff --git a/data/src/main/java/com/streamvault/data/manager/PreferenceBackupRegistry.kt b/data/src/main/java/com/streamvault/data/manager/PreferenceBackupRegistry.ktindex c93cabce..91e4fc11 100644--- a/data/src/main/java/com/streamvault/data/manager/PreferenceBackupRegistry.kt+++ b/data/src/main/java/com/streamvault/data/manager/PreferenceBackupRegistry.kt@@ -13,6 +13,10 @@ internal object PreferenceBackupRegistry {"last_active_provider_id", "active_live_source_type", "active_live_source_id","default_view_mode", "parental_control_level", "parental_pin_hash", "parental_pin_salt","default_category_id", "app_language", "app_landing_destination", "app_top_level_destinations",+ "sports_event_source_mode", "sports_event_source_instance_id",+ "sports_score_source_mode", "sports_score_source_instance_id",+ "sports_standings_source_mode", "sports_standings_source_instance_id",+ "sports_metadata_source_mode", "sports_metadata_source_instance_id","app_home_dashboard_shelves", "app_time_format", "app_theme", "live_tv_channel_mode", "live_tv_auto_hide_categories","show_live_source_switcher", "show_favorites_category", "show_all_channels_category","show_recent_channels_category", "live_tv_category_filters", "live_tv_quick_filter_visibility",@@ -54,10 +58,6 @@ internal object PreferenceBackupRegistry {)private val deviceBoundStorageKeys = setOf("download_tree_uri",- "sports_event_source_mode", "sports_event_source_instance_id",- "sports_score_source_mode", "sports_score_source_instance_id",- "sports_standings_source_mode", "sports_standings_source_instance_id",- "sports_metadata_source_mode", "sports_metadata_source_instance_id",)private val runtimeStorageKeys = setOf("parental_v2_migrated", "parental_pin", "live_variant_observations", "vod_variant_observations",@@ -105,6 +105,10 @@ internal object PreferenceBackupRegistry {private val globalKeys = setOf("automaticSyncDefaults", "parentalControlLevel", "parentalPinHash", "parentalPinSalt", "appLanguage", "appTimeFormat", "appTheme","defaultViewMode", "appLandingDestination", "appTopLevelDestinations", "appHomeDashboardShelves",+ "sportsEventSourceMode", "sportsEventSourceInstanceId",+ "sportsScoreSourceMode", "sportsScoreSourceInstanceId",+ "sportsStandingsSourceMode", "sportsStandingsSourceInstanceId",+ "sportsMetadataSourceMode", "sportsMetadataSourceInstanceId","remoteShortcutPreferences", "liveTvCategoryFilters", "liveTvQuickFilterVisibility", "liveTvChannelMode","liveTvAutoHideCategories","showLiveSourceSwitcher", "showFavoritesCategory", "showAllChannelsCategory", "showRecentChannelsCategory",diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 1b4f402b..467a4c87 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -6,6 +6,8 @@ All notable product changes are recorded in this document.### Added+- Added a Sports tab populated with events from the EPG.+ - Added support for built-in and custom sports API providers in Sports settings.- Added a localized security warning to QR phone pairing that explains provider credentials are sent unencrypted over the local network.- Clarified Extensions navigation and plugin installation actions, added Stremio onboarding, and replaced its blanket parental gate with an independent Hide Stremio Add-ons option under Privacy (off by default).- Added native Stremio add-on support with manifest URL installation, catalog browsing, cross-addon metadata/stream/subtitle resolution, direct and debrid HTTP(S) playback, resume history, and downloads for offline playback managed from the Downloads tab. Plugins and Stremio Add-ons are grouped under the Extensions navigation item.diff --git a/docs/FFMPEG-LGPL-NOTICE.md b/docs/FFMPEG-LGPL-NOTICE.mdindex f15b9e12..f31ad3a6 100644--- a/docs/FFMPEG-LGPL-NOTICE.md+++ b/docs/FFMPEG-LGPL-NOTICE.md@@ -2,6 +2,10 @@StreamVault distributes a bundled Media3 FFmpeg audio decoder artifact built for LGPL-compatible use.+The current artifact provenance is recorded in `player/libs/media3-decoder-ffmpeg-1.11.0.properties`. It identifies AndroidX Media3 source commit `2bc207851df311340767e913931ca7b28cab1794`, FFmpeg source commit `ba69be84a1ceabfb39127831ad8da0fd7cb471f3`, the enabled decoders and supported ABIs. The corresponding license texts are packaged in `app/src/main/assets/licenses/`.++Corresponding source is available from the commit-pinned [AndroidX Media3 decoder module](https://github.com/androidx/media/tree/2bc207851df311340767e913931ca7b28cab1794/libraries/decoder_ffmpeg) and [FFmpeg source](https://github.com/FFmpeg/FFmpeg/tree/ba69be84a1ceabfb39127831ad8da0fd7cb471f3). The pinned [Media3 decoder README](https://github.com/androidx/media/blob/2bc207851df311340767e913931ca7b28cab1794/libraries/decoder_ffmpeg/README.md) contains upstream build instructions. StreamVault's specific settings for this artifact are listed in the properties file and in `docs/FFMPEG.md`.+Distribution rules for this repo:- Do not enable GPL or nonfree FFmpeg components in the bundled artifact.diff --git a/docs/FFMPEG.md b/docs/FFMPEG.mdindex 9d65b173..d840fa18 100644--- a/docs/FFMPEG.md+++ b/docs/FFMPEG.md@@ -17,7 +17,11 @@ Important product notes:Refresh procedure:-1. Rebuild the AndroidX FFmpeg decoder against Media3 `1.11.0`.-2. Replace `player/libs/media3-decoder-ffmpeg-1.11.0.aar`.-3. Update `player/libs/media3-decoder-ffmpeg-1.11.0.properties` if provenance changes.+The current binary's pinned source revisions and build inputs are recorded in `player/libs/media3-decoder-ffmpeg-1.11.0.properties`. The source repositories are [AndroidX Media3 at the recorded commit](https://github.com/androidx/media/tree/2bc207851df311340767e913931ca7b28cab1794/libraries/decoder_ffmpeg) and [FFmpeg at the recorded commit](https://github.com/FFmpeg/FFmpeg/tree/ba69be84a1ceabfb39127831ad8da0fd7cb471f3). Follow the [pinned upstream decoder build instructions](https://github.com/androidx/media/blob/2bc207851df311340767e913931ca7b28cab1794/libraries/decoder_ffmpeg/README.md) to build FFmpeg and assemble the decoder AAR.++For this artifact, build FFmpeg for `armeabi-v7a` and `arm64-v8a` with `ac3`, `eac3`, `dca`, `mp2`, `mp3`, and `truehd` enabled. The metadata records FFmpeg NDK `26.1.10909125` and AAR NDK `28.2.13676358`; use compatible NDK/CMake tooling as described by the pinned upstream instructions. The generated AAR is statically linked with the FFmpeg libraries, so preserve the build outputs and wrapper object/source needed to relink it with a modified FFmpeg library.++1. Replace `player/libs/media3-decoder-ffmpeg-1.11.0.aar`.+2. Update `player/libs/media3-decoder-ffmpeg-1.11.0.properties` with the new source revisions, configuration, toolchain and SHA-256.+3. Keep the corresponding source available for the release and update `docs/THIRD-PARTY-LICENSES.md` if the source or configuration changes.4. Run `:player:verifyLocalFfmpegArtifact` and the player/app test builds.diff --git a/docs/OPENSUBTITLES_INTEGRATION.md b/docs/OPENSUBTITLES_INTEGRATION.mdindex 5f6a1698..f789541d 100644--- a/docs/OPENSUBTITLES_INTEGRATION.md+++ b/docs/OPENSUBTITLES_INTEGRATION.md@@ -22,13 +22,15 @@ Online search is hidden for live TV and catch-up. Search uses the movie or serie## API key-Add this line to the root `local.properties` file (already gitignored), then rebuild a debug build:+For a local debug build, add this line to the root `local.properties` file (already gitignored), then rebuild:```propertiesopensubtitles.api.key=YOUR_OPENSUBTITLES_API_KEY```-The key is injected into debug builds only; release variants currently have an empty key. The app can still compile without a key, but OpenSubtitles requests return setup guidance and the online subtitle feature cannot work. The key is required even when no user is signed in. It is packaged into the app binary and can be extracted from an APK, so this local setup prevents Git exposure but does not make the key secret from app users. Account passwords and bearer tokens remain encrypted locally.+For GitHub Actions, add the repository Actions secret `OPENSUBTITLES_API_KEY`. The beta and release workflows pass it to Gradle when assembling their APKs, so both variants can use online subtitles. Local `local.properties` values remain debug-only. Builds without the key still compile, but OpenSubtitles requests return setup guidance and online subtitle search cannot work. The key is required even when no user is signed in.++The key is packaged into the app binary and can be extracted from an APK. A GitHub Actions secret keeps it out of the repository and workflow source, but cannot hide it from people who receive the APK. Keep it in Actions Secrets and rotate it if exposed; protecting it from APK users would require routing API requests through a server. Account passwords and bearer tokens remain encrypted locally.## Validationdiff --git a/docs/PLAYBACK_PREFERENCES_PLAN.md b/docs/PLAYBACK_PREFERENCES_PLAN.mddeleted file mode 100644index 26a32203..00000000--- a/docs/PLAYBACK_PREFERENCES_PLAN.md+++ /dev/null@@ -1,265 +0,0 @@-# Playback Preferences and Quality Profiles--## Purpose--Expand [issue #263](https://github.com/Davidona/StreamVault-IPTV/issues/263) into a coherent playback preference system. Users should be able to set quality limits, save meaningful preferences for particular content, understand the quality currently playing, and trust that recovery and restarts preserve their choices.--This document specifies the agreed release and tracks implementation progress. The release covers profiles, connection limits, provider defaults, saved live-channel/movie/series ceilings, temporary choices, backup/restore, and playback lifecycle integration.--## Implementation status--Updated while implementation is in progress. Completed items below describe code currently present; unchecked items remain planned or incomplete.--Latest verification: `:app:compileDebugKotlin` succeeds with quality consent, policy diagnostics, fixed-track status, Cast messaging, source-only constrained preloads, and per-field player controls. All 30 strings added in the playback module exist in all 38 advertised locales; XML parses, no translation is an English placeholder, and positional formatting contracts match. `git diff --check` reports no whitespace errors. Runtime playback, migration/restore behavior, and automated test coverage have not been validated yet.--- [x] Added domain profile, limit, scope override, candidate, and resolver models.-- [x] Added global profile/custom/Wi-Fi/Ethernet bitrate preferences to the DataStore contract and implementation, preserving the existing Wi-Fi/Ethernet height keys.-- [x] Added global backup export/import and classified the new setting as a global preference.-- [x] Added localized Settings > Playback controls for Auto, Data Saver, Balanced, Custom, custom height/bitrate, and connection bitrate limits in all configured locales.-- [x] Exposed video height and advertised bitrate metadata on player tracks.-- [x] Applied profile, connection, provider-default, multiview, and compatibility limits through the current player track controller; made constrained selection strict and validated manual video choices before application and on policy updates.-- [x] Observed global quality preference changes in playback; constrained neighbor preloads stop at source/manifest preparation, and already-buffered windows are cleared when a quality limit tightens.-- [x] Added provider/content-scoped Room storage, a domain-facing read/write contract, provider-delete cascade, migration 82 → 83, and exported schema 83.-- [x] Added portable backup/restore for scoped quality preferences using portable provider identity, validation, per-provider replacement behavior, and restore checkpoint rollback.-- [x] Pass stable provider-supplied live/movie/series identifiers into playback; resolve saved provider and content preferences during foreground prepare.-- [x] Added player actions to save the current resolution as an adaptive ceiling and remove a saved ceiling. Saving returns selection to Auto, so it stays adaptive under the saved limit.-- [x] Added localized save/remove actions for every advertised locale.-- [x] Added temporary adaptive ceilings to the shared resolver and player selector; Auto clears the temporary ceiling, and content changes discard it.-- [x] Added player quality-menu actions to save the current resolution as a provider-wide adaptive ceiling and remove that provider default.-- [x] Added provider settings controls for per-field inherited height/bitrate limits, no additional limit, and explicit maxima.-- [x] Observe provider-default and content-scope preference flows during playback; scope switches cancel stale observations and apply updates to the active player without waiting for another prepare.-- [x] Keep a manual fixed-track choice session-local across same-media retries; reject choices outside current policy limits and reapply only after availability and policy revalidation.-- [x] Add sanitized logs and player diagnostics for effective limits, contributing policy sources, observed video format, and decoder-pressure ceilings.-- [x] Expose per-dimension Save maximum, Inherit, and content-scoped No additional limit actions in the player; saving one dimension preserves the other.-- [x] Gate no-match/unknown-metadata playback with explicit consent, preserve play intent, and defer player recovery while intentionally waiting. The gate offers one candidate, a source alternative when available, and stop; Continue once relaxes only the violating user dimensions and remains bounded to the current source/policy. Compatibility and multiview constraints still apply; decoder-pressure state disables the exception.-- [x] Effective limits, contributing sources, observed format, and decoder-pressure ceilings are logged and shown in the diagnostics UI.-- [x] Constrained neighbor preloads stop at source/manifest preparation, and tighter limits clear existing ranges; candidate-specific selector enforcement remains an optimization. Internal adaptive/single-rendition, timeshift, and fixed-track capability/status are reported. Cast reports that the receiver controls quality; external-player launch/handoff integration remains open.-- [ ] Complete migration/restore/lifecycle validation and emulator playback validation. Migration and restore test coverage is still pending.--Current implementation boundary: Settings edits the global profile, connection policy, and provider-wide height/bitrate defaults with per-field Inherit/No additional limit/maximum choices. Playback can save current height or advertised bitrate ceilings per dimension for content or provider scope, restore inherited fields, opt a content scope out of a provider default per dimension, use temporary adaptive ceilings, and gate no-match/unknown-metadata playback pending explicit consent. Diagnostics report effective limits, policy sources, decoder pressure, adaptive versus single-rendition capability, timeshift, Auto versus Fixed track mode, and unavailable Cast enforcement; current-quality save actions are disabled during Cast playback. Consent is source-scoped and invalidated on policy, connection, multiview, compatibility, or source changes while same-media retries retain it. Candidate-specific preloading, external-player launch/handoff integration, migration/restore validation, and runtime playback validation remain open.--## What exists today--- Playback settings persist Auto/Data Saver/Balanced/Custom profile values, connection bitrate limits, and the existing Wi-Fi/Ethernet height caps in DataStore.-- Provider settings expose independent height and bitrate overrides with Inherit, No additional limit, and maximum choices; an existing saved maximum outside the preset list remains selectable.-- `PlayerTrackController` combines global profile, active network, provider-default, multiview, and compatibility constraints; unknown constrained metadata is ineligible and automatic exceedance is disabled.-- The player can list and manually select video tracks, save height and advertised-bitrate ceilings per dimension for content or provider scope, restore inherited fields, opt content out of provider ceilings per dimension, and set a temporary adaptive ceiling that clears on Auto or content change.-- VOD audio and subtitle choices persist globally and by movie or series scope.-- Live channel variant selections are remembered by provider and logical channel group.-- Adaptive HLS/DASH playback can temporarily restrict renditions when decoder pressure is detected.-- Multiview can impose a 720p ceiling.-- Compatibility decoder mode contributes a 720p maximum to the same resolved policy, so it cannot replace a stricter user maximum.-- Room schema 83 adds sparse provider/content preference rows with provider-delete cascade. Portable backup/restore resolves provider identities and retains stable remote scope keys; migration/restore runtime validation remains pending.-- Room already stores channel aspect ratio and AV offset, with deletion cascades and portable backup support. Migration 12 to 13 moved per-channel state out of DataStore. Its raw-channel row identity is different from a logical channel group's lifetime.-- `applyInitialParameters` clears audio, text, and video overrides; reactive quality updates must not call it unchanged.-- `PlayerTrack` exposes numeric height and advertised bitrate metadata for semantic saves. With an active quality limit, neighbor preloading prepares only the source/manifest and does not load a video range; tighter limits clear existing preload windows. Candidate-specific selector enforcement remains an optimization.--These mechanisms are useful, but they have separate inputs and do not give the user one view of the effective quality rule or why a rendition was selected.--## Product behavior--### Preference model--Save semantic adaptive ceilings, such as Up to 720p, rather than persistent fixed tracks or Media3 track IDs. Rendition IDs and ordering can change between sessions. Adaptive bitrate selection and decoder-pressure adaptation remain active within a saved ceiling.--Support these scopes:--1. A global playback profile and quality ceiling.-2. Optional connection-specific ceilings for Wi-Fi and Ethernet.-3. An optional provider default.-4. An optional channel or VOD item preference.-5. A temporary adaptive ceiling or fixed-track selection; a save action creates a durable adaptive ceiling, not a persistent track lock.--Global profile and active connection maxima combine using the strictest maximum in each dimension. Provider defaults supply content ceilings; saved channel/movie/series values replace provider defaults per field, and temporary adaptive values replace those saved defaults for the session. None can silently exceed the global/connection limits. Compatibility, device support, multiview, and decoder-pressure constraints can narrow eligibility further and cannot be bypassed by an above-limit exception.--For scoped fields, distinguish Inherit, No additional limit, and a specific maximum. No additional limit removes an inherited content default while retaining global/connection limits. Player Auto clears temporary selection and resumes applicable policy. Remove saved preference separately clears durable content settings. Auto must not be presented as unlimited when inherited limits remain.--Initial presets are product defaults, not device-performance promises:--| Profile | Maximum video height | Maximum advertised video bitrate |-| --- | --- | --- |-| Auto | No additional limit | No additional limit |-| Data Saver | 480p | 2 Mbps |-| Balanced | 720p | 4 Mbps |-| Custom | User selected | User selected |--Custom provides Auto/480p/720p/1080p/2160p height choices and No Limit/2/4/8 Mbps bitrate choices. Editing a preset copies it into Custom. Existing installs start with Auto and retain connection caps. Height and bitrate are independent limits; Maximum video bitrate filters advertised rendition metadata and does not throttle all network traffic or guarantee total data use. Frame-rate caps are deferred.--Live preferences apply to a stable provider/logical channel group, or an unambiguous remote channel when stable grouping is unavailable. Movie preferences apply to the logical movie or remote item; series preferences carry across episodes. Episode-specific settings and cross-provider identity matching are deferred.--Fixed track remains an advanced temporary mode. It obeys applicable limits but disables automatic decoder-pressure adaptation by design, and status explicitly says Fixed. If the selected rendition disappears, return to adaptive selection within policy with a notice. Saving a quality means saving a ceiling, using numeric metadata rather than a translated label; do not implicitly save the selected rendition's bitrate as a new cap without the user choosing that bitrate maximum.--### Source capability and fallback--Apply rendition limits to adaptive sources that expose multiple tracks, including HLS and DASH. Preserve the existing provider-level stream variant choice (for example, a channel's SD or HD URL) as a separate source choice in the same quality experience. Do not suggest that a fixed-quality progressive or transport stream can be downshifted when it exposes no lower rendition.--[Media3 permits exceeding video constraints by default](https://developer.android.com/reference/androidx/media3/exoplayer/trackselection/DefaultTrackSelector.Parameters#exceedVideoConstraintsIfNecessary) when nothing fits. Configure the selector to disable automatic exceedance and validate manual overrides against the same eligibility rules. Install constraints before prepare/autoplay; once tracks are known, publish Checking quality, Within limits, Choice required, or Unverified exception.--If nothing qualifies, pause the whole player and preserve user play intent rather than starting an audio-only session. Choice required is intentional waiting and must not trigger stuck timeouts or recovery that bypasses policy. Offer Choose another available source, Continue once, and Stop. Display the limit being exceeded and the offered quality before consent. An exception for a known rendition relaxes only the required dimensions up to the displayed maxima; unrelated and runtime safety limits still apply.--Unknown height excludes a track when height is constrained; unknown advertised bitrate excludes it when bitrate is constrained. Never treat unknown as zero. If no eligible track remains, explain Cannot verify quality or No quality meets your limits. A user can explicitly continue with an unverified exception. Source metadata can be inaccurate: pause and re-evaluate if later format information contradicts it. This cannot guarantee zero preparation traffic or prevent every transient decode of incorrectly described content.--Keep provider-source choice distinct from adaptive tracks; offer a lower source explicitly, then evaluate it under policy. Automatic provider-URL switching to enforce caps is deferred.--### Player and settings experience--- Put profile and connection limits in Settings > Playback, alongside the existing network quality caps.-- [x] Add provider-default controls to provider settings using Inherit/No additional limit/maximum choices.-- Extend the player quality panel with Auto within policy, adaptive ceilings, Fixed track, provider sources, Save for this channel/movie/series, and Remove saved preference. Cover TV remote focus and mobile layouts.-- Show requested policy and observed playback quality together, such as “Balanced · up to 720p · playing 480p.”-- In player diagnostics, explain which constraint is active: profile, connection, saved content choice, decoder protection, multiview, or source availability.-- Diagnostics include every contributing constraint, effective maxima, supported/eligible tracks, selected format, connection class, session/policy revision, and blocked/downshift reasons. Use the existing log sanitizer for URLs/tokens. Unknown metadata remains unknown, and Fixed/temporary exception states are visible.-- Keep audio and subtitle preferences working as they do today. Align them with shared scope conventions where that does not broaden this release unnecessarily.--## Policy and data boundaries--- Put profile, inherited-field, scope, candidate metadata, effective-limit/reason, and enforcement-status models in `domain`, with a pure resolver that imports no Android/Media3 types.-- A playback policy coordinator owns session inputs and revisions. Compatibility, multiview, and decoder-pressure components submit constraints; one adapter applies the combined video result. A compatibility maximum of 720p plus a user maximum of 480p stays 480p. Removing runtime constraints restores remaining user policy, not unlimited playback.-- The adapter owns video overrides so a saved adaptive ceiling does not disable pressure adaptation by appearing as a foreign override. Fixed mode follows its separate behavior. Reactive video changes preserve audio/subtitle overrides, injected subtitles, playback speed, and play intent.-- Keep global profile, Custom values, and connection settings in DataStore. Retain existing Wi-Fi/Ethernet height keys as authoritative to avoid duplicate migration/write paths.-- Add a sparse Room `playback_quality_preferences` table for provider/content settings: provider FK/cascade, scope type/key/identity version, inherited height/bitrate fields, and unique provider/scope index. Keep persistence behind domain-facing preferences/repository contracts.-- Do not attach logical-group quality only to `ChannelPreferenceEntity.channelId`: changing variants changes the raw row, and removing one member must not erase a group's ceiling. Reuse Room lifecycle/portable preference infrastructure while supporting the correct scope lifetime.-- Prove group identity stability across sync and grouping changes, or fall back to remote-item scope. Include parent/category namespace when a provider requires it. Ambiguous matches do not receive a preference. Keep temporarily absent settings dormant; partial/failed sync is not evidence of permanent removal.-- Follow `docs/DATABASE_MIGRATION_INVARIANTS.md`: migrate from the version current at implementation, export the schema, cover populated origins, and check foreign keys.-- Classify new global keys in `PreferenceBackupRegistry`; export scoped settings through portable provider/content references, never local IDs. Extend pending restore for catalogs that hydrate after import.-- Define absent versus explicitly-empty sections, merge/replace behavior, ambiguous/unmatched reporting, and cross-store restore checkpoint/rollback. Older backups lacking quality settings retain corresponding current settings. Test restore with changed provider/catalog IDs. Exclude temporary selections, consent, observation caches, and runtime pressure state from backup.--## Playback lifecycle and temporary choices--Observe preference and connection changes instead of only sampling `.first()` during prepare. Unclassified connections use global limits; offline playback does not inherit a stale connection class. Re-resolve at prepare, content/source/manifest changes, settings/network revisions, player recreation, retries/recovery, compatibility changes, multiview entry/exit, preload promotion, and live/timeshift transitions.--Scope asynchronous work to session and policy revision; reject old-channel/old-policy callbacks. Apply changes idempotently without track-update loops. Tightening a cap gates incompatible playback before resuming; relaxing it lets ordinary adaptation choose when to raise quality.--Temporary ceilings/fixed choices persist through same-session transient reconnects and player recreation after revalidation. They end on new content, Stop/close, process restart, or Auto. A next episode ends a temporary choice; a saved series ceiling carries forward. View-model/navigation recreation that preserves the session must preserve its identity.--Above-limit consent additionally binds to connection class, applicable user-policy revision, and source identity. Changing those inputs, source switching, or recovery to a different source invalidates consent. Same-source retries may retain it. Consent never becomes a saved preference or authorizes another channel.--Preload selectors must enforce each candidate's limits before selecting/loading video, using independent selector instances. A foreground exception cannot apply to adjacent candidates. Cancel/invalidate incompatible preloads on tighter limits and revalidate at promotion. If candidate-specific enforcement is unsupported, reduce that candidate's preload to source/manifest preparation rather than load unconstrained video.--Timeshift snapshots cannot supply a lower rendition never captured. Check snapshot format and explain the limitation or offer return to live; do not silently play above changed limits. Local recordings use fixed-source capability reporting. External/cast players report enforcement unavailable when they cannot support these limits; internal-player policy must not be presented as controlling them.--## Delivery stages--### Stage 0: Identity and integration design (partially complete)--- Map live/raw/movie/series identities to storage and portable references, including concrete provider-specific fallbacks.-- Specify Room schema/inherited-field encoding and trace all selector writers and preload setup.-- Design the capability gate, recovery suppression, and preservation of play intent.-- Design TV/mobile flows using the resolved product rules above.--Gate: identity lifetime, schema, and single selector ownership cover existing playback paths.--### Stage 1: Shared policy and migration (implementation complete; validation pending)--- [x] Add the domain preference types and a pure resolver for profile, network, saved scope, source capability, and runtime constraints.-- [ ] Add policy tests for field inheritance, unknown/malformed metadata, mixed limits, no match, and exceptions; numeric candidate metadata is exposed in player models.-- [x] Read existing Wi-Fi and Ethernet height caps as equivalent constraints so the user's current settings retain their meaning.-- [x] Add preference repository flows and update operations for global and scoped preferences with validation and default behavior.-- [x] Implement scoped Room persistence, migration, provider cascade, and portable backup/restore with provider identity remapping and checkpoint rollback.--Gate: legacy caps round-trip, scoped settings survive restart/portable restore, and no preference attaches to ambiguous content.--### Stage 2: Apply policy to playback (in progress)--- [x] Apply global, connection, provider-default, content-scope, multiview, and compatibility limits through the player track controller; constrained automatic selection is strict.-- [x] Carry a temporary adaptive ceiling through preparation/retry, return to Auto on set/clear, and discard it when content changes.-- [x] Re-resolve active playback when global preferences, connection class, or the current provider/content scoped preference changes; cancel stale scoped observers when playback identity changes.-- [x] Retain and revalidate a manual video-track override through same-media retries; new media resets the selection and unavailable or newly disallowed tracks return to Auto.-- [x] Scope consent to the current source; invalidate it for global/scoped/temporary policy, connection, multiview, compatibility, and media changes, while retaining it through same-media retries. Runtime recreation/source transitions remain to be validated.-- [x] Integrate the resolver with decoder-pressure and multiview constraints without allowing temporary automatic changes to overwrite user preferences.-- [x] Keep provider SD/HD stream switching available and report provider variants distinctly from adaptive rendition capability.-- [x] Diagnostics show actual resolution/bitrate, effective quality limits, grouped limiting sources, and active decoder-pressure ceilings; sanitized logs include the same policy and pressure information.-- [x] Strict selector behavior and manual override revalidation; gate no-match and unverifiable candidates; report fixed mode, internal source capability, timeshift, and temporary consent.-- [x] Integrate settings/network observation, policy/source consent expiry, same-media retry retention, and compatibility changes. Runtime recreation, timeshift, and external-source transitions remain to be checked.--Gate: all supported internal playback paths respect policy; gated waiting causes no recovery loop and video updates preserve other track choices.--### Stage 3: Settings and saved choices (in progress)--- [x] Add profile selection and Custom controls for height and maximum video bitrate alongside the existing Wi-Fi/Ethernet height controls.-- [x] Add in-player save-as-adaptive-ceiling and remove-saved-ceiling actions for supported live channels and VOD items.-- [x] Add a session-only adaptive ceiling that returns playback to Auto; Auto/content changes clear the temporary ceiling.-- [x] Manual fixed-track selection remains temporary and survives same-media retry after revalidation; provider settings expose Inherit/No additional limit controls for both quality dimensions.-- [x] Persist manual quality changes only after a user chooses a saved content or provider scope; temporary limits and exceptions remain session-only.-- [x] Add player-menu provider-default save/remove actions, per-field reset controls, provider-settings controls, fixed-mode labels, source capability explanations, and scoped consent.--Gate: users can save/reset a ceiling and recognize a temporary exception through TV/mobile controls.--### Stage 4: Backup, compatibility, and release readiness (in progress)--- [ ] Validate versioned backup parsing, invalid-entry handling, and older backups that lack quality sections.-- [ ] Verify provider deletion and playlist refresh do not attach a preference to a different logical channel.-- [ ] Verify older installs retain their network caps and receive a safe Auto default for new profile settings.-- [ ] Add or update UI and runtime tests at the domain, repository, player, and playback integration boundaries.-- [x] Implement backup classification, checkpoint rollback, and portable provider identity remapping for the scoped quality section.-- [ ] Validate backup classification, checkpoint rollback, deferred catalog identity remapping, and preloading restrictions introduced in earlier stages.-- [x] Document metadata-based limits and stricter legacy no-match behavior: previous caps could permissively fall back above the selected height.--Gate: release the complete vertical feature after storage, enforcement, diagnostics, UI, and playback validation pass.--## Acceptance criteria--- Auto, Data Saver, Balanced, and Custom produce deterministic eligible-rendition sets for a given source and runtime constraint.-- Existing Wi-Fi/Ethernet cap values still constrain playback after upgrade.-- A channel/content preference survives app restart and source refresh when its stable identity is unchanged.-- Temporary quality selections never persist implicitly; a save action creates the corresponding semantic ceiling, and exceptions are never saved.-- Known rendition metadata respects effective ceilings unless the user accepts a scoped exception. Unknown metadata requires explicit unverified consent when constrained, and later contradictory metadata triggers re-evaluation.-- Unsupported or fixed-quality sources are described accurately; a no-match case is visible and does not silently break playback.-- Decoder protection and multiview continue to work, and neither silently raises a user's configured ceiling.-- Backup/restore and provider deletion have defined behavior for saved overrides.-- Playback diagnostics make it possible to distinguish a user cap from network adaptation, decoder protection, multiview, and source limitations.-- Unknown constrained metadata never silently qualifies. Intentional waiting neither autoplays audio-only nor triggers stuck/recovery loops.-- Compatibility mode cannot raise a 480p cap to 720p. Saved adaptive ceilings preserve pressure adaptation; Fixed mode is explicitly different.-- Live settings/network changes take effect without waiting for a new content prepare, and stale callbacks cannot overwrite the current policy.-- Temporary consent expires on content/source/connection/policy changes as specified, and never spreads to preload candidates.--## Validation plan--Use deterministic manifests and supported decoders to assert selected rendition metadata and eligibility through preparation and every transition. Changing screenshots verify liveness, not cap enforcement. Advertised video bitrate and observed transfer rate must not be conflated.--| Scenario | Required evidence |-| --- | --- |-| Scope inheritance and mixed dimensions | Inherit differs from No additional limit; each rendition satisfies both effective maxima. |-| Unknown/no-match/fixed-quality sources | Accurate gating; no above-cap or audio-only autoplay; scoped Continue once and Stop work. |-| Saved adaptive and temporary Fixed modes | Adaptive selection can downshift within a saved ceiling; fixed mode is intentionally nonadaptive and gracefully handles missing tracks. |-| Compatibility/multiview/pressure | Runtime constraints never raise user limits; removing them preserves remaining policy and audio/subtitle selections. |-| Connection/settings changes | New revisions apply live, relevant consent expires, and stale work is rejected. |-| Retry/recreation/source fallback/next episode | Same-session choices survive applicable reconnects; consent and temporary preferences expire at their defined boundaries. |-| Manifest/preload/timeshift transitions | No stale override or incompatible background video load; snapshot limitations are visible. |-| Restart/sync/group member removal | Stable scopes restore without transfer to other content or deletion when one variant disappears. |-| Migration/provider deletion/portable restore | Populated migration preservation, cascade cleanup, changed-local-ID mapping, pending restore, and rollback. |-| TV/mobile controls and diagnostics | Focus/save/reset/Auto/exception states work; actual quality and sanitized reasons agree. |--Exercise HLS and DASH, at least two live channels, a VOD movie and successive series episodes, separate provider sources, and a fixed-quality stream. Include bandwidth-driven adaptation, decoder pressure, unknown metadata, and a cap tightening during active playback.--- For live playback validation, test more than one live channel. Capture 61 screenshots per channel at a two-second interval (about two minutes), confirm hashes change and the video region progresses throughout the capture, and check that the media session remains `PLAYING` with `error=null`. Clock/overlay changes alone are not evidence of progressing video.-- Review sanitized emulator logs for HLS prepare/read/first-frame or intended recovery, no fatal player error, no stuck-player timeout, no unintended MPEG-TS fallback, and evidence that quality policy was applied. Record channel names, frame counts, interval, unique hash counts, media-session status, and log findings.-- Also record applied limits, the selected rendition timeline, and any explicit exceptions. Intentional Choice required cases use expected paused/gated assertions instead of requiring PLAYING.--## Out of scope for this release--- A guaranteed network-wide bandwidth shaper or a guarantee on total bytes transferred.-- Automatically changing a provider's URL or transcoding its stream.-- A thermal sensor or device-temperature promise. Decoder-pressure protection remains based on playback signals already available to the app.-- Cloud-synced preferences or a broad redesign of every audio, subtitle, buffer, decoder, and transport setting.-- Persistent fixed tracks, episode-specific rules, and recording/download/timeshift capture quality controls. Their playback sources still receive capability reporting.--## Relevant code areas--- `domain/src/main/java/com/streamvault/domain/settings/PlayerPreferences.kt`-- `domain/src/main/java/com/streamvault/domain/settings/SettingsPreferences.kt`-- `domain/src/main/java/com/streamvault/domain/settings/VodTrackPreferences.kt`-- `data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt`-- `data/src/main/java/com/streamvault/data/local/entity/Entities.kt` and `dao/Daos.kt`-- `domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt`-- `data/src/main/java/com/streamvault/data/manager/PreferenceBackupRegistry.kt`-- `data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt`-- `data/src/main/java/com/streamvault/data/manager/PendingBackupRestoreCoordinator.kt`-- `player/src/main/java/com/streamvault/player/PlayerTrack.kt`-- `player/src/main/java/com/streamvault/player/tracks/PlayerTrackController.kt`-- `player/src/main/java/com/streamvault/player/tracks/AdaptiveDecodePressureTracks.kt`-- `player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt`-- `player/src/main/java/com/streamvault/player/playback/Media3PreloadWindowManager.kt`-- `feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreparationCoordinator.kt`-- `feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPlaybackPreferenceActions.kt`-- `feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsPlaybackSection.kt`diff --git a/docs/STALKER_SYNC_IMPROVEMENT_PLAN.md b/docs/STALKER_SYNC_IMPROVEMENT_PLAN.mddeleted file mode 100644index 54343310..00000000--- a/docs/STALKER_SYNC_IMPROVEMENT_PLAN.md+++ /dev/null@@ -1,311 +0,0 @@-# Stalker Add Provider and catalog ingestion improvement plan--Status: S1-S6 implementation is applied and focused correctness/recovery checks-pass. Real-provider onboarding and sustained live playback acceptance remain-unverified because this workspace has no installed app/provider session.-Prepared: 2026-10-10 against the current working tree, including the uncommitted-Xtream sync improvements.--Implementation evidence: [S1/S2 implementation](STALKER_SYNC_S1_S2_IMPLEMENTATION.md).-S3/S4 evidence: [S3/S4 implementation](STALKER_SYNC_S3_S4_IMPLEMENTATION.md).-S4-S6 follow-up: [overlap, category coverage, readiness, and continuation](STALKER_SYNC_S4_S6_IMPLEMENTATION.md).--## Goal and boundaries--VOD follow-up: [Stalker VOD ingestion improvement plan](STALKER_VOD_IMPROVEMENT_PLAN.md).-It retains pagination and tracks bounded recovery, repeated page work, and-conditional pipeline/decoder improvements separately from S1-S6.--Reduce avoidable work when adding a Stalker provider and when completing its-live catalog in the background. Apply the same ingestion improvements to-Settings live refresh where the existing shared path permits it.--Preserve the existing upfront resolver/discovery flow. Its portal selection,-authentication, compatibility/profile checks, capability validation, content-type detection, and split versus unified catalog decisions are working behavior-to retain. Do not bypass checks, weaken verification, reorder discovery recipes,-or change classification heuristics as part of this plan.--Optimize how successful resolved results are reused and how accepted catalog-rows are decoded, mapped, identified, and persisted after resolution. The-remote-ID database resolver discussed below is a separate persistence concern;-its identity rules also remain unchanged.--No baseline, before/after timing comparison, performance benchmark suite,-physical-device tuning campaign, or numerical speedup gate is required. Validate-correctness, compatibility, bounded resource use, and successful completion.-Do not claim a measured speedup without measurements.--## Current behavior to retain--- New-provider onboarding uses bootstrap sync: at most 200 live rows are read,- category shells are prepared, and durable full-catalog work is queued.- This is initial availability, not a complete lineup.-- Provider edits validate and promote the replacement catalog through the- existing staged configuration and commit callback.-- Bulk live loading already precedes category fallback, with learned capability- state, a stall watchdog, and provider-aware request admission.-- Movie/series item indexing and guide work already have continuation paths.-- Authentication/session caches, custom headers, transport configuration,- request priority, throttling, and stress cooldown remain authoritative.-- Shared Xtream work already supplies the cheaper logical group-ID calculation- and staged live promotion using Room FTS content-sync triggers. Reuse those- changes; do not implement duplicates or reintroduce global FTS rebuilds.--Relevant source:--- `data/.../repository/ProviderRepositoryImpl.kt`: discovery and onboarding.-- `data/.../remote/stalker/StalkerDiscoveryCoordinator.kt`: upfront discovery.-- `data/.../remote/stalker/StalkerProvider.kt`: layout detection, mapping, caches.-- `data/.../remote/stalker/OkHttpStalkerApiService.kt`: streaming row parsing.-- `data/.../remote/stalker/StalkerRemoteIdentityResolver.kt`: persistent IDs.-- `data/.../sync/StalkerCatalogSyncExecutor.kt`: live staging and fallback.-- `data/.../sync/SyncCatalogStore.kt`: transactional catalog promotion.--## S1 — Reuse successful discovery results--Status: **Implemented and correctness validated** (all five implementation items).--Keep every required discovery request and decision. Retain successful category-responses already obtained during layout detection so the subsequent setup flow-does not fetch the identical categories again.--Implementation:--1. Introduce an internal resolved-category snapshot containing the raw category- records, endpoint/content type, resolved layout, and the session/configuration- identity needed to establish that it belongs to the current provider.-2. Retain successful empty responses as successful empty responses. A failure,- timeout, or inconclusive result must not become an authoritative empty list.-3. Hand the snapshot from the discovery client to the sync client through an- explicit, short-lived in-memory handoff. Account for the new provider ID- assigned after discovery; map remote IDs only in the final provider scope.- Do not put session tokens or raw category payloads in sanitized discovery- summaries or persist them as new credential copies.-4. Consume it through the existing category mapping and classification path,- including adult flags, wildcard category behavior, and unified/split routing.-5. Invalidate on configuration changes, authentication invalidation/session- replacement, incompatible layout, deletion, or expiry. A process restart or- cache miss uses the current network path normally.--Acceptance: setup consumes matching successful discovery categories without a-duplicate request; misses and stale snapshots still fetch normally. Existing-resolver outcomes and error behavior remain equivalent.--## S2 — Reduce per-row database and category lookup work--Status: **Implemented and correctness validated** (all five implementation items).--Optimize identity persistence without changing assigned IDs or collision rules.--Implementation:--1. Add chunked DAO queries for existing raw IDs and occupied candidate surrogate- IDs. Respect SQLite bind limits; never build an unbounded `IN` query.-2. Under the existing provider/content-type lock and transaction, reuse known- identities and assign missing identities in the current sorted order.- Preserve preferred category IDs, numeric candidates, legacy hash candidates,- and high-surrogate fallback precedence.-3. Track occupied/new candidates within the batch, batch-insert new records, and- retain conflict recovery for external writers. Avoid `REPLACE`, which could- silently change an established mapping. Read high-surrogate allocation state- once when needed and advance it safely within the transaction.-4. Keep memory bounded to the current identity batch. Preserve reverse lookup- and category migration/name reconciliation behavior.-5. Build immutable category lookup maps when category seeds change. Preserve- the existing first-match behavior when raw ID and name matches disagree or- duplicate names exist, case-insensitive name matching, fallback names, and- category ordering. Rebuild maps when projection adds category seeds.--Acceptance: numeric, nonnumeric, duplicate, colliding, and preexisting identities-resolve identically; refresh preserves local IDs and user state; category mapping-matches the existing list-based implementation.--## S3 — Add a direct live-row decoder--Status: **Implemented and correctness validated** (all five implementation items).--Replace per-row Gson trees only on the bulk live ingestion path. Keep generic-VOD, series, detail, and guide decoders outside this change.--Implementation:--1. Read retained live fields directly from `JsonReader` into a live record or- compatible `StalkerItemRecord`; skip irrelevant nested payloads without- allocating their trees.-2. Preserve field aliases, scalar coercion, null/default behavior, duplicate-key- handling, text decoding, and supported array/wrapper/object-keyed shapes.-3. Preserve all fields needed for channel admission and playback: raw identity,- name/order, category, logo, EPG ID, adult status, command/direct URL, extension,- temporary-link/playback descriptors, archive and timeshift/PVR capabilities.- Audit `toItemRecord` and `toChannel` together before selecting retained fields.-4. Preserve portal error and invalid-token detection. A truncated document or- transport failure cannot be accepted as a complete catalog. Separate invalid- rows from invalid document structure and retain current admission limits.-5. Keep the legacy reader available internally until differential compatibility- checks pass. Do not add user-facing experimental decoder options.--Acceptance: fixture rows produce equivalent accepted channel fields and playback-descriptors; malformed/error/truncated responses retain failure semantics.--## S4 — Overlap live metadata and bounded ingestion--Status: **Implemented; focused concurrency and recovery checks pass**.--- [x] One producer, one queued raw batch, and one mapping/staging consumer.-- [x] Runtime row budgets and estimated retained-byte batch limits.-- [x] Consumer-owned counters, deduplication, and deferred fallback-category snapshots.-- [x] Fresh staging state and refreshed category context on authorization retry.-- [x] Joined reader/writer cancellation and failed-attempt cleanup.-- [x] Preserve the 200-row bootstrap prefix without recording full fidelity.-- [x] Watchdog distinguishes local work/backpressure from network stalls.-- [x] Overlap eligible live-category and bulk HTTP requests.-- [x] Keep limit-one/stressed portals sequential to avoid holding the only permit- while the bulk consumer waits for category context.-- [x] Exercise overlap with a blocked category response and verify the bulk HTTP- request starts before categories complete.--After upfront resolution completes, fetch live categories and the selected bulk-live response concurrently when admitted by the existing Stalker coordinator.-Use one bulk request, a bounded queue of raw live-row batches, and one consumer-that resolves identities, maps channels, and writes staging batches.--Implementation:--1. Reuse Xtream pipeline concepts without forcing Xtream DTOs or category rules- onto Stalker. Resolve immutable category context once before mapping rows.-2. Preserve learned bulk support/fidelity selection. Known category-only portals- enter fallback directly. When category discovery is needed for route selection,- retain that dependency; overlap only where the bulk choice is already valid.-3. Respect existing metadata concurrency, cooldowns, priorities, and network- permits. Category retrieval must remain able to finish while the bounded- reader queue is full, including when the provider limit has dropped to one;- never create a request-permit/queue deadlock.-4. Start conservatively with one queued batch and existing row batch sizes.- Count reader, queued, and writer batches in retained memory. Add a retained-byte- bound for wide records using the existing admission policy.-5. Keep counters, deduplication, category collection, and staging-session ownership- in the single consumer. Materialize fallback categories at completion rather- than copying their growing snapshot after every batch.-6. Give each bulk attempt a fresh staging session. Automatic authorization- retry must restart the whole attempt after cleanup, rather than replay rows- into the previous attempt's writer state. Join cancelled work before fallback.-7. Cancellation or writer failure closes the response and queue and discards- staging. Promotion requires a valid completed response and drained writes.-8. Treat the existing 200-row bootstrap limit as an intentional partial result.- Preserve its current admission/count semantics and durable full-sync handoff;- never mark the partial bootstrap as a complete catalog or bulk-fidelity proof.-9. Distinguish network read progress from local writer/backpressure time so the- bulk stall watchdog does not misclassify healthy database work as a stalled- portal. Retain prompt timeout and cancellation for actual network stalls.--Acceptance: concurrency limits hold, slow categories and a full queue terminate,-writer/reader failures cannot promote partial attempts, and bootstrap still queues-full sync. No unbounded lineup list is introduced on the bulk route.--## S5 — Stage category fallback as categories finish--Status: **Implemented; bounded streaming and durable failed-scope retries are wired**.--Keep the current category concurrency cap and stress-based downgrade policy.-Replace retained whole-lineup outcomes with bounded category staging.--Implementation:--1. Stage each category attempt separately. Merge its rows into the import only- after that attempt succeeds; discard a failed attempt before retrying it.-2. Retain compact coverage/count/error receipts instead of every completed- category's channel list. Bound the remaining current-response memory; where- the paged API still materializes a list, stream or consume bounded pages.-3. Preserve deterministic ordering and duplicate admission across categories.- Concurrent completion order must not decide which duplicate row wins.-4. For bootstrap, stop after the current accepted prefix limit is satisfied;- do not request later categories merely to truncate the combined list to 200.- The full provider continuation remains durable.-5. For complete refresh, prune only confirmed complete scopes. Failed categories- preserve existing verified rows, hidden categories remain preserved, and- required hidden rows still participate under current rules.-6. Persist failed category IDs, names, configuration generation, attempt count,- and sanitized error in the Room live-category retry queue. On the next ordinary- sync, fetch only those still-visible scopes. Commit retry-queue updates in the- same transaction as channel promotion; a successful full bulk refresh clears- the queue. Keep `lastLiveSuccess` stale until all retry scopes complete.- Portal-wide authentication/account/rate-limit failures are not stored as- independent category retries.--Acceptance: fallback imports all successful scopes, partial failure preserves-verified data, retries do not retain failed rows, and bootstrap avoids unnecessary-remaining category downloads without claiming full coverage.--## S6 — Integrate readiness and durable follow-up--Status: **Readiness and durable bootstrap handoff verified in focused tests**;-the real-provider lifecycle acceptance below remains pending.--Preserve the current bootstrap/full-sync product behavior. Do not enlarge or-remove the 200-row cap as an incidental optimization.--- Publish readiness only after the relevant transaction commits. Distinguish- initial availability, full live completion, category shells, item indexing,- and guide completion using existing state models.-- Keep pending full live work ahead of optional item indexing and guide work.- Use the current workflow locks, generations, and continuation scheduler;- avoid competing work chains or duplicate scheduling.-- Ensure cancel, process restart, provider edit, and deletion cannot publish- stale results or lose the bootstrap continuation.-- Keep setup completion/navigation and explicit save-with-verification-pending- behavior intact. Reuse existing localized messages where possible.--## Correctness validation--Extend existing focused tests rather than introducing a performance harness.-Use fake request counts and coroutine barriers for reuse/concurrency assertions;-do not use elapsed-time speed assertions.--| Area | Required checks |-| --- | --- |-| Upfront resolver | Existing portal/profile/capability/type/layout fixtures retain their outcomes; no checks are skipped |-| Snapshot reuse | Split/unified layouts, successful empty response, error, session/configuration mismatch, new ID assignment, restart/cache miss |-| Identity persistence | Numeric/string IDs, collisions within/across batches, existing mappings, reverse lookup, provider/type isolation, transaction rollback |-| Decoder | Differential field equivalence, aliases/coercion, wrappers/keyed objects, descriptors, unknown nesting, errors, truncation, cancellation |-| Pipeline | Slow categories/writer, full queue, limit-one permits, authorization retry after staged rows, stall timeout, bounded wide rows |-| Fallback | Bulk unsupported/error, category retry/downgrade, deterministic duplicates, partial coverage, bootstrap early stop, hidden scopes |-| Catalog | Insert/update/delete/unchanged search, stable IDs/favorites/protection, provider isolation, atomic promotion |-| Lifecycle | Add Provider, staged edit, Settings refresh, full continuation, cancel, restart, supersession, deletion |--Run affected data/domain/provider unit tests and Room instrumentation for actual-identity constraints and promotion/search behavior. Exercise onboarding through-its real sync entry point and verify persisted rows and continuation state.-Build success alone is insufficient correctness evidence.--When ingestion or mapping changes affect playable channel fields, validate two-representative live channels in the emulator under `AGENTS.md`: preferably 61-screenshots per channel at 2-second intervals, progressing frames, media session-`PLAYING` with `error=null`, and sanitized logs with no fatal/stuck error or-unintended MPEG-TS fallback. Record channel names, capture counts/intervals,-unique hashes, session results, and log findings. This is playback correctness-validation, not a before/after speed comparison. Missing provider access remains-an explicit validation gap rather than a passing result.--## Implementation order and completion--S1-S6 are implemented in the current working tree. Keep changes independently-reviewable and preserve unrelated dirty Xtream work.-Prefer DAO/code changes without schema migration where current tables suffice.--- [x] S1 resolved category reuse and invalidation verified.-- [x] S2 batched identities and category lookup equivalence verified.-- [x] S3 live decoder compatibility verified.-- [x] S4 bounded ingestion, retry isolation, bootstrap prefix, and eligible- category/bulk overlap verified; single-slot admission remains sequential.-- [x] S5 incremental category streaming, provider-order duplicate precedence,- bootstrap early stop, and partial-scope preservation implemented.-- [x] S6 readiness milestones and durable bootstrap full-sync handoff verified.-- [x] Focused Stalker, SyncManager, and provider repository unit tests pass.-- [x] Implemented identity/import/promotion behavior passes Room integration checks.-- [ ] Real-provider onboarding and continuation acceptance verified.-- [ ] Playback correctness verified where playable imported fields changed.-- [x] Current validation gaps documented; no unsupported speedup claims.--Last updated: 2026-10-10. Checked items describe completed work in the current-working tree, not a claim that all provider/playback acceptance has passed.diff --git a/docs/STALKER_SYNC_S1_S2_IMPLEMENTATION.md b/docs/STALKER_SYNC_S1_S2_IMPLEMENTATION.mddeleted file mode 100644index 768cd27d..00000000--- a/docs/STALKER_SYNC_S1_S2_IMPLEMENTATION.md+++ /dev/null@@ -1,76 +0,0 @@-# Stalker setup: resolved category reuse and identity persistence--Implemented 2026-10-10. Covers S1 and S2 of-[the improvement plan](STALKER_SYNC_IMPROVEMENT_PLAN.md). S3-S6 remain pending.--## Changes--Successful series/VOD category responses obtained by existing layout detection-are retained for one use by the subsequent category mapping path. Upfront portal-discovery, authentication, compatibility validation, and type/layout decisions-are unchanged. Failed probes are not converted into cached empty responses.--An explicit process-local handoff bridges the discovery client and the sync-client after the final provider ID is assigned. Its key includes provider ID,-configuration generation, and a digest of the complete typed configuration.-Consumption requires matching endpoint, token, authentication epoch, session-scope, expiry, and compatible resolved layout. The snapshot has a 60-second-lifetime; the shared cache is limited to 256 entries. Authentication invalidation-and provider deletion clear applicable handoffs. No new persistent session,-credential, or raw payload storage is introduced. The normal network path remains-the fallback after cache misses, restarts, mismatches, and expiration.--Unified VOD consumes the VOD endpoint probe while continuing to map categories-under the VOD content type. Raw category IDs are translated only within the-final provider's identity scope. Existing category/adult/wildcard mapping remains-authoritative.--Identity resolution now uses chunked existing-raw-ID and occupied-surrogate-ID-queries, followed by batch inserts. SQL parameter chunks are capped at 400.-Existing mappings, sorted assignment order, preferred category IDs, numeric-candidates, legacy hash candidates, and high-surrogate allocation precedence-are preserved. Ignored insert conflicts take the existing collision recovery-path; established identities are never replaced. The current lock and database-transaction still own the operation. No schema migration is needed.--Immutable category lookup maps replace repeated list scanning during row mapping.-They preserve the earliest list match when ID and name disagree, duplicate-name-ordering, and case-insensitive name matching. They rebuild when the underlying-category seed list changes and clear when authentication is invalidated.--The existing 200-row bootstrap limit, catalog activation, continuation scheduling,-and setup navigation behavior are unchanged.--## Validation--The following command completed successfully:--```powershell-.\gradlew.bat :data:testDebugUnitTest --tests '*Stalker*Test' --tests '*SyncManagerTest' --tests '*ProviderRepositoryImplTest' :data:connectedDebugAndroidTest '-Pandroid.testInstrumentationRunnerArguments.class=com.streamvault.data.local.StalkerIdentityIntegrationTest' --console=plain-```--- 346 unit tests across 24 suites passed, with no failures, errors, or skips.-- The Room identity integration test passed on `emulator-5554`, reported as- `Television_4K_2(AVD) - 16` by the Android test runner.-- New coverage verifies one-shot split/unified category reuse, normal mapping,- invalidation, new-provider ID handoff through the existing persisted session,- configuration/generation/session/layout mismatches, expiry, and deletion.-- Identity checks cover more than one SQL chunk, equivalence with sequential- assignment rules, numeric aliases, occupied numeric/hash candidates, refresh,- provider isolation, and competing identity conflict recovery.-- Room checks verify actual unique constraints, ignored conflicts without- replacement, reverse lookup, preferred category IDs, and transaction rollback.-- Category mapping checks preserve earlier name matches when a later ID match- disagrees, including duplicate case-insensitive names.-- `git diff --check` passed.--The first Room run exposed an incorrect assertion that raw ID `1` necessarily-owned surrogate ID `1`. Existing sorted assignment lets `001` claim that ID-first. The assertion now checks the actual assigned surrogate; identity rules-were not changed to satisfy the test.--Validation output is under ignored `build/stalker-validation.log`, the Gradle-unit-test reports, and the connected Android test reports. No before/after-performance measurement was run or required. No measured speedup is claimed.-Real-provider onboarding and sustained playback were not exercised in this-implementation batch; the decoder and ingestion pipeline have not changed.diff --git a/docs/STALKER_SYNC_S3_S4_IMPLEMENTATION.md b/docs/STALKER_SYNC_S3_S4_IMPLEMENTATION.mddeleted file mode 100644index 09894a73..00000000--- a/docs/STALKER_SYNC_S3_S4_IMPLEMENTATION.md+++ /dev/null@@ -1,95 +0,0 @@-# Stalker direct live decoding and bounded ingestion--This is the initial S3/S4 implementation snapshot. The follow-up completed the-remaining S4 overlap work and implemented S5/S6; see-[the follow-up report](STALKER_SYNC_S4_S6_IMPLEMENTATION.md) for current status.--Implemented 2026-10-10. Completes S3 and implements the ingestion/retry portion of-S4 in [the improvement plan](STALKER_SYNC_IMPROVEMENT_PLAN.md).--## Direct decoding--The bulk live response reader now consumes mapped scalar fields and command-variants directly from `JsonReader`. Unknown nested metadata is skipped without-building Gson trees. The direct and retained legacy readers share the existing-record mapper, preserving category/EPG fields, adult flags, command descriptors,-temporary-link and archive/PVR capabilities, extensions, and other mapped-metadata. Generic VOD, series, detail, guide, and upfront resolver decoding are-unchanged.--Scalar coercion, aliases, last-key-wins behavior, command-array indexes, malformed-command shapes, and missing-row identity/name admission are preserved. The-complete-response path now also checks `END_DOCUMENT`; extra JSON after a valid-catalog is a failure rather than a completed snapshot. Intentional bootstrap-prefix termination remains distinct from full-response completion.--## Bounded pipeline and attempt ownership--Bulk live loading now uses one raw-row producer, a one-batch queue, and one-consumer that owns identity mapping and staging callbacks. The consumer uses-the existing runtime row budgets, with estimated raw batch byte budgets of-256/512/1024 KiB for LOW/MID/HIGH. Wide rows exceeding the batch byte budget fail-explicitly. Direct callers without a runtime profile retain a 500-row limit and-a 1 MiB byte budget.--Memory accounting includes the producer's current batch, a queued batch, the-consumer's batch, and the separate mapped staging batch. The queue does not-remove the existing admitted-ID deduplication set, which remains governed by-the provider catalog row limit. The byte estimate limits retained batches; it-is not a measured total heap bound or a token-level scalar allocation limit.--Reader failure, writer failure, and cancellation close the queue and join the-consumer before retry or attempt cleanup. Normal writer cleanup does not turn-a returned portal error into cancellation. Authorization retry invokes an-attempt-start callback that discards the previous session, counters, duplicate-state, buffered rows, and fallback categories. It reloads category context after-reauthentication before starting the replacement stream.--Staging uses admitted-count accounting for fresh attempts and materializes-fallback categories at completion. The bulk stall watchdog distinguishes local-mapping/writes and queue backpressure from network inactivity. Cancelled staging-cleanup runs in a noncancellable context after the pipeline has stopped.--The 200-row bootstrap cap is preserved. A successful prefix no longer records-a positive bulk category-fidelity verdict; that evidence requires a completed-full response. Durable full sync still follows bootstrap through existing-continuation behavior.--## Initial follow-up status (superseded)--Live categories still load before bulk HTTP. Concurrent category/bulk requests-require explicit admission ordering so a bulk response holding the only portal-permit cannot fill its queue while its consumer waits for queued category work.-That ordering has not been implemented; S4 remains partially complete.--Incremental category fallback (S5), remaining readiness/scheduling integration-(S6), and final end-to-end provider/playback acceptance are also pending.--## Validation--- 356 unit tests across 26 suites passed, with no failures, errors, or skips:- `:data:testDebugUnitTest --tests '*Stalker*Test' --tests '*SyncManagerTest' --tests '*ProviderRepositoryImplTest'`.-- Decoder differential tests compare the retained legacy path across complete- mapped fields/descriptors, 1,000 mixed scalar/alias rows, duplicate keys,- command shapes, and truncation.-- Coroutine-barrier tests verify reader backpressure, ordered drain, reader error,- writer failure, full-queue cancellation, joined cleanup, and wide-row rejection.-- SyncManager tests force an authorization failure after actual staged writes,- then verify a fresh session is promoted and the failed session is discarded.- Bootstrap tests verify 200 staged rows without a positive fidelity verdict.-- Two `StalkerLiveIngestionIntegrationTest` tests passed on `emulator-5554`- (`Television_4K_2(AVD) - 16`). They use the real HTTP decoder, Stalker mapper,- identity resolver, pipeline, staging helpers, and Room promotion. Only initial- authentication is supplied by the fixture; production discovery is unchanged.-- The Room tests verify additions/deletions, stable local IDs, retained favorites,- EPG/archive fields, stream descriptor equivalence, and FTS rename behavior.- Trailing and truncated documents leave the verified catalog intact and clear- failed staging.-- `:app:assembleDebug -PcompatAbi=x86_64` passed. The APK was built, not installed.-- `git diff --check` passed.--Logs: ignored `build/stalker-s3-s4-validation.log`,-`build/stalker-s3-s4-room.log`, and `build/stalker-s3-s4-app-build.log`.-No before/after speed measurements were run and no measured speedup is claimed.-Real-provider setup and the two-channel sustained playback acceptance were not-run; synthetic import/Room checks do not count as playback validation.diff --git a/docs/STALKER_SYNC_S4_S6_IMPLEMENTATION.md b/docs/STALKER_SYNC_S4_S6_IMPLEMENTATION.mddeleted file mode 100644index b943d121..00000000--- a/docs/STALKER_SYNC_S4_S6_IMPLEMENTATION.md+++ /dev/null@@ -1,75 +0,0 @@-# Stalker S4-S6 follow-up implementation--Implemented 2026-10-10. This report extends the initial-[S3/S4 implementation snapshot](STALKER_SYNC_S3_S4_IMPLEMENTATION.md) and-records current status for the [improvement plan](STALKER_SYNC_IMPROVEMENT_PLAN.md).--## S4: eligible category and bulk overlap--The live category request starts before the bulk request. When the provider's-adaptive metadata limit permits two requests, bulk HTTP can run while categories-load; the single bulk consumer waits for the complete category context before-mapping any row. When stress state lowers admission to one, categories finish-before bulk starts, so bulk cannot hold the only slot while waiting on its own-consumer. Known category-only portals continue to use category fallback.--The coordinator retains request priority, rate-limit cooldown, provider stress,-and cancellation behavior. Existing bounded pipeline rules still own raw batches,-mapping, staging, authorization retry, and reader/writer cleanup.--## S5: incremental category fallback--Category fallback uses the validated paged `get_ordered_list` reader and bounded-mapped batches. Every full category attempt has a separate staging session. A-transport/server retry starts with a fresh session after the previous pipeline-drains; failed attempts are discarded. Completed categories merge into the-catalog stage in provider order, so concurrent completion order does not choose-the duplicate row winner.--Complete refreshes prune only successfully fetched category scopes. Failed or-unvisited scopes retain their verified channels. A partial category result does-not advance `lastLiveSuccess`. Failed category scopes are persisted in the Room-`stalker_live_category_retries` table with their category ID/name, configuration-generation, attempt count, and sanitized error. The next ordinary live/provider-sync fetches only queued, still-visible scopes; successful scope promotion and-queue deletion happen in the same Room transaction. A verified full bulk refresh-clears the queue. Entries for changed provider configurations, removed categories,-and intentionally hidden categories are discarded. Portal-wide authorization,-account, rate-limit, or transport-consent failures stop further category-scheduling and are not recorded as independent category retries.--Bootstrap fallback is sequential and stops requesting later categories once the-200-row accepted prefix is reached. The prefix uses upsert-only promotion, does-not certify bulk fidelity, and retains the existing durable full-provider-continuation.--## S6: readiness and continuation--Live readiness is published after staged promotion returns; category readiness-follows category-shell commits. The coordinator passes bootstrap's typed-`FULL_CATALOG` receipt to `ProviderContinuationScheduler`, which schedules the-existing provider-resume work. The focused bootstrap test verifies readiness,-the 200-row limit, stale full-catalog metadata, and the durable resume call.-Existing repository coverage continues to check save-with-verification-pending-and provider configuration revision behavior.--## Validation--- Focused unit run passed: 361 tests across 26 suites, no failures, errors, or- skips. Command:- `:data:testDebugUnitTest --tests '*Stalker*Test' --tests '*SyncManagerTest' --tests '*ProviderRepositoryImplTest'`.-- New `SyncManagerTest` cases cover overlap while category loading is blocked,- fallback bootstrap stopping before the next category, and preserving a stale- live-success timestamp after a category failure.-- `StalkerLiveIngestionIntegrationTest` passed on `emulator-5554`, covering Room- promotion, partial-scope pruning, stable IDs/favorites/search, bounded category- pages, and rejection of trailing/truncated catalogs.-- `git diff --check` passed on the final working tree.-- Durable per-category retry tracking was added after that validation run; it has- not yet been covered by a test run in this follow-up. Production and unit-test- Kotlin compilation passed, the app/Hilt graph compiled, and KSP generated the- version 80 Room schema.-- The emulator has the sync benchmark packages but not the StreamVault app. No- real provider credentials/session were available. Two-channel sustained live- playback and real-provider onboarding/continuation therefore remain unverified.-- No before/after timing comparison was run; no numerical speedup is claimed.diff --git a/docs/STALKER_VOD_IMPROVEMENT_PLAN.md b/docs/STALKER_VOD_IMPROVEMENT_PLAN.mddeleted file mode 100644index 425eaa11..00000000--- a/docs/STALKER_VOD_IMPROVEMENT_PLAN.md+++ /dev/null@@ -1,210 +0,0 @@-# Stalker VOD ingestion improvement plan--Status: V1 and V2 are implemented; focused unit, Room, and app-build validation-passed, including page-limit and resume coverage. Real-provider browsing and-playback remain unverified.-Prepared: 2026-10-10 against the current working tree.-Related: [Stalker live improvements](STALKER_SYNC_IMPROVEMENT_PLAN.md).-Implementation evidence: [V1/V2 implementation notes](STALKER_VOD_V1_V2_IMPLEMENTATION.md).--## Decision and boundaries--Keep paginated VOD loading as the default. Improve work around each page and-exceptional whole-category loading. Do not introduce a speculative single-request-bulk endpoint, request every page concurrently, or force full VOD ingestion into-Add Provider. An All/wildcard listing is still paginated.--Preserve the upfront resolver, authentication/profile checks, content detection,-split/unified layout decisions, movie/series classification, VOD-derived series,-playback descriptors, source order, and category protection. Preserve existing-interactive OPEN/NEXT_PAGE/COMPLETE behavior and background continuation policy.--No before/after measurements, benchmark suite, or numerical speedup gate is-required. Validate correctness and bounded processing; make no measured gain claims.--## Existing implementation to retain--- [x] Setup prepares category shells and defers item loading.-- [x] Interactive hydration commits page rows and checkpoints transactionally.-- [x] Successful-page checkpoints support continuation.-- [x] Existing page anomaly checks detect inconsistent totals/repeated pages.-- [x] Background indexing limits category concurrency and downgrades on stress.-- [x] Unified VOD preserves mixed movie/series classification and page ordering.-- [x] Page mapping uses the shared identity resolver improved by live work.-- [x] Limited wildcard strategy already exists with learned support.--These are existing behaviors observed in source, not new work completed by this-plan or a claim that all end-to-end acceptance has passed.--Relevant source:--- `data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.kt`- (`getVodStreams`, `fetchPagedItems`, and single-page decoding).-- `data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt`- (page mapping, classified split/unified VOD, identities).-- `data/src/main/java/com/streamvault/data/sync/SyncManager.kt`- (`fetchStalkerSummaryPageWithRecovery`, operations adapters).-- `data/src/main/java/com/streamvault/data/sync/VodCategoryHydrationCoordinator.kt`- (interactive hydration and page transactions).-- `data/src/main/java/com/streamvault/data/sync/StalkerIncrementalIndexExecutor.kt`- (background fetch windows, checkpointing, pruning, wildcard strategy).-- `data/src/main/java/com/streamvault/data/sync/StalkerIndexPolicy.kt`- (pagination, deduplication, and retry decisions).--## V1 — Bound exceptional complete-category recovery--Priority: first. Status: implemented.--The normal page path is incremental. However, empty-first-page summary recovery-calls `getVodStreams` or `getSeriesList`. The VOD list API calls `fetchPagedItems`,-accumulates all pages, and recovery wraps the result as page 1 of 1. This loses-real page provenance and can retain a whole category during a background slice.--- [x] Trace production callers of complete-list APIs and separate required public- list contracts from internal ingestion callers. Do not change unrelated providers.-- [x] Identify the compatibility difference that makes this recovery useful using- existing fixtures/request traces. Both VOD routes ultimately use ordered-list- requests; preserve necessary recovery instead of assuming it is redundant.-- [x] Give ingestion recovery a bounded page/batch consumption contract with- explicit coverage and termination receipts. Reuse proven pagination checks.-- [x] Preserve real page provenance or isolate complete-category recovery staging- from normal page checkpoints; do not label a partial prefix as page 1 of 1.-- [x] Remove complete-category recovery from summary ingestion, so no staging- attempt or concurrent page work remains to join or clean. A retry is page-scoped;- cancellation unwinds before the existing page commit.-- [x] Keep each recovery attempt to one paged response and preserve its coverage- receipt. Existing anomaly, truncation, page-limit, and background-slice handling- remain authoritative; no client-side byte cap was added.-- [x] Preserve classified split/unified behavior, including derived series, when- replacing list-based recovery. Verify native-series fallback separately.--Acceptance: ordinary and exceptional ingestion do not retain a complete category-list; failed recovery cannot publish complete coverage or prune verified data.-Any remaining public list-returning API is explicitly documented and excluded-from claims of bounded internal ingestion.--## V2 — Reduce repeated page-local database work--Priority: second. Status: implemented.--Unified hydration reloads all VOD categories to find one category's protection-settings on each page. Split hydration already resolves category context before-its loop. Background indexing also performs repeated hydration reads; audit-their role before removing them because they may observe concurrent progress.--- [x] Resolve immutable mapping context once per safe hydration scope or use a- targeted DAO lookup instead of loading all categories per page.-- [x] Establish how edits/protection changes become visible during a long request.- Retain provider/category locks and generation checks; refresh mutable protection- at commit if required by existing behavior. Do not cache it across requests.-- [x] Audit repeated hydration/count/category lookups and avoid only those that- have equivalent authoritative in-memory state inside the same locked scope.-- [x] Keep row writes, catalog-entry ordering, and successful-page checkpoint in- one transaction. For background operations, inspect transaction boundaries- before changing batching; prevent checkpoints advancing ahead of durable rows.-- [x] Preserve stable IDs, favorites, watch progress, protection, and duplicate- rules. Use batch DAO operations where existing page methods already support them.--Acceptance: equivalent persisted content and checkpoint behavior with fewer-redundant lookups, asserted through fake call counts and Room state checks.--## V3 — Evaluate bounded background fetch/write overlap--Priority: after V1/V2. Status: evaluated; retain the bounded category windows.--Background indexing currently awaits all results in a bounded category window,-then validates and persists successful pages. This is already bounded; replacing-it is justified only if a small pipeline simplifies useful overlap without-weakening ordering, scheduling, or retry behavior.--- [x] Document category/duplicate precedence and page transaction ownership first.-- [x] Decide whether to retain windows or use admitted fetches feeding a single- writer through a bounded queue. Record the decision and reason in this document.-- [x] Not applicable: a fetch/write pipeline was not adopted; the existing bounded- windows and deterministic category order were retained.-- [x] Not applicable: no producer queue or reorder buffer was introduced.-- [x] Not applicable: network-permit/backpressure behavior was unchanged.-- [x] Summary row batches and checkpoint/job/prune writes now assert workflow- ownership inside their Room transactions; checkpoints still advance only after- durable row commits. Bounded windows retain their existing scheduling behavior.--Acceptance: failure in one category cannot corrupt another; cancellation joins-all work; committed pages resume correctly; queue pressure cannot block a portal-permit needed by the consumer. If retained windows are the better fit, mark this-stage complete with that decision rather than adding concurrency for its own sake.--## V4 — Conditional direct VOD page decoding--Priority: optional follow-up. Status: evaluated and deferred.--VOD pages already bound typical response size. A direct decoder may avoid trees,-but the live reader is not a drop-in replacement for movie and series metadata.--- [x] Audit all retained fields consumed by movie, native-series, and classified- VOD mappers, including playback descriptors and mixed item classification.-- [x] Decide whether direct decoding is warranted after V1-V3; record the decision.-- [x] Not applicable: direct VOD decoding was deferred; the generic decoder remains- in use and its parsing behavior was not changed.-- [x] Not applicable: no differential decoder path or user-facing switch was added.--Acceptance: equivalent item fields, classification, ordering, and pagination-evidence. A malformed response must never become complete coverage.--## Wildcard policy--Do not broaden wildcard use by default in this plan. Existing limited support-remains authoritative. Wider catalog-wide pagination needs separate evidence of-complete coverage, correct item categories, hidden/protected-scope behavior,-mixed movie/series classification, and safe pruning before replacing category-requests. A returned list alone is not proof of those properties.--## Validation and completion tracking--Extend focused tests using call counts, coroutine barriers, and persisted state.-Do not use elapsed-time performance assertions.--- [x] V1 empty-first-page retry call counts and real page receipt verified.-- [x] V2 targeted protection lookup and transaction placement verified.-- [x] V3 decision documented; bounded windows retained, no pipeline adopted.-- [x] V4 decision documented; direct decoder deferred.-- [x] Split and unified VOD, mixed movie/series, native and derived series verified.-- [x] Empty, repeated, changing-total, truncated-page, and page-limit behavior- verified in focused provider and coordinator tests.-- [x] Retry after committed pages resumes from the next durable page; failed page- attempts do not advance the successful checkpoint or write rows.-- [x] Failed empty-first-page recovery leaves successful coverage unchanged and- skips stale-row pruning.-- [x] Room verifies page ordering, stable identity, favorites, protection, watch- progress, and successful-page coverage checkpoints.-- [x] Room rollback preserves the last committed rows and coverage receipt.-- [x] Room search indexes reflect page updates, and stale-row pruning runs only- after complete coverage, not after a failed empty-page retry.-- [x] Interactive OPEN/NEXT_PAGE/COMPLETE, cancellation boundaries, and durable- retry after a failed page verified.-- [x] Add Provider setup creates VOD/Series category shells without requesting- VOD or Series item pages.-- [x] Background index continuation resumes from persisted category checkpoints;- a focused test resumes a fresh RUNNING job at its next stored page. Interactive- next-page retry after failure is covered separately above.-- [x] A Stalker page-fetch test invalidates the workflow lease after the response- arrives and verifies that neither rows nor its successful-page checkpoint commit.- The ownership check shares each Room write transaction with its mutation.-- [x] Room reopen verifies durable VOD page and index continuation state, and- provider deletion cascades through VOD hydration, catalog entries, movies, and- the Stalker index job.-- [ ] One scenario combining an actual provider edit, active page work,- supersession, and process restart is not covered; real-provider validation- remains separate below.-- [x] Focused unit/instrumentation checks and app build pass.-- [ ] Real-provider VOD browsing, continuation, and representative movie/series- playback verified where changed; unavailable access recorded as a validation gap.-- [x] Shared live playback behavior was not touched; sustained multi-channel- validation from `AGENTS.md` is not applicable to this VOD work.-- [x] Implementation notes list completed stages, evidence, and remaining gaps.--V1 and V2 implementation is complete. V3/V4 were evaluated and deferred as-conditional expansions. Focused tests cover the durable continuation pieces and-the shared workflow supersession fence, but do not combine a background run,-provider edit, and process restart in one scenario. Real-provider VOD browsing,-continuation, and playback remain unverified. Preserve unrelated dirty changes-and existing live work.diff --git a/docs/STALKER_VOD_V1_V2_IMPLEMENTATION.md b/docs/STALKER_VOD_V1_V2_IMPLEMENTATION.mddeleted file mode 100644index 353f9934..00000000--- a/docs/STALKER_VOD_V1_V2_IMPLEMENTATION.md+++ /dev/null@@ -1,126 +0,0 @@-# Stalker VOD V1/V2 implementation--Implemented 2026-10-10. Covers V1/V2 and the conditional V3/V4 decisions in-[the VOD improvement plan](STALKER_VOD_IMPROVEMENT_PLAN.md).--## V1: bounded empty-first-page recovery--Production background indexing now retries only the requested first page when-that page succeeds with no items. The retry uses the existing paged provider-route and returns its original page number, total-page count, advertised totals,-truncation state, and termination reason. The old recovery called-`getVodStreams`/`getSeriesList`, which used the same `get_ordered_list` requests-but accumulated a complete category and then represented it as page 1 of 1.--The retained compatibility behavior is the extra request after an empty first-response, which can recover a transient empty response. For Series, each paged-attempt still prefers the native series route and falls back to one VOD page-filtered by `is_series`; split VOD still uses the classified page path, preserving-movies and VOD-derived series. Existing provider tests cover mixed classification-and page order.--An error from the retry now propagates to the index executor, so it cannot turn-the original empty response into successful coverage. Cancellation unwinds-before any row write or successful-page checkpoint. The page result is committed-through the existing page flow; subsequent page errors preserve already committed-rows and resume from their durable checkpoint. Public list-returning provider-contracts remain available, but summary ingestion no longer calls them.--No category staging layer was needed: this recovery no longer performs a-complete-category attempt or emits rows while a request is in flight. It consumes-one normal paged response, so existing page anomaly checks and background slice-continuation remain authoritative.--## V2: page-local category work--Unified hydration no longer loads every VOD category to find one category's-protection bit. `CategoryDao` now has a targeted provider/type/category lookup.-Hydration reads that mutable flag inside the same Room transaction that writes-movie/series rows, replaces ordered catalog entries, counts persisted entries,-and writes the successful-page checkpoint. A protection edit made while the-network request is running is therefore read at commit time; protection is not-cached across pages or requests.--Split hydration already resolves the movie category before its page loop. Its-series/category counts and page checkpoint reads still affect eligibility,-native-series precedence, or persisted progress, so they remain. Background-indexing reloads hydration at window admission and after the slice to account for-durable progress and concurrent workers. Summary rows commit before their-successful-page checkpoint is advanced; a crash in between replays an idempotent-page rather than skipping uncommitted data.--The interactive coordinator now compares each response fingerprint with both-pages seen during the current COMPLETE request and the last committed page-fingerprint. This catches a portal repeating the last page across separate-NEXT_PAGE calls without replacing the durable successful-page checkpoint. Native-Series-page fallback to VOD is explicitly marked `VOD_DERIVED` in both paged and-legacy list APIs; focused tests cover split mixed-order mapping, unified mixed-mapping, and the fallback classification.--Stalker background index mutations now assert the active provider-workflow lease-inside their Room transactions. This covers summary row/index writes, hydration-attempt and success/failure checkpoints, job state, summary metadata, watch-progress-restoration, and stale-row pruning. A focused test lets a page fetch finish, marks-the lease superseded before its row transaction, and verifies that rows and the-successful-page checkpoint remain unchanged.--## V3/V4 decisions--V3 keeps the existing bounded fetch windows. `awaitAll` preserves the requested-category order, pages remain sequential per category, and the writer processes-the validated window in that order. This is the current duplicate-precedence and-checkpoint ownership rule. A queue pipeline would add retained payloads,-backpressure, and portal-permit coordination without a correctness need, so no-fetch/write overlap was added.--V4 defers direct VOD decoding. Movie, native-series, and classified VOD mapping-consume different metadata and playback descriptors, and the live decoder cannot-stand in for those field contracts. V1 no longer needs a whole-category list, so-the separate decoder work is not required for this change.--## Validation--- Focused unit run passed:- `:data:testDebugUnitTest --tests '*SyncManagerTest' --tests '*VodCategoryHydrationCoordinatorTest' --tests '*StalkerProviderTest'`.- It covers empty-first-page retry call counts, actual page provenance, no- whole-list fallback call, and targeted protection lookup inside the commit- transaction.-- The focused tests also cover resume after a failed NEXT_PAGE, a repeated page- across calls, a changed advertised page total, successful sequential COMPLETE,- and the 200-page COMPLETE limit remaining `TRUNCATED` and incomplete. A failed- empty-first-page retry also leaves the successful checkpoint unchanged, avoids- movie row writes, and does not run stale-row pruning.-- Room instrumentation run passed:- `:data:connectedDebugAndroidTest` with- `-Pandroid.testInstrumentationRunnerArguments.class=com.streamvault.data.local.StalkerVodHydrationIntegrationTest`- passed on the `Television_4K_2(AVD) - 16` emulator against the current database- schema. It covers mixed movie/series page order, category protection, stable- movie IDs, favorites, watch progress, updated movie FTS results, the- completed-page checkpoint, and transaction rollback after a simulated failure.-- A Room lifecycle instrumentation case now closes and reopens the database,- verifies the committed VOD page checkpoint and partial Stalker index job are- still available for continuation, then deletes the provider and verifies Room- cascades clear its hydration, catalog entries, movie rows, and index job.-- Focused SyncManager tests cover resuming a fresh RUNNING Stalker job from its- next persisted page. Shared provider workflow integration tests cover lease- supersession. A Stalker page test also checks lease validity at the page commit- boundary after the response has been fetched. There is not yet one combined- scenario spanning an actual configuration edit, active background write, and- process restart.-- The supersession case passed with:- `:data:testDebugUnitTest --tests '*SyncManagerTest.superseded Stalker movie index cannot commit fetched page rows or checkpoint'`.- The full `*SyncManagerTest` class also passed after adding transaction fences.-- A focused initial-sync test verifies Add Provider stores the VOD and Series- category shells but does not request VOD or Series item pages. Indexing remains- deferred.-- App debug build and `git diff --check` passed. The diff check emitted only- existing working-tree LF/CRLF normalization warnings.-- Real-provider VOD browsing and representative playback: not available in this- workspace; record as a validation gap.-- Background continuation, persisted restart state, stale-lease write fencing,- and provider deletion now have focused component/instrumentation coverage. A- combined provider-edit/supersession/restart scenario and real-provider behavior- remain unverified end to end. Unit checks verify pruning occurs after full- coverage and is skipped after failed first-page recovery.-- No live playback path was changed. No before/after measurements or performance- benchmark suite was run.diff --git a/docs/STREMIO_ADDONS_ACCEPTANCE_CHECKLIST.md b/docs/STREMIO_ADDONS_ACCEPTANCE_CHECKLIST.mddeleted file mode 100644index 00ceb724..00000000--- a/docs/STREMIO_ADDONS_ACCEPTANCE_CHECKLIST.md+++ /dev/null@@ -1,74 +0,0 @@-# Stremio-compatible Add-ons acceptance checklist--Use this checklist for the Android TV UI, D-pad, and normal-use pass after the-direct/debrid and P6 companion implementations are handed over. Run it on the-dedicated `Codex_StremioProvider_Validation_20261013` AVD or another clean profile. The-public Cinemeta add-on is catalog/metadata only; stream and subtitle checks need-separately installed add-ons that provide those resources. Use a legal direct-or debrid HTTP(S) stream source for the direct-playback checks. Torrent/magnet-acceptance has its own checklist in `STREMIO_TORRENT_P6_ACCEPTANCE.md`.-## Navigation and install--- [ ] Extensions keeps the same heading on both tabs. Compact tabs distinguish- the active section from D-pad focus and do not enlarge when focused.-- [ ] Plugin installation explicitly says APK or APK URL; Stremio installation- explicitly asks for a manifest URL. Each section explains what it provides.-- [ ] With no add-ons installed, the Stremio-compatible Add-ons page shows an onboarding message and a- visible Add Stremio-compatible add-on action without requiring navigation to Manage.--- [ ] The top navigation has one Extensions item; its focused tabs switch between- Plugins and Stremio-compatible Add-ons and Back returns to the prior content.-- [ ] Install Cinemeta with `https://v3-cinemeta.strem.io/manifest.json`, then- confirm the manager displays the add-on and its catalogs.-- [ ] Add a stream-capable add-on from its manifest URL. Confirm duplicate,- malformed, unavailable, and configuration-required URLs give a useful result.-- [ ] Confirm Manage displays only the add-on server origin, not URL userinfo,- path, query, or fragment. Disable/enable, reorder, and remove the add-on.-- [ ] Reopen the app and confirm retained add-ons and manager settings persist.--## Browse and choose a stream--- [ ] Browse an enabled catalog, move focus across cards, open an item, and use- Back to return with focus and scroll position intact.-- [ ] Try catalog search and genre filters where offered. Load additional items- and confirm paging ends without duplicated or endlessly repeated cards.-- [ ] Open an item whose metadata comes from a different add-on than its catalog.- Confirm the detail page keeps the catalog provenance and shows stream rows- from enabled stream add-ons.-- [ ] Test no-stream, unsupported-stream, partial-add-on-failure, retry, and- parental-control states. Confirm one failing add-on does not hide other results.--## Playback and history--- [ ] Play a direct MP4 stream and an HLS stream. Confirm playback starts, seek- works, and Back returns to a usable detail or browse screen.-- [ ] If available, try a stream requiring request headers. Confirm playback- works internally and the credentials do not appear in UI or logs.-- [ ] Open the subtitle picker with inline and add-on-provided subtitles. Select- a track, then switch episodes and confirm the old episode's results do not- remain selected or appear in the new episode.-- [ ] Stop and reopen an item from Stremio progress/history. Confirm the app- resolves a fresh stream and resumes near the saved position.-- [ ] Without the Torrent plugin enabled, confirm magnet rows show the clear- missing-plugin or disabled-plugin message. With it enabled, use- `STREMIO_TORRENT_P6_ACCEPTANCE.md` for torrent playback, seek, and teardown.- Cast must reject add-on-origin-scoped headers rather than send them to a- receiver. Stremio external-player handoff is not part of v1.--## Privacy and visibility — revised during user acceptance (2026-10-14)--Implemented in the UI/UX cleanup; user acceptance is pending. These criteria replace-the previous blanket Stremio parental-control gate.--- [ ] Stremio-compatible Add-ons are open by default, including browsing, installation,- and playback, independently of the global parental-control level.-- [ ] Settings → Privacy offers "Hide Stremio-compatible add-ons", off by default.-- [ ] Enabling the option hides Stremio-compatible Add-ons; disabling it restores access.-- [ ] The visibility choice persists after restarting the app.-- [ ] Existing global parental-control settings continue to work for their- other content without being changed to access Stremio-compatible Add-ons.--Record the device/profile, add-on names and capabilities, steps that failed, and-the screen/remote action where focus or expected behavior diverged. Redact-configured URLs, tokens, cookies, and authorization headers from any notes or-screenshots.diff --git a/docs/STREMIO_ADDONS_HANDOFF.md b/docs/STREMIO_ADDONS_HANDOFF.mddeleted file mode 100644index 0b9e3b75..00000000--- a/docs/STREMIO_ADDONS_HANDOFF.md+++ /dev/null@@ -1,163 +0,0 @@-# Stremio addons — continuation handoff--User acceptance correction (2026-10-14), implemented; user acceptance pending: Stremio-Add-ons must be open by default, independent of the global parental-control-level. Add Settings → Privacy → "Hide Stremio Add-ons", off by default.-This replaces the blanket parental gate documented in the historical results-below. The updated debug APK is installed on emulator-5558. Track-the new acceptance criteria in `STREMIO_ADDONS_ACCEPTANCE_CHECKLIST.md`.--Working agreement: the user owns manual UI/UX and emulator acceptance testing.-The agent implements changes and runs build/code checks, then hands over the-build. Do not continue manual emulator testing unless the user asks.--UI cleanup implements a stable Extensions heading, compact fixed-scale tabs,-plugin-specific APK/URL action labels, and Stremio onboarding with a visible-Add action. The hide preference is independent of global parental controls,-off by default, and retained in DataStore. The temporary hide choice used-during agent checks was returned to off; global parental settings are intact.-Build and code checks passed (30 Stremio, 63 Settings, 165 app unit tests,-plus the focused visibility preference test). Four existing plugin UI checks-passed before the user clarified testing ownership. Plugin golden assets were-re-recorded; their subsequent comparison was not run. User acceptance items-remain unchecked.--P6 implementation is complete. The Stremio stream picker constructs a validated-magnet URI from `infoHash`, tracker sources, and `fileIdx`; the plugin manager-requires an enabled scheme-owning handler, rejects non-loopback plugin outputs,-and sends best-effort stop IPC when playback closes. The separate companion-repository at `D:\antigravity-scratch\streamvault-torrent-plugin` contains the-libtorrent engine, loopback byte-range server, plugin IPC service, configuration-Activity, tests, and a successful debug APK build. JVM tests and APK assembly-pass. The companion source is committed locally at `9ac943c` (branch `main`, no-remote configured). Real torrent playback, seeking, replay, and teardown have not been tested;-the user owns that manual acceptance pass in `STREMIO_TORRENT_P6_ACCEPTANCE.md`.--Continuation update (2026-10-12): P0–P5 are implemented in this worktree. P1 is-committed at `e96ce49e`; P2–P5 and the Extensions navigation follow-up remain-uncommitted. Unit tests and debug assembly pass. P4 direct MP4 playback and-history/resume were smoke-tested. The synthetic HLS fixture raised transient-network EOFs over local HTTP/1.0, but the same playlist and segments completed-over HTTP/1.1 on the same host port; validate with a real third-party addon-endpoint before classifying this as a player defect. A remote HLS VOD smoke also-passed through the local Stremio fixture, as recorded below. P5 inline subtitle-discovery and the picker were smoke-tested. Cross-addon subtitle playback is now-verified on isolated API 36 `emulator-5556`: the fresh `tt7654327` item exposed-the German track from the independent subtitle-only addon, and its VTT cue-rendered while the player remained healthy. At that point the remaining v1-gates were a real third-party addon HLS/DASH child-resource check, provider-playback, and header-dependent cast/external-player regression. No suitable-public-domain third-party HLS addon was found. The install-URL storage/export/-removal policy is documented, Manage shows only addon server origins, and D-pad-focus through Extensions and its sub-tabs is verified. See-`STREMIO_ADDONS_PLAN_REVIEW.md`.--Continuation update (2026-10-13): provider playback now passes on a dedicated-clean Android TV API 36 AVD using the local V11 fixture. HLS played through a-145-second health/position-advance hold; 61 screenshots at two-second cadence-span 120.26 seconds with 60 distinct hashes because the synthetic VOD loops at-120 seconds. Media session was PLAYING with `error=null` during capture, and-sanitized logs show HLS prepare, first frame, playlist/segment reads, and no-retry, fatal error, stuck timeout, or MPEG-TS fallback. Progressive MP4 also-reached first frame. Cleanup passed and the fixture provider row count is zero.-This is provider-fixture VOD validation, not a real provider or live-TV result.-The real third-party addon HLS/DASH child-request check remains open: the-official Public Domain Movies addon returns torrents, the Archive.org addon-returns direct files and its old host is down, and the community Public Domain-Foreign Movies manifest URL returns 404; its source contains no HLS playlist-references. The header-dependent cast/external-player regression also remains-open.--Copy this whole block into a new session working in the worktree.-------Continue the StreamVault Stremio addon feature. Work only in:-`D:\antigravity-scratch\iptv-player\.worktrees\stremio-addons` (branch `feature/stremio-addons`, based on `develop` @ 540ec30c). Read `docs/STREMIO_ADDONS_IMPLEMENTATION_PLAN.md` first. P1 was committed after its verification; check the current branch history for the commit.--Important: the worktree now uses Room DB version 80. It includes the historical-78→79 addon-registry migration and the new 79→80 Stremio playback-history-migration. A separate emulator profile with a version-81 database is still not a-valid target for this branch; do not clear shared emulator data to work around it.--## Done and verified--- P0 (protocol client): `data/src/main/java/com/streamvault/data/remote/stremio/` (`StremioAddonClient`, `StremioAddonUrl`, `StremioAddonDtos`, `StremioMapper`) + domain models `domain/src/main/java/com/streamvault/domain/model/stremio/`; the latest focused client/URL run has 24 passing tests.-- P1 data layer: `StremioAddonEntity`, `StremioAddonDao`, `FeatureMigrationsV78To79`, `StremioAddonRepository` (domain) + `StremioAddonRepositoryImpl`, `StremioCatalogSettingsCodec`, `StremioAddonClient.fetchManifestSnapshot/parseManifest`; DI wired in `DatabaseModule`/`RepositoryModule`; schema export `data/schemas/com.streamvault.data.local.StreamVaultDatabase/79.json`; repository tests covered configuration-required rejection (14 now passing after P2 coverage); `StreamVaultDatabaseMigrationTest` — 43 tests green on emulator-5554 (API 36), including the new `migrate78To79_...` test.-- P1 verification update: `:app:testDebugUnitTest` passed 163 tests; `:feature:stremio:testDebugUnitTest` passed 6; focused data tests passed 34 (`StremioAddonClientTest` 13, `StremioAddonUrlTest` 9, `StremioAddonRepositoryImplTest` 10, migration registry 2). `:app:assembleDebug` succeeded. A broader data run hit unrelated download mock-server and Google Drive backup test failures; the focused Stremio rerun passed.-- P1 emulator smoke: installed `com.streamvault.app.debug` on isolated `Television_1080p` (API 36) and installed `https://v3-cinemeta.strem.io/manifest.json`. Screenshot: `addons.png`. At that point the branch was at DB v79. The current worktree is v80; `Television_4K_2` was later found at DB v82 and remains incompatible, so its data was left untouched.-- P1 nav/UI: `AppDestination.Addons` and its route remain distinct; the global navbar now uses one `AppTopLevelDestination.EXTENSIONS` item with focusable Plugins / Stremio Add-ons tabs. Legacy saved top-level `plugins` and `addons` values migrate to `extensions`, while plugin/addon startup destinations remain available. The new `feature:stremio` module (`StremioRoutePatterns.ADDONS="addons"`, `AddonsViewModel`, `AddonsScreen`) is wired through `AppNavHost`; the APK Plugins screen is still separate. Unit and emulator smoke validation for P1 are complete.-- P2 catalog browsing and Extensions navigation polish are implemented but uncommitted: Browse and Manage tabs, enabled-addon/catalog rows, search/genre and required-extra gates, nullable `hasMore`, raw response counts and 100-item skip pagination, duplicate-page/page-count guards, cancellation of stale requests, refresh-aware cache identity, 200-page/5-minute LRU cache, errors/retry/empty/loading states, and TV card focus border. Seven `StremioCatalogBrowseViewModelTest` cases and six existing Addons ViewModel tests pass. Focused data tests pass (14 client, 10 URL, 14 repository); `:app:assembleDebug` passes.-- P2 TV smoke: on isolated `Television_1080p` API 36 (`emulator-5556`), installed the latest APK, installed Cinemeta through Manage, loaded its Popular catalog/posters through Browse, and navigated by D-pad to a focused card. The catalog heading renders with readable foreground contrast. The shared `emulator-5554` was not used for this smoke.-- Extensions navigation follow-up (2026-10-12): one Extensions navbar/settings item now opens focusable Plugins and Stremio Add-ons tabs; the plugin and addon routes and startup landing choices remain distinct. Legacy top-level `plugins`/`addons` preferences normalize to `extensions`. `:domain:test`, `:app:testDebugUnitTest`, `:feature:system:testDebugUnitTest`, `:feature:stremio:testDebugUnitTest`, `:feature:system:compileDebugAndroidTestKotlin`, and `:app:assembleDebug` pass. Updated plugin golden screenshots; both plugin screenshot tests pass on the isolated read-only `Codex_Trakt` API 36 emulator. The full System golden class still has four existing welcome/download pixel mismatches on that AVD.-- P3 meta/detail and cross-addon resource routing (2026-10-12): implemented `StremioResourceResolver` for enabled addons with resource/type/exact-ID-prefix matching, catalog-origin-first metadata fallback, stable bounded stream/subtitle fan-out, attributed partial results, retry, and cancellation. The detail page preserves catalog provenance and exact `meta.videos[].id` values, shows unsupported stream rows with reasons, and creates a typed playback reference for eligible direct URLs.-- P4 playback/history (2026-10-12): direct/debrid playback uses the normal player pipeline with selected media headers scoped to media requests; magnet casting is blocked with an explicit unsupported state; addon progress lives in `stremio_playback_history` at Room version 80 and reopens through fresh stream resolution rather than stored URLs. Migration, history, playback-identity, header-sanitization, cast, and player tests pass. The migration instrumentation suite passed all 45 tests on isolated `Television_1080p` (API 36), including 79→80. On isolated API 36 `emulator-5556`, synthetic MP4 playback and resume/history reopening worked. The synthetic 120-second HLS asset raised `unexpected end of stream` at media positions 67.878s and 115.874s when served by the local HTTP/1.0 fixture; the player retried and recovered each time. The same playlist and segments served over HTTP/1.1 on the same host port completed at 120.007s with 51 screenshots (38 unique frames), all 31 datasource reads complete, and no retry/error. Treat the failure as a local fixture transport issue pending a real Stremio addon HLS smoke. This VOD check is not live-TV validation.-- P4 remote HLS VOD smoke (2026-10-12): the public Mux Big Buck Bunny HLS sample (`https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8`) played through the local Stremio fixture on isolated API 36 `emulator-5556`. Captured 61 screenshots at a two-second cadence; all 61 frame hashes were unique. Logs showed HLS prepare and first-frame success, and media session was `PLAYING` at position 213,376 ms with `error=null` when capture ended. There were two startup audio-underrun warnings and no retry, fatal error, stuck timeout, or MPEG-TS fallback. This validates remote HLS VOD playback; a real third-party addon endpoint and its redirect/header behavior remain open. This is not live-TV validation.-- P5 subtitles (2026-10-12): inline `stream.subtitles` are parsed and carried ephemerally with the playback request; addon subtitle resources are loaded lazily from the player picker, including `videoHash`, `videoSize`, and `filename` extras, language mapping, URL filtering/deduplication, and external-track injection. A focused overlay test fixed the no-embedded-track dead end by keeping the CC action visible when Stremio subtitle sources exist. Focused subtitle, player, data, app tests and debug assembly pass. On isolated API 36 `emulator-5556`, the picker showed the German resource from the independent subtitle-only addon for `tt7654327`; selecting it logged `addExternalSubtitle language=de`, rendered “Fixture German subtitle,” and media session remained `PLAYING` with `error=null`.-- Parental-control gate (2026-10-13): because addon catalogs and meta do not provide a dependable age rating, the whole Stremio feature is treated as protected content. Off allows access; Locked and Private require the existing PIN once per app session; Hidden blocks Stremio content and install. Private also omits Stremio continue-watching from the aggregate surface. Both browse and item routes are gated before their screens (and network requests) are created; install, catalog fetch, metadata, and stream actions also fail closed. Unit tests cover all four levels and blocked install/catalog/detail requests. TV smoke on isolated `Television_1080p` API 36 (`emulator-5556`) verified Hidden denial, Locked and Private PIN prompts, rejection of a wrong PIN, successful unlock, re-lock after changing levels, and Off access without a PIN. The original 1,750-byte preferences file was restored and its SHA-256 verified; `emulator-5554` and `Television_4K_2` were not used.-- Header/privacy review (2026-10-13): selected stream headers are validated and applied by an isolated playback client with cookies, authenticators, and cache disabled. The network interceptor adds them only for the selected media origin; an existing MockWebServer test confirms a cross-origin 302 does not forward Authorization. Playback history contains no stream URL or request headers. Credential policy: keep configured install URLs in app-private Room so addon configuration survives app restarts; do not log, back up, or include addon records in manual export; show only the origin in Manage; Remove deletes the active addon row, while disabling retains it. Room does not add app-level encryption, so protection relies on the Android app sandbox and device storage encryption. HLS/DASH child-resource and cast/external-player behavior still need verification with a suitable addon or fixture.-- Public-domain addon source check (2026-10-13): the official Public Domain Movies addon serves torrent `infoHash` streams for public-domain catalog items (verified with `tt0012349`, `tt0063350`, and `tt0013257`); torrent playback is deferred to P6, so this cannot validate direct HLS playback. The maintained Internet Archive addon source generates `archive.org/download/...` file URLs for AVI/MP4/MKV/WMV/MOV/M4V and does not emit HLS playlists; its previously published Baby-Beamup host no longer resolves. The community Public Domain Foreign Movies repository advertises public-domain/free-to-view sources, but its published `now.sh` manifest currently returns 404 and a source scan found no `.m3u8` stream references. No suitable public-domain third-party HLS addon was found. Keep the third-party-addon HLS gate open; do not count either local-fixture VOD smoke as satisfying it. Sources: [official Stremio addon index](https://github.com/Stremio/stremio-official-addons/blob/master/index.json), [Public Domain Foreign Movies source](https://github.com/jaruba/stremio-public-domain-foreign/blob/master/index.js), [Public Domain Foreign Movies README](https://github.com/jaruba/stremio-public-domain-foreign/blob/master/README.md).-- TV navigation regression check (2026-10-13): on isolated API 36 `emulator-5556`, D-pad focus moved from Home to the single Extensions navbar item, then between Plugins and Stremio Add-ons tabs. The Stremio Add-ons content correctly displayed the Hidden parental-control gate. The emulator's restored 1,750-byte preferences file still matches its original SHA-256; no settings were changed.-- Provider playback fixture validation (2026-10-13): created a separate clean Android TV API 36 AVD, `Codex_StremioProvider_Validation_20261013` (`emulator-5558`), and ran instrumentation directly with `adb` so Gradle did not uninstall app data. `V11 HLS Adaptive Fixture` resolved as HLS (H.264/AAC, 640x360, 2.5 Mbps; TTFF 1,122 ms); local server events included the master and child playlist plus `segment_000.ts` and `segment_001.ts`. The probe held HLS playback for 145 seconds and checked every two seconds that state stayed READY, `isPlaying` stayed true, and position advanced. Concurrent capture took 61 screenshots at a two-second cadence over 120.26 seconds; 60 hashes were unique because the 120-second synthetic VOD loop repeats its first frame at the end. At about 105 seconds, media session was PLAYING at position 105,101 ms with `error=null`. Logs contain HLS prepare/first-frame and progressing hold entries, with no retry, fatal error, stuck timeout, or MPEG-TS fallback. The progressive fixture also reached first frame (H.264/AAC, 640x360; TTFF 354 ms). A cleanup instrumentation test passed, and a read-only database check found zero `stremio_addons` rows after cleanup. This is VOD fixture validation, not live-TV validation or a third-party addon test.-- Playback-test environment incident (2026-10-13): `:app:connectedDebugAndroidTest` was run without a serial filter, so Gradle targeted both connected devices. The isolated `Television_1080p` run passed; `Television_4K_2` failed because its database is version 82 while this worktree expects version 80. Gradle removed `com.streamvault.app.debug` from `emulator-5556` after the run. The app was reinstalled and its Room v80 database and saved preferences were restored from local snapshots, but uninstalling destroyed Android Keystore keys: the restored provider rows' encrypted credentials now fail decryption and must be re-entered. The original local M3U cache was not in the available backups. Do not use `emulator-5556` for provider playback until credentials are re-entered, do not clear `emulator-5554`/`Television_4K_2`, and avoid connected Gradle tasks without an explicit single-device filter. The fresh `emulator-5558` was used for the fixture check instead.-- Credential display regression fix (2026-10-13): the Manage-addon row now renders only the parsed server origin, omitting credentials in URL userinfo, path, query, and fragment. `StremioAddonOriginLabelTest` covers configured secrets, default/custom ports, IPv6, and malformed URLs. The focused Stremio unit test and `:app:assembleDebug` pass.-- Cast privacy and usability follow-up (2026-10-13): Stremio playback retains an origin marker even with no request headers so its isolated network client is still used. `CastMediaRequestFactory` now blocks casting only when a Stremio stream actually has scoped headers; headerless direct streams can use the normal cast path. Focused playback tests cover both outcomes, including `blocks addon origin scoped headers from cast requests` and `allows headerless addon media to use the normal cast path`.-- Final local code gate (2026-10-13): `:feature:playback:testDebugUnitTest --tests com.streamvault.feature.playback.cast.CastMediaRequestFactoryTest :app:testDebugUnitTest :feature:stremio:testDebugUnitTest :domain:test :data:testDebugUnitTest :app:assembleDebug` passed. The latest APK was installed with `adb -s emulator-5558 install -r ...` and launched on the dedicated clean Android TV API 36 AVD; `com.streamvault.app.debug/MainActivity` resumed successfully. No connected Gradle task was run.-- P3 verification: `:domain:test --tests com.streamvault.domain.repository.StremioResourceResolverTest`, focused Stremio data tests (`StremioAddonClientTest`, `StremioAddonRepositoryImplTest`), `:feature:stremio:testDebugUnitTest`, `:app:testDebugUnitTest`, and `:app:assembleDebug` passed. A fresh `:feature:stremio:testDebugUnitTest :app:assembleDebug` run also passed after a TV-discovered detail-text contrast fix.-- P3 TV smoke: on read-only isolated `Television_1080p` API 36 (`emulator-5556`), installed Cinemeta, browsed Popular, opened the Unabomber detail page, confirmed metadata provenance and readable text, then requested streams and confirmed the clear no-enabled-stream-addon state. This smoke did not validate playback or a real multi-addon stream list; cross-addon behavior is covered by repository/domain/feature tests. The shared `emulator-5554` was not used.--## Immediate next steps--1. P1 unit verification, emulator install smoke, and the reviewed P1 commit are- complete; see the results above. Commit: `e96ce49e`.-2. P2 and P3 are implemented and verified against AD-10 and AD-9. Their worktree- changes, including the Extensions navigation follow-up, remain uncommitted.-3. The direct/debrid v1 implementation and local verification are complete.- The parental PIN smoke is complete on isolated API 36 `emulator-5556` at- Off, Locked, Private, and Hidden levels. D-pad navigation through Extensions- and its Plugins/Stremio Add-ons tabs is also verified. No suitable- public-domain third-party HLS addon was found: the official public-domain- catalog returns torrent streams, Archive.org returns direct files, and the- community foreign-movies addon has a dead manifest host and no HLS URLs in- its source. Keep the real-addon HLS gate open until an eligible endpoint is- available; the remote sample and provider fixture through local servers are- complete. The credential storage/export/removal policy is now documented and- the Manage screen displays only the server origin. Scoped-header casting is- intentionally rejected and unit-tested; headerless direct streams use the- normal cast path. External-player handoff is outside direct/debrid v1. The- only remaining external qualification is real-addon HLS/DASH child-resource- playback; no suitable public-domain endpoint was found. The independent- subtitle-only fixture smoke is complete. Playback checks use VOD only; do not- report them as live-TV validation. The latest debug APK is installed and- launched on clean Android TV API 36 `emulator-5558` for the manual UI/usage- pass in `docs/STREMIO_ADDONS_ACCEPTANCE_CHECKLIST.md`.-4. P6 implementation is complete; the user still owns the real-torrent manual- acceptance pass in `STREMIO_TORRENT_P6_ACCEPTANCE.md`. Home/global search- remains optional.--## Environment gotchas--- Windows PowerShell; use `.\gradlew.bat`. Long builds: run detached `Start-Process cmd.exe -ArgumentList "/c",".\gradlew.bat ... > log 2>&1" -PassThru -NoNewWindow` and poll the log — don't block in foreground >2 min.-- Worktree has its own `local.properties` (sdk.dir=C:\Users\David\AppData\Local\Android\Sdk).-- Emulator `emulator-5554` (API 36) is connected; instrumented: `:data:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.streamvault.data.local.StreamVaultDatabaseMigrationTest`.-- `Television_4K_2` has database version 82 while this worktree is at 80; use a clean/read-only emulator profile for this version-80 worktree rather than clearing shared app data.-- The 2026-10-13 unfiltered `:app:connectedDebugAndroidTest` also targeted `Television_4K_2` and uninstalled the app from `emulator-5556`; app-private backups do not restore Android Keystore keys. Existing provider credentials there cannot decrypt until re-entered. Use serial-targeted `adb shell am instrument` on the clean `emulator-5558` for fixture work, and do not clear data on `emulator-5554` or `Television_4K_2`.-- Data module uses OkHttp + kotlinx.serialization DTOs; domain has no serialization — keep that split.-- Cosmetic compiler warning: `hiltViewModel()` has moved to `androidx.hilt.lifecycle.viewmodel.compose`; the current build succeeds.-- Do not reuse provider URL policies for addon streams (relevant in P4).--## Remaining phases (details in the plan doc)--Direct/debrid v1 implementation (P0–P5 and required P7) and local regression-checks are complete. Cross-addon subtitles, remote HLS VOD through the local-Stremio fixture, provider fixture playback, the parental gate, and Extensions-navigation have passed their recorded checks. The latest debug APK is installed-and launched on clean Android TV API 36 `emulator-5558`, ready for the manual-UI/usage pass. A real third-party addon HLS/DASH and child-resource smoke remains-external qualification because no suitable public-domain addon endpoint was-found. Scoped-header casting is intentionally rejected and unit-tested;-headerless direct addon streams use the normal cast path. External-player-handoff is outside direct/debrid v1. P6 implementation is complete and its-real-torrent acceptance remains with the user; optional Home/global search-remains deferred. P1 is verified and-committed; P2–P5, the parental gate, and Extensions navigation remain uncommitted.diff --git a/docs/STREMIO_ADDONS_IMPLEMENTATION_PLAN.md b/docs/STREMIO_ADDONS_IMPLEMENTATION_PLAN.mddeleted file mode 100644index ff8238e6..00000000--- a/docs/STREMIO_ADDONS_IMPLEMENTATION_PLAN.md+++ /dev/null@@ -1,518 +0,0 @@-# Stremio addon support implementation plan--Status (2026-10-16): P0–P6 implementation and required P7 polish are complete;-P6 real-torrent playback acceptance is pending the user. The companion source-and debug APK live in the separate `D:\antigravity-scratch\streamvault-torrent-plugin`-repository. P1–P6 code/build verification is recorded in-`STREMIO_ADDONS_HANDOFF.md`. P4 MP4/history and provider fixture-playback checks passed. The synthetic HLS VOD fixture initially failed around-68 seconds over local HTTP/1.0; the same asset completed over HTTP/1.1 on the-same host port. A public Mux HLS sample passed 61 screenshots at a two-second-cadence through the local Stremio fixture, with unique frames and a healthy-media session. The provider HLS fixture then passed a 145-second advancing-playback hold, with 61 screenshots across 120.26 seconds (60 unique hashes-because the fixture loops at 120 seconds), healthy media-session state, and no-retry/fatal/stuck/fallback logs. These local fixtures do not close the external-real third-party addon HLS/DASH child-resource qualification. Scoped addon-headers are intentionally rejected for casting, while headerless direct streams-use the normal cast path; external-player handoff is outside v1. P5 inline and-independent subtitle-addon playback smoke passed on the isolated API 36 emulator;-the German WebVTT cue rendered from the subtitle-only addon.-The parental PIN gate is now smoke-tested at all four levels on TV, and D-pad-focus through Extensions and its Plugins/Stremio Add-ons tabs passes. Credential-storage/export/removal policy is documented, and Manage shows only addon server-origins. No suitable public-domain third-party HLS addon was found: the official-catalog returns torrents, the Archive.org addon returns direct files, and the-community Foreign Movies manifest host is down and its source has no HLS-playlist references. All direct/debrid v1 implementation and local regression-gates are complete. A real-addon HLS/DASH child-request smoke remains external-qualification. Scoped-header cast rejection is unit-tested; headerless direct-streams use the normal cast path. External-player handoff is outside v1.-Plan reviewed 2026-10-11; see `STREMIO_ADDONS_PLAN_REVIEW.md` for external-qualification and user acceptance.--## Current handoff status (2026-10-16)--- **User acceptance correction (2026-10-14), implemented; user acceptance pending:** UI/UX- cleanup makes Stremio Add-ons open by default, independently of the- global parental-control level. Uses a separate Settings → Privacy →- "Hide Stremio Add-ons" option, off by default. This supersedes the blanket- Stremio parental gate described below; those sections record the prior- implementation and its historical verification. The user owns manual UI/UX- acceptance testing; agent checks should be limited to builds and code tests.-- [x] P0–P5 direct/debrid Stremio support is implemented; required P7 polish is- implemented. Verification details are in `STREMIO_ADDONS_HANDOFF.md`.-- [x] P6 implementation is complete: the host routes validated magnet URIs to- an enabled scheme-owning plugin, restricts plugin output to loopback, and- sends best-effort playback-stop IPC. The separate companion repository- contains the libtorrent engine, byte-range server, configuration Activity,- and debug APK. Unit tests and APK build pass; real-torrent emulator acceptance- is pending the user. See `STREMIO_TORRENT_P6_ACCEPTANCE.md`.-- [x] Debug APK `1.0.19-debug` was built from this worktree, installed with- replace/retain-data on `emulator-5558`, and `MainActivity` was launched on the- dedicated Android TV API 36 AVD `Codex_StremioProvider_Validation_20261013`.-- [ ] User UI/UX and normal-use acceptance pass is pending; use- `STREMIO_ADDONS_ACCEPTANCE_CHECKLIST.md` and leave its items unchecked until- the user exercises them.-- [ ] Real third-party addon HLS/DASH child-request qualification remains open.-- [ ] User end-to-end torrent playback acceptance is pending; use- `STREMIO_TORRENT_P6_ACCEPTANCE.md`. The agent has not installed the companion- APK or tested a real torrent.--Prepared 2026-10-10 against source-revision `540ec30c` (`develop`), branch `feature/stremio-addons`, worktree-`.worktrees/stremio-addons`.--Goal: StreamVault can install Stremio addons by URL and use them natively — browse-catalogs, open meta/details, choose from a stream list, play direct and torrent-backed-streams, and load addon subtitles. Torrent playback is delivered by a companion-StreamVault plugin APK so the main application and repository never ship a BitTorrent-engine.--## Outcome and scope--Deliver a first-class "Addons" surface in StreamVault:--- Install an addon by pasting its manifest URL or a `stremio://` install link.-- Manage installed addons (enable/disable, remove, reorder, catalog selection).-- Browse catalog rows per addon with pagination, genre filters, and catalog search.-- Open movie/series meta pages for addon items (poster, background, description,- cast, release info, seasons/episodes).-- Pick from the addon's stream list ("stream picker"), showing name/title/quality- hints exactly as the addon returns them.-- Play direct (http/https, including debrid-resolved) streams through the existing- player pipeline, with resume and history.-- Load addon-provided subtitles into playback.-- When a torrent stream (infoHash/magnet) is selected and the companion torrent- plugin is installed, resolve it through the plugin into loopback playback.- Without the plugin, show an explicit "torrent playback requires the StreamVault- Torrent plugin" state instead of failing playback.--V1 scope note: direct/debrid streams are the phase-1 usable product. Torrent-playback is phase-gated (P6) behind the companion plugin and a separate repository.--Non-goals for this plan:--- Stremio account, sync, or Trakt integration.-- YouTube (`ytId`) stream playback.-- `externalUrl` / opener streams, NZB, or other non-media endpoints.-- A web-based addon configuration editor. V1 accepts already-configured manifest- URLs (users configure addon URLs in their browser, then paste the result).-- Addon content inside the Live TV, Movies, Series, or Guide tabs in v1. Stremio- content lives in its own destination; Home/global-search integration is a P7- option.-- Casting torrent-backed streams. See AD-6.--## Why the existing plugin M3U path is not enough--The plugin API can already surface a companion APK as a provider-(`MSG_GET_PROVIDER_URL`, `StreamVaultPluginManager.kt:661`) and can prepare playback-URLs (`MSG_PREPARE_PLAYBACK`, `StreamVaultPluginManager.kt:481`), but it cannot-produce the Stremio experience:--- The M3U importer flattens everything into channels/movies/series rows with a- single stream URL. Plugin providers are additionally forced to live-only- classification (`m3uVodClassificationEnabled = false` reset at- `StreamVaultPluginManager.kt:700`; importer treats entries as LIVE at- `SyncManagerM3uImporter.kt:240`).-- Stremio's model is one meta to many streams, with user selection at play time.- No catalog rows, meta pages, or stream-picker UI exist in StreamVault's catalog- surfaces (`feature/catalog/.../presentation`).-- A plugin cannot inject UI into the host. Only its own configuration Activity.-- Sync-based ingestion is the wrong data flow: Stremio catalogs are remote,- dynamic (IMDB-id keyed), paginated, and change per request. They must not be- copied into the synced provider catalog tables.--Conclusion: the host application must become the Stremio addon client. The plugin-boundary is kept only where it is genuinely needed — torrent resolution — using the-existing `playback.prepare` capability with a `magnet:` scheme (see AD-3).--## Stremio addon protocol summary (implementation-relevant)--Transport: plain HTTP(S) JSON endpoints under the addon base URL.--- Manifest: `GET {base}/manifest.json` → `id`, `version`, `name`, `description`,- `logo`, `background`, `resources` (e.g.- `["catalog","meta","stream","subtitles"]`), `types` (`movie`, `series`,- `channel`, `tv`), `catalogs` (`type`, `id`, `name`, optional `extra`,- `genres`), `idPrefixes` (e.g. `["tt"]`), `behaviorHints`- (`configurable`, `configurationRequired`).-- Catalog: `GET {base}/catalog/{type}/{id}.json`, with extras:- `/catalog/{type}/{id}/skip={n}.json`, `/genre={genre}.json`,- `/search={query}.json`. Response: `metas` array of meta previews plus optional- `hasMore`.-- Meta: `GET {base}/meta/{type}/{id}.json` → `meta` with full detail; series meta- carries `videos` (seasons/episodes, id format `tt1234:1:2`).-- Stream: `GET {base}/stream/{type}/{id}.json` → `streams` array. A stream is one- of: `url` (http/https direct, debrid addons use this), `infoHash` (+ optional- `fileIdx`, tracker `sources`), `ytId`, `externalUrl`. Optional `name`, `title`,- `description`, `behaviorHints` (`notWebReady`, `bingeGroup`, `filename`,- `videoSize`, `proxyHeaders`).-- Subtitles: `GET {base}/subtitles/{type}/{id}.json` (plus optional- `/videoHash=...`/`/filename=...` extras) → `subtitles` array with `id`, `url`,- `lang` (3-letter codes).-- Install links: `stremio://host/path/manifest.json` is an install alias for the- corresponding `https://` manifest URL. Many addons are configured by query- parameters, so the "install URL" is the whole configured manifest URL and must- be stored verbatim (minus the scheme rewrite).--Compatibility notes for the client:--- Unknown fields anywhere must be ignored (forward compatibility).-- `resources` may be objects with per-resource `types`/`idPrefixes`; catalog- entries may each declare their own `extra`.-- Missing `idPrefixes` means the addon handles all ids of its declared types.-- Long catalog/meta responses can be large; keep timeouts and page sizes bounded.--## Architecture decisions--### AD-1: Host-native Stremio addon client--The host implements the protocol directly (HTTP + kotlinx.serialization + OkHttp,-following existing data-module network client conventions and the Hilt `Json`-config in `app/.../di/NetworkModule.kt`). Addons are ordinary HTTP resources; no-plugin or WebView is required. This is the only way to get native catalog/meta/-stream-picker UX in the host, and it keeps the plugin contract untouched for-P0–P5.--### AD-2: Separate content store, not a provider type--Stremio addons are not `ProviderType` entries and do not run through provider sync.-New Room table `stremio_addons` (P1) stores install records; catalogs/meta/streams-are fetched on demand (bounded in-memory cache per session; a persistent response-cache is explicitly deferred). This avoids polluting provider-scoped catalog DAOs,-`ProviderSnapshot` assumptions, and the sync pipeline. `LegacyProvider`/-`ProviderSnapshot` (`domain/.../model/Provider.kt`, `ProviderConfiguration.kt`)-are untouched by this feature.--### AD-3: Torrent playback via companion plugin, existing IPC--The plugin IPC already supports this without contract changes:--- `preparePlaybackStreamInfo` accepts any non-blank URL; a `magnet:` URI has no- host, so scheme-only ownership applies (`PluginPlaybackRouting.kt:37-41`). A- plugin declaring `playbackUrlSchemes: ["magnet"]` receives- `MSG_PREPARE_PLAYBACK` and can return `output_url` (an http loopback proxy),- `stream_type`, and headers (`applyPlaybackPreparationResponse`,- `StreamVaultPluginManager.kt:553`).-- What blocks magnet today is only ingress: `StreamEntryUrlPolicy` /- `UrlSecurityPolicy` allowlists (http, https, rtsp, rtsps, rtmp, file, content)- reject `magnet:` before playback. Addon streams bypass those provider-path- policies and get their own ingress policy (AD-5).--Decision: the torrent engine (libtorrent4j or equivalent JNI) lives in a separate-companion APK in its own repository, not in this repo or the main APK. The host-learns nothing about torrents beyond "a `magnet:` URL may be resolved by an-enabled plugin".--### AD-4: One top-level "Extensions" destination--Keep separate `AppDestination.Plugins` and `AppDestination.Addons` routes and-startup landing options, but show one `AppTopLevelDestination.EXTENSIONS`-destination in the global navigation. Its screen has focusable in-page tabs for-native APK Plugins and Stremio Add-ons, so both features remain distinct without-using two top-level slots. Migrate saved `plugins` and `addons` top-level-navigation values to `extensions`; retain Plugins and Stremio Add-ons as-separate startup choices while Extensions is visible. The addon manager remains-inside Stremio Add-ons, and torrent plugins remain managed as APK plugins.-Files: `domain/.../model/AppTopLevelDestination.kt`,-`domain/.../model/AppLandingDestination.kt`,-`app/.../navigation/AppRouteCodec.kt`, `app/.../navigation/AppNavigationAdapters.kt`,-`app/.../ui/components/shell/AppShellNavigation.kt`,-`core/ui/.../components/shell/ExtensionsSectionTabs.kt`,-`app/.../navigation/StartupNavigationResolver.kt`, `app/.../navigation/AppNavHost.kt`.--### AD-5: Dedicated addon-stream ingress policy--Do not reuse provider URL policy. Introduce a Stremio-specific validation:--- Playable now: `http`, `https`, `magnet` (magnet only resolvable with the torrent- plugin enabled).-- Recognized but unsupported: `ytId`, `externalUrl`, `nzbUrl` → show a clear- "not supported" row state in the picker, never a broken player start.-- Everything else: rejected.-Also sanitize poster/background/logo URLs (https preferred), bound response sizes,-and never forward addon-supplied headers to non-addon hosts.--### AD-6: Cast and external-playback stance--- `magnet:` streams are never castable. Add an explicit guard in- `CastMediaRequestFactory` (`feature/playback/.../cast/`) so an unresolved magnet- can never reach a receiver; the picker hides the Cast action for them.-- After plugin resolution the URL is `http://127.0.0.1:<port>/...`; the existing- cast rewrite path (`cast.rewriteUrl` with `LOCAL_URI` reason) already handles- loopback URLs — without a cast-capable plugin the cast attempt fails as- `UNSUPPORTED`, which is acceptable and should surface a clear message.-- External player handoff: only resolved http(s) URLs are offered; the external- launcher allowlist already excludes `magnet`. Stremio external-player handoff- is outside direct/debrid v1 because the launcher cannot preserve origin-scoped- request headers.-- Casting rejects Stremio media with addon-supplied request headers, since the- receiver cannot preserve their origin scope. Headerless direct streams use the- normal cast path. This behavior is covered by unit tests.--### AD-7: Phase gating — direct/debrid first, torrents at P6--P0–P5 ship a complete, useful product for addons that return direct URLs-(debrid-backed Torrentio, catalog addons, etc.). P6 adds the torrent plugin and-the magnet flow end to end. This keeps legal exposure and schedule risk out of the-main repository for as long as possible.--### AD-8: Content identity, resume, and history--Do not use `PlaybackHistory` for addon items. That table requires a real provider-row through a foreign key, numeric `contentId`/`providerId`, and its replay-navigation currently reuses the stored `streamUrl`. Those assumptions do not fit-remote Stremio IDs, and a stored direct/debrid URL may expire.--Add a `StremioPlaybackHistory` model/repository and a Room table keyed by a-canonical string `contentKey`. The table stores the exact Stremio item/video ID,-type, parent series ID where applicable, display metadata, resume position,-duration, watched state, and catalog-origin namespace. It does not store a-playable URL, stream headers, or addon response bodies. A selected stream's addon-namespace may be kept as a preference hint, but never as content identity.--Identity rules:--- Preserve protocol IDs byte-for-byte after the existing trim validation; do- not synthesize episode IDs from season/episode numbers. The `meta.videos[].id`- value is the episode's request ID; retain the parent `meta.id` separately.-- Recognize only validated IMDb IDs (`tt` followed by digits) as cross-addon- identities: `stremio:global:{type}:{exact-id}`. Episode keys use the exact- `video.id` under `series-episode`; the parent series key remains separate.-- Namespace every other ID by the catalog-origin install identity:- `stremio:addon:{source-key}:{type}:{exact-id}`. `source-key` is a- domain-separated SHA-256 fingerprint of the persisted configured manifest- URL (preserving raw encoded path and query bytes), never a numeric playback- ID. This survives uninstall/reinstall of that- same configured addon without storing a credential-bearing URL in history;- do not log the fingerprint or configured URL. Different addon installs with- colliding custom IDs remain separate.-- Keep `catalogOrigin`, `metaOrigin`, and selected `streamOrigin` distinct.- Switching stream providers for a global ID preserves progress. A custom ID- stays scoped to its catalog origin even when another addon can answer the- same prefix.--Add an optional typed Stremio playback reference to `PlayerNavigationRequest`.-The player uses it to read/write addon progress through the Stremio history-repository; it does not fabricate numeric provider/content IDs. History replay-routes back through the Addons feature, resolves fresh metadata and streams, and-shows the picker unless a prior stream choice can be safely revalidated. For a-global IMDb ID, reinstalled/other eligible addons may provide fresh streams. For-a custom ID, try its origin first and keep the item unavailable until that-source is reinstalled if no eligible metadata/stream source can resolve it.-Keep an Addons-owned Continue Watching row in v1; integrating the existing-provider-only Watch Next/history surfaces is a later explicit project.--### AD-9: Resource routing across installed addons--Use a single `StremioResourceResolver` for meta, stream, and subtitle requests.-Its candidate input is the enabled installed-addon snapshot, resource kind,-Stremio type, exact requested ID, and optional preferred origin. Catalog-selection controls only which catalog rows are shown; disabling a catalog does-not suppress that addon's meta/stream/subtitle capability. A disabled addon is-never a candidate.--Match manifests using protocol filters, preserving missing versus explicitly-empty arrays in the parsed model. A string resource uses manifest-level `types`-and optional `idPrefixes`; an object resource uses its resource-level type-filter (falling back to manifest-level types only when omitted) and its own-optional `idPrefixes`. Omitted prefixes mean any ID; an explicitly empty prefix-list matches no IDs. `catalog` is routed only through the catalog declaration,-not by ID-prefix matching. Compare prefixes against the exact request ID.--For meta, query the eligible catalog-origin addon first, then remaining eligible-addons in installed order. Empty and failed responses fall through; cancellation-propagates. If no meta succeeds, keep the catalog preview usable. A movie may-still request streams using its item ID; a series without `videos` stays-preview-only and cannot invent episode IDs.--For streams and subtitles, fan out to eligible enabled addons with bounded-concurrency (maximum four in flight). Preserve installed order while merging-results, attach addon attribution to each row, expose partial errors/retry per-addon, and cancel the fan-out when item or screen scope changes. Apply-`idPrefixes` to the exact movie ID or exact episode `video.id`, never to the-parent series ID by assumption. Subtitle requests use the protocol's video ID-and carry available hash/size/filename separately.--### AD-10: Catalog page and cache contract--Preserve optional `hasMore` as nullable and retain raw response count before-filtering/deduplication. A catalog advertises `skip` before the UI offers-pagination. Request 100 raw items per page; when `hasMore` is absent, continue-only after a full raw page. When present, honor it, but guard against repeated-page fingerprints and impose a per-session page cap. Advance `skip` by raw-response count, not the number of renderable cards. Never paginate a catalog-without `skip`.--Required extras must be satisfied before making a request. V1 supports `search`,-`genre`, and `skip`; a required unknown extra disables that catalog row with a-clear unsupported-requirement message. Search-only catalogs wait for a nonblank-query. Reset pagination and stale-request ownership on query/filter changes.-Keep the P2 cache bounded to 200 pages with a five-minute TTL; key it by-configured-addon fingerprint, catalog type/id, normalized search/genre, and-skip. Invalidate affected entries on addon removal, manifest refresh, or catalog-setting changes.--## Phases--| Phase | Work item | Status | Exit criteria |-| --- | --- | --- | --- |-| P0 | Protocol client + models | Done | Domain models (manifest/catalog/meta/stream/subtitle), lenient DTO mapping, URL normalization (`stremio://` → https, configured paths, query preservation) and endpoint builders, `StremioAddonClient` with bounded responses and fixture-based tests — 22 tests passing (`StremioAddonClientTest`, `StremioAddonUrlTest`) |-| P1 | Persistence + addon manager | Implemented and verified | Room migration 78 → 79 (`stremio_addons`) with `MigrationTestHelper` coverage and schema export per `docs/DATABASE_MIGRATION_INVARIANTS.md`; add/remove/enable/reorder/catalog-select; configuration-required manifests rejected with a clear message; unit tests and emulator install smoke pass. Remaining release concerns are tracked in `docs/STREMIO_ADDONS_PLAN_REVIEW.md`. |-| P2 | Catalog browsing | Implemented and verified | Browse/Manage tabs with enabled per-addon catalog rows; nullable `hasMore`, raw-count 100-item pagination only when `skip` is advertised, required `search`/`genre` gating and unsupported-extra states, stale-request cancellation, refresh-aware bounded cache, loading/empty/error states, and visible D-pad focus on TV. Seven browse ViewModel tests pass; Cinemeta catalog fetch and TV card-focus smoke pass on API 36. |-| P3 | Meta + stream picker | Implemented and verified | Catalog cards open a detail page with provenance-first metadata fallback, preview-only behavior, exact episode IDs, attributed cross-addon stream rows, bounded partial fan-out and per-addon retry, visible unsupported stream kinds, and a typed player handoff. Focused domain, data, and feature tests plus app unit tests and debug assembly pass. API 36 TV smoke verified Cinemeta detail/provenance and the no-stream-provider state; it did not validate playback. |-| P4 | Playback integration | Implemented; fixture playback verified | Direct/debrid streams use the existing player preparation path with media headers scoped to playback requests; Room v80 stores Stremio progress without URLs or headers; resume/history reopening resolves fresh streams; magnet cast/playback states are explicit. Tests, MP4/history smoke, and all 45 migration instrumentation tests pass on isolated API 36, including 79→80. Synthetic HLS completed at 120 seconds over HTTP/1.1; HTTP/1.0 serving produced transient EOFs. Remote Mux HLS passed through the local Stremio fixture. On a clean dedicated API 36 AVD, a provider HLS fixture passed a 145-second advancing hold and 61 screenshots over 120.26 seconds (60 unique frames due to the fixture loop); progressive MP4 reached first frame. This is fixture VOD coverage. A real third-party addon HLS/DASH and child-resource smoke remains external qualification because no suitable public-domain addon was found. Same-origin scoped headers are applied by the playback policy, and cross-origin redirect removal is integration-tested. Cast rejects scoped addon headers but allows headerless direct streams; external-player handoff is outside v1. |-| P5 | Subtitles | Implemented; partial emulator verification | Inline and addon subtitles are carried to the player, addon resources load lazily, request extras include hash/size/filename, language codes map to Android locales, and external tracks use `PlayerEngine.addExternalSubtitle`. The CC picker remains available for Stremio subtitles even when the stream has no embedded text track. Tests/build and independent subtitle-only addon playback smoke pass. |-| P6 | Torrent companion plugin | Implementation complete; user acceptance pending | Host: validated `infoHash`/tracker/file-index conversion, scheme-owned plugin prepare, clear missing/unhandled plugin errors, loopback-only output validation, and best-effort `MSG_STOP_PLAYBACK`. Separate repo/APK: libtorrent engine, loopback HTTP range streaming server, `playbackUrlSchemes: ["magnet"]`, and configuration Activity with buffer/speed/status/stop/clear controls. Unit tests and debug build pass. User still needs to verify real torrent playback, seeking, replay, and teardown with a torrent-backed addon. |-| P7 | Required polish + optional integrations | Implemented; optional Home/global search deferred | Conservative parental gate is implemented, unit-tested, and smoke-tested on TV at Off/Locked/Private/Hidden; Private omits Stremio continue-watching from the aggregate. Extensions and the Plugins/Stremio Add-ons landing destinations are wired. README, handoff, plan review, changelog, and the user acceptance checklist document the feature and its limitations. Optional Home/global search remains deferred. |--Effort estimate: P0–P5 ≈ 5–6 weeks for a shippable direct/debrid v1; P6 adds-≈ 4–8 weeks (torrent engine quality on TV hardware is the dominant risk); P7-≈ 1–2 weeks. Total to full parity ≈ 2–4 months.--## Host change map--New module `feature:stremio` (add to `settings.gradle.kts`), following the-`feature/catalog` conventions:--- `feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/`- — AddonsScreen, AddonInstallDialog, AddonManagerScreen, StremioMetaScreen,- StremioStreamPickerScreen.-- `feature/stremio/.../api/` — ports consumed by `app` (navigation actions,- playback handoff), mirroring `feature/catalog/.../api`.--Data layer:--- `data/.../local/` — `stremio_addons` and `stremio_playback_history` entities,- Room version 80, migrations `78 → 79` and `79 → 80`, and schema exports.-- `data/.../stremio/` — `StremioAddonRepository`, `StremioCatalogClient` (HTTP),- response models, bounded cache.--Domain:--- `domain/.../model/` — addon, catalog, meta, stream, subtitle models (pure- Kotlin), plus `AppTopLevelDestination.ADDONS` / `AppLandingDestination.ADDONS`.--App wiring:--- `app/.../navigation/AppRouteCodec.kt`, `AppNavigationAdapters.kt`,- `StartupNavigationResolver.kt`, `AppNavHost.kt` (+ new graph registration),- `app/.../ui/components/shell/AppShellNavigation.kt`.-- `app/.../di/` — repository/client bindings.--Playback (small, surgical):--- `feature/playback/.../cast/CastMediaRequestFactory.kt` — magnet guard.-- `feature/playback/.../player/PlayerPreparationCoordinator.kt` — already routes- through plugin prepare (`:72`); verify non-http probe skip (`:193`) and that a- magnet that fails plugin resolution produces a user-facing error rather than an- engine start.-- `player/.../Media3PlayerEngine.kt` / `PlayerEngine.kt` — no changes expected for- P4; P5 uses `addExternalSubtitle`.--Plugin docs:--- `docs/PLUGIN_API.md` — appendix: torrent-style plugins declare- `playbackUrlSchemes: ["magnet"]`, must return loopback `output_url`, must never- expect host headers/credentials, and are non-castable.--## Companion torrent plugin (P6) — integration spec--Separate repository and APK (working name StreamVault Torrent Plugin). It uses the-existing plugin API; the host needs zero torrent-specific code.--- Manifest: `capabilities: ["playback.prepare", "configuration.activity"]`,- `playbackUrlSchemes: ["magnet"]`, no `playbackUrlHosts`,- `configurationMode: "activity"`.-- `MSG_PREPARE_PLAYBACK` with `input_url = magnet:?...` (or assembled from- `infoHash` + trackers):- 1. Start/attach a torrent session (foreground service, persistent notification).- 2. Prioritize the target file (respect `fileIdx` when present; otherwise largest- video file), streaming piece deadlines around the play head.- 3. Serve ranges on `http://127.0.0.1:<port>/stream/<token>`; return- `success=true`, `handled=true`, `output_url`, `stream_type=progressive`- (or `hls` if the plugin remuxes), and an `expirationTime`-like short-lived- token recommendation (host currently has no expiry field in the response —- acceptable; the URL stays valid while the session is alive).- 4. Return `success=false` with a user-facing `message` for magnets it cannot- resolve; the host then shows the plugin's message.-- Config Activity: download directory, buffer target, upload/speed caps, connected- peer/status view, active session list, stop/clear actions. TV-first layout per- the native Activity guidance in `docs/PLUGIN_API.md`.-- Security posture: loopback bind only, no LAN exposure by default, no telemetry,- session teardown when playback stops.-- Legal posture: engine and indexing live only in this separate APK/repo; the main- app references nothing torrent-specific in code, branding, or docs beyond the- plugin capability description.--## Testing and validation strategy--- P0–P1: pure unit tests for URL normalization, manifest validation, extra/query- encoding, response parsing (fixture JSON committed under test resources,- including malformed/unknown-field cases).-- P1: Room migration tests per `docs/DATABASE_MIGRATION_INVARIANTS.md`- (`StreamVaultDatabaseMigrationTest` adjacent hop + populated multi-hop origin),- schema JSON export committed, `PRAGMA foreign_key_check` on the new table.-- P2–P3: viewmodel/repository tests with a fake client; D-pad focus checks on- emulator for the new screens (TV-first).-- P4: emulator smoke confirmed direct MP4 playback and history/resume. The- synthetic HLS asset completed for 120 seconds over HTTP/1.1 on the same host- port; local HTTP/1.0 serving produced transient network EOFs. A remote Mux HLS- sample played through the local Stremio fixture for 61 screenshots at a- two-second cadence (61 unique hashes), with HLS prepare/first-frame logs and a- healthy session. A separate provider HLS fixture reached first frame and- advanced for 145 seconds; 61 screenshots over 120.26 seconds had 60 unique- hashes because the synthetic source loops at 120 seconds. Media session was- PLAYING with `error=null`; logs showed HLS playlist/segment reads without retry,- fatal error, stuck timeout, or MPEG-TS fallback. Progressive fixture MP4 also- reached first frame. This remains fixture VOD evidence. Verify a real- third-party addon endpoint and its redirect/header behavior before closing- that gate. Confirm magnet-without-plugin does not start the engine.-- P5: tests cover inline/addon subtitle conversion and external playback paths.- Emulator smoke confirmed inline English discovery and selected a German track- from an independent subtitle-only addon; its WebVTT cue rendered during playback.- Episode-switching subtitle isolation remains a regression check.-- P6: end-to-end on emulator with the torrent plugin APK: magnet → plugin prepare- → first frame; seek forward/back; plugin stop tears the session down; capture- log evidence analogous to the AGENTS.md live playback validation discipline- (screenshot cadence during the stream, player health, no unintended fallbacks).-- Regression: run existing migration suite and feature/catalog tests; verify no- changes to provider sync behavior.--## Risks and mitigations--| Risk | Impact | Mitigation |-| --- | --- | --- |-| Addon ecosystem drift (protocol variance, giant responses) | Broken browsing | Lenient parsing (ignore unknown fields), bounded page sizes/timeouts, per-addon error surfaces, fixture tests |-| Legal exposure for torrent support | Takedown/abuse reports | Engine only in separate plugin APK/repo; main repo has no torrent code; document posture |-| TV hardware limits for torrent streaming | Poor playback | Buffer/peer caps, file selection heuristics, clear errors; validate on 4K TV emulator and real device before calling P6 done |-| Room migration mistakes | Data loss | Follow `DATABASE_MIGRATION_INVARIANTS.md`; migration tests + schema export as a hard gate |-| Adult content via addon catalogs | Parental controls bypass | Treat all unrated Stremio content as protected; gate install, catalogs, details, playback, and history through the existing parental PIN policy; deny all at Hidden |-| Cast expectations | User confusion | Cast hidden for magnet; resolved loopback streams surface the existing `UNSUPPORTED` path with a clear message |-| Scope creep (config webviews, Home integration early) | Slips v1 | Phase gate: P0–P5 plus required P7 polish is direct/debrid v1; P6 torrents and optional Home/search integration are follow-ons |--## Resolved implementation decisions--- Stremio metadata has no dependable age-rating coverage, so the entire feature- is treated as protected: Off allows access, Locked/Private require a PIN once- per process session, and Hidden blocks the feature. Private omits the Stremio- continue-watching aggregate. Route gates prevent protected screens and their- requests from starting before unlock; view-model entry points fail closed.-- Unsupported YouTube/external stream kinds stay visible as disabled rows with a- reason.-- Subtitle language codes map through the existing player locale/preferences- path; no Stremio-specific preference was added.-- Catalog responses use a bounded in-memory cache; disk persistence is deferred- unless browsing performance requires it.-- V1 accepts copy/paste install links; `stremio://` intent registration is- optional.-- V1 rejects `configurationRequired` addons with a clear configure-in-browser- message.--## Deferred follow-ups--- V1 assumes configured addons return playable direct/debrid HTTP(S) URLs. In-app- debrid credentials and API-key UI are outside the current scope.-- Manifest refresh with last-known-good fallback, capability changes, and- catalog-setting reconciliation is post-v1 work.diff --git a/docs/STREMIO_ADDONS_PLAN_REVIEW.md b/docs/STREMIO_ADDONS_PLAN_REVIEW.mddeleted file mode 100644index bb55b4e7..00000000--- a/docs/STREMIO_ADDONS_PLAN_REVIEW.md+++ /dev/null@@ -1,315 +0,0 @@-# Stremio addons plan review--2026-10-14 acceptance correction: the blanket Stremio parental gate described-below is superseded. Stremio is open by default with a separate Settings →-Privacy → Hide Stremio Add-ons preference. The prior gate verification remains-historical evidence; use the revised acceptance checklist for current UX.--2026-10-14 acceptance correction: the blanket Stremio parental gate described-below is superseded. Stremio is open by default with a separate Settings →-Privacy → Hide Stremio Add-ons preference. The prior gate verification remains-historical evidence; use the revised acceptance checklist for current UX.--Reviewed 2026-10-11 in `.worktrees/stremio-addons`, branch-`feature/stremio-addons`, against the uncommitted implementation and the official-Stremio SDK protocol documentation. The review itself was a planning/code-inspection pass; subsequent verification results are recorded in-`STREMIO_ADDONS_HANDOFF.md`.--Design follow-up (2026-10-11): resource routing, catalog pagination, and-playback identity now have concrete decisions in implementation-plan AD-8-through AD-10. Those design gates are closed. AD-8 through AD-10 implementation-is now in place; the HLS and remaining release-check gaps are described in the-2026-10-12 update below.--P2 verification update (2026-10-11): AD-10 catalog browsing is implemented and-verified. The handoff records unit-test, build, and API 36 TV emulator evidence.-AD-9 resource routing, AD-8 playback history, and the release gates below were-still open at that review point; see the implementation updates below.--P3 verification update (2026-10-12): AD-9 resource routing and the meta/detail-stream picker are implemented and verified. Tests cover catalog-only,-stream-only, and subtitle-only capabilities, ID-prefix filtering, provenance-fallback, partial fan-out/retry, exact episode IDs, and cancellation. An isolated-API 36 TV smoke confirmed the Cinemeta detail page and no-stream-provider state;-it did not validate playback. P4 and P5 have since been implemented, with the-remaining smoke and release gates recorded below and in the handoff.--Implementation update (2026-10-12): P0–P5 are implemented. P4 adds direct-playback, scoped media headers, magnet guards, and URL-free Room progress at-database version 80. Synthetic MP4 playback and history/resume smoke passed. The-synthetic HLS VOD fixture raised transient `unexpected end of stream` errors over-local HTTP/1.0; the same asset completed over HTTP/1.1 on the same host port with-no error. A remote Mux Big Buck Bunny HLS sample then passed 61 screenshots at a-two-second cadence through the local Stremio fixture, with 61 unique frame hashes,-HLS prepare/first-frame logs, and a healthy media session. Confirm against a real-third-party addon endpoint and its redirect/header behavior before closing that gate.-P5 carries inline subtitles and lazily resolves addon subtitle resources; tests,-debug assembly, inline English discovery, and independent subtitle-only playback-smoke pass. On isolated API 36 `emulator-5556`, the fresh `tt7654327` item exposed-the German subtitle-only addon track, selection logged `addExternalSubtitle`, and-the WebVTT cue rendered while media session remained healthy. Direct/debrid v1 is-still gated on a real third-party addon HLS endpoint, the final header/privacy-review, and TV regression checks. The parental PIN gate was smoke-tested at all-four levels on isolated API 36 `emulator-5556` on 2026-10-13; details are below.--Provider-playback update (2026-10-13): on a new clean API 36 TV AVD, the local-V11 provider fixture played HLS through a 145-second health and position-advance-hold and progressive MP4 to first frame. The HLS capture used 61 screenshots at-two-second cadence over 120.26 seconds, with 60 unique hashes because the-synthetic VOD repeats after 120 seconds. During capture media session was-PLAYING with `error=null`; sanitized logs show HLS prepare, first frame, playlist-and segment reads, and no retry/fatal/stuck/MPEG-TS fallback. This closes the-provider-fixture regression check, not the real third-party-addon gate. A check-of the community Public Domain Foreign Movies addon found its manifest host-returns 404 and no `.m3u8` references in source; the official public-domain addon-returns torrents and Archive.org returns direct files. No suitable public-domain-HLS addon was found.--The host-native client, separate addon registry, dedicated Addons route, and-direct/debrid-first delivery are appropriate. The Plugins and Stremio Add-ons-routes are now grouped under one Extensions navigation destination with-focusable in-page tabs. Direct/debrid v1 implementation and local regression-checks are complete; the remaining items below identify external qualification-and the user's manual UI/usage acceptance pass.--## Required additions--### 1. Cross-addon resource routing (P2–P3, implemented and verified)--The plan describes picking from "the addon's" streams but does not define how a-catalog-only addon such as Cinemeta connects to stream-only and subtitle-only-addons. Add a resource resolver that queries enabled installed addons matching-resource, media type, and content/video ID. Honor global restrictions and-per-resource overrides, including `idPrefixes`; distinguish absent restrictions-from explicitly empty ones where the protocol requires it. The original-implementation only checked resource/type; P3 now preserves absent versus empty-filters and applies manifest/resource-level type and prefix rules to exact IDs.--Keep catalog origin as provenance. For metadata, define deterministic precedence-(origin first when eligible, then installed order), fallback after empty/failure,-and a useful preview-only state if no metadata provider is available. Never assume-Cinemeta is installed automatically. For streams/subtitles, use bounded concurrent-fan-out, preserve addon attribution/order, allow partial results and per-addon-retry, and cancel obsolete requests when leaving/changing the item. Disabling-catalog rows must not disable that addon's stream/subtitle resources.--Acceptance: browse a Cinemeta item and see streams from a separate stream-only-addon; one failing addon does not hide successful results; an unrelated ID prefix-is never queried; disabling an addon removes it from resource routing. These-cases are covered by domain/repository/feature tests; the TV smoke verified the-metadata detail and preview state, not real multi-addon playback.--### 2. Catalog capability and pagination semantics (P2, implemented and verified)--`StremioMapper` currently converts absent `hasMore` to `false`. The standard-catalog response does not require that field, so consuming this boolean directly-would stop many catalogs after page one. Preserve whether it was supplied, and-define the standard fallback: only paginate catalogs advertising `skip`; use-100-item pages/offsets and stop on a short page. Track raw response count before-filtering or deduplication so dropped cards do not change server offsets. Support-an explicit `hasMore` extension without creating an infinite repeated-page loop.--Honor required extras, including search-only catalogs and genre options; don't-request a default row when required inputs are missing. Decide which extra names-v1 supports and display a clear limitation for unknown required extras. Reset-pagination on query/filter changes, cancel stale searches, retain focus/scroll-when returning from details, and define bounded cache keys/TTL/invalidation.--Acceptance: a 100-item response without `hasMore` loads page two; a short page-ends pagination; repeated pages cannot cause endless fetching; required-search-catalogs receive requests only after search input exists.--### 3. Playback identity and history reopening (design before P3; implement P4)--AD-8's string key is not directly compatible with the existing pipeline:-`PlaybackHistory` and `PlayerHistoryCoordinator` require numeric `contentId` and-`providerId`. `PlaybackHistoryNavigation` replays a stored `streamUrl`, which can-expire for debrid media or refer to an old plugin loopback session.--Choose an explicit persistence/navigation integration: a dedicated addon progress-store or an extension of the existing identity model, with any required Room-migration. Do not invent a provider row or use an unchecked string hash as an ID.-Keep the exact video ID returned in `meta.videos`; do not synthesize all episode-IDs as `tt...:season:episode`. Keep parent series identity separately. Specify-whether custom addon IDs share a namespace; only merge identities when they-represent the same content. Reopening history must resolve fresh streams and-restore progress, with a picker when automatic selection is not reliable.--Acceptance: progress survives process death and addon reinstall; changing stream-providers retains position for the same video; expired URLs are resolved again;-two unrelated custom-ID addons cannot overwrite each other's progress.--### 4. Media headers and credentials (P1/P4, implemented; external HLS qualification open)--P4 implements origin-scoped selected-stream headers. The playback client avoids-shared interceptors/cookies/authentication state, applies credentials only to-the configured media origin, and strips them after a redirect to another host.-Addon URL parsing preserves encoded path bytes, and playback diagnostics redact-private origins and paths. Tests cover origin matching and sanitization.--The local MockWebServer test confirms a cross-origin 302 removes Authorization;-the playback client also isolates cookies, authenticators, and cache. Every HLS-or DASH child request uses the same origin-scoped media policy. Credential-policy: configured manifest URLs remain in app-private Room; do not log, back up,-or manually export addon records; show only the server origin in Manage; Remove-deletes the active addon row, while disabling retains it. Room is not app-level-encrypted and relies on the Android app sandbox and device storage encryption.-Stremio streams with scoped headers are rejected by casting; headerless direct-streams can use the normal cast path. External-player handoff is outside v1-because it cannot preserve the header scope. The public-domain addons checked-did not provide a suitable HLS/DASH endpoint, so real-addon child-resource-playback remains external qualification rather than a local implementation gap.-The app's network security configuration allows HTTP for media sources.--Acceptance: encoded configuration paths round-trip; a header-dependent stream-plays without credentials leaking to unrelated hosts; sanitized diagnostics-contain no configured URL secrets. Unit and MockWebServer redirect coverage pass.-A suitable real addon remains needed to confirm end-to-end HLS/DASH child-requests with its own manifest and media URLs.--### 5. P1 completeness and manifest lifecycle--Resolved P1 finding: `StremioAddonRepositoryImpl.installAddon` rejects-`configurationRequired` manifests with a configure-in-browser/paste-configured-URL-message, and the configured install URL is the registry identity.--Manifest refresh with last-known-good fallback, version/capability changes, and-catalog-selection reconciliation remains a post-v1 follow-up. Document validation-boundaries for malformed or unusable manifests while retaining valid stream-only-and subtitle-only addons. V1 supports copy/paste install links; OS `stremio://`-intent registration remains optional. Keep the manager separate from catalog-browsing within the Addons destination.--The compile failure recorded in `stremio-test-run2.log`-(`AddonsViewModelTest.kt:157` could not resolve `StremioManifestResource`) is-historical; the import was fixed and the current Stremio/app tests and debug build-pass. Emulator smoke confirmed addon installation. Repository/ViewModel tests-cover duplicate and configuration-required installs, enable/disable, reorder,-catalog selection, and removal. The manual acceptance pass should confirm-retention after app restart and D-pad focus through the manager.--### 6. Torrent plugin contract feasibility (design spike before P6)--Existing IPC can route `magnet:` but the claim that the plugin needs no host-contract work is premature:--- `MSG_PREPARE_PLAYBACK` sends only `input_url`. Specify a documented URI encoding- for `fileIdx` and tracker sources, or version an IPC field; prove the plugin- selects the requested episode file. Normalize `tracker:` source prefixes and- define DHT handling rather than passing source strings blindly as magnet trackers.-- Preparation currently has both a five-second handler deadline and a five-second- total deadline. Timeout/no handler returns the original stream. A cold torrent- may exceed this: choose fast loopback endpoint allocation with asynchronous- buffering, or a bounded readiness/progress contract. Reject unresolved magnet- output before engine start, including plugin failure, timeout, disabled state,- and a nominal success response lacking usable output.-- There is no playback-session stop signal in the documented IPC. Define session- ownership, cancellation, cleanup on switch/back/process death, inactivity expiry,- and seek/range behavior; an HTTP disconnect alone is not a reliable stop signal.--Keep torrent provenance after resolution. AD-6's possible loopback cast rewrite-conflicts with the stated non-goal of torrent casting: block cast for the whole-torrent-backed session, including resolved URLs. Decide external-player support-separately, since handoff changes session ownership. A separate APK does not itself-settle distribution or licensing requirements; review those when choosing an engine.--Acceptance: file-index preservation, cold-start beyond five seconds, cancellation,-plugin death, seek/range requests, and cleanup all work using a deterministic-fixture before a real-network end-to-end trial.--### 7. Subtitle coverage (P5)--Implemented: inline `stream.subtitles` and enabled subtitle-resource addons are-carried to playback. Requests include the exact video ID and available-`videoHash`, `videoSize`, and `filename` extras. Results are deduplicated with-provenance, three-letter language codes are mapped, and external tracks use the-existing player path and preferences. The subtitle picker appears when Stremio-sources exist even if no embedded text track is present. Focused tests/build and-the inline English picker smoke pass. An isolated API 36 TV smoke selected a-German track from an independent subtitle-only fixture and rendered its WebVTT-cue over playback.--Remaining acceptance: verify that switching episodes cannot retain the previous-subtitle request/result.--### 8. Parental controls and content-type scope (before v1 release)--The parental-control decision is now implemented ahead of v1. Addon catalogs-and metadata do not provide dependable age ratings, so all Stremio content is-treated as protected: Off allows access, Locked and Private require the existing-PIN once per app session, and Hidden blocks the feature, including installation.-Both browse and item routes are gated before screen construction/network fetches;-install, catalog, metadata, and stream actions also fail closed. Private omits-Stremio continue-watching from the aggregate surface. Feature tests cover each-level and blocked install/catalog/detail requests. The isolated API 36 TV smoke-verified Hidden denial, Locked/Private PIN prompts, wrong-PIN rejection, valid-unlock, re-lock after a level change, and Off access without a PIN; the original-emulator preferences were restored and hash-verified. This release gate is-closed.--Explicitly define v1 as movie/series playback, with `tv`/`channel` browsing or-playback deferred unless separately implemented. The current model recognizes-these types, while the plan's playback/resume design assumes VOD. Newer guide and-archive-source capabilities remain unsupported v1 states; preserve a visible-unsupported row rather than silently dropping identifiable stream kinds.--### 9. Release validation and documentation (P4–P5 release gate)--Add a deterministic multi-addon fixture setup covering catalog-only, stream-only,-subtitle-only, custom episode IDs, missing `hasMore`, required extras, redirects,-headers, unsupported stream kinds, cancellation, partial failures, and expiring-URLs. Use legitimate direct MP4 and HLS media; exercise seek, resume after restart,-audio/subtitle selection, TV focus restoration, and existing provider playback.--First frame/build/install alone are not playback acceptance. The provider-fixture now covers a 145-second advancing HLS playback window and progressive-first frame; real addon HLS/DASH and child-resource behavior remains open. Capture-progression and sanitized player logs across a meaningful playback window. If live addon-playback is added, follow AGENTS.md exactly: at least 45 screenshots at two-second-intervals (prefer 61 for prior one-minute failures), healthy media session, no-fatal/stuck/unintended fallback, and multiple channels for general live bugs.-Do not claim live validation from the VOD fixture runs.--Separate mandatory v1 polish/documentation from optional Home/search integration-and P6 torrent work. Revise the schedule after identity and plugin spikes; the-original estimates do not account for these unresolved integration contracts.--## Recommended continuation order--1. P1 registry/configuration, verification, and commit are complete; results- are in the handoff.-2. P2 catalog browsing against AD-10 is implemented and verified; results are- recorded in the handoff.-3. P3 cross-addon routing and the detail/stream picker against AD-9 are complete- and verified; results are recorded in the handoff. P4/P5 are implemented, and- the direct MP4/history and independent subtitle-addon smoke checks passed.-4. Parental PIN TV smoke at Off, Locked, Private, and Hidden is complete. D-pad- navigation through Extensions and its Plugins/Stremio Add-ons tabs also- passes. No suitable public-domain third-party HLS addon was found: the- official Public Domain Movies addon returns torrent hashes, while the- maintained Archive.org addon returns direct file URLs and its published host- no longer resolves. The community Public Domain Foreign Movies endpoint also- returns 404 and its source has no HLS playlist references. Keep the real-addon- HLS gate open; neither local fixture smoke satisfies that gate.-5. Provider playback passes with a dedicated fixture. Direct/debrid v1 code and- local regression gates are complete. A real third-party addon HLS/DASH and- child-resource smoke remains external qualification because the public-domain- candidates checked so far do not provide usable HLS. Same-origin headers are- scoped in the player request policy and the cross-origin redirect integration- test confirms credentials are removed. Casting rejects streams with scoped- addon headers and allows headerless direct streams. External-player handoff- is outside v1.- The install-URL secret storage, backup/export, Manage display, and removal- policy is documented in the handoff and enforced by the origin-only row.-6. Keep the P6 torrent-plugin feasibility spike deferred until the direct/debrid- user acceptance pass is reviewed. Home/global search remains optional after- v1.--## Primary protocol references--- [Resource routing and cross-addon IDs](https://github.com/Stremio/stremio-addon-sdk/blob/master/docs/protocol.md)-- [Manifest resources, required extras, and adult/configuration hints](https://github.com/Stremio/stremio-addon-sdk/blob/master/docs/api/responses/manifest.md)-- [Catalog pagination](https://github.com/Stremio/stremio-addon-sdk/blob/master/docs/api/requests/defineCatalogHandler.md)-- [Stream headers, file indices, tracker sources, and inline subtitles](https://github.com/Stremio/stremio-addon-sdk/blob/master/docs/api/responses/stream.md)-- [Subtitle request extras](https://github.com/Stremio/stremio-addon-sdk/blob/master/docs/api/requests/defineSubtitlesHandler.md)diff --git a/docs/STREMIO_TORRENT_P6_ACCEPTANCE.md b/docs/STREMIO_TORRENT_P6_ACCEPTANCE.mddeleted file mode 100644index 9fa2bbaa..00000000--- a/docs/STREMIO_TORRENT_P6_ACCEPTANCE.md+++ /dev/null@@ -1,56 +0,0 @@-# Stremio torrent playback — P6 acceptance--The companion implementation and debug APK are ready for manual testing. This-pass belongs to the user; no real torrent playback has been performed by the-build workflow. Cinemeta is catalog/metadata only, so test with an installed-Stremio addon that actually returns torrent streams.--The host app was rebuilt from the current Stremio worktree as-`1.0.19-debug`. If your installed host predates this handoff, update it from:--`D:\antigravity-scratch\iptv-player\.worktrees\stremio-addons\app\build\outputs\apk\debug\app-debug.apk`--Then install the companion from StreamVault → Extensions → Plugins → Install-plugin APK, using:--`D:\antigravity-scratch\streamvault-torrent-plugin\app\build\outputs\apk\debug\app-debug.apk`--The companion is `0.1.0-debug`; its SHA-256 is-`F3908E11E1DECB38F2589AEE8F33F164E7722FEDBFAC488F83D512B627588C06`.--Enable **StreamVault Torrent** in Plugins. Open its configuration Activity to-confirm the service is ready. Keep the host app and companion APK versions noted-when reporting results.--## Playback--- [ ] Open a movie with a torrent stream, select it, and confirm playback starts- without exposing the magnet URI to the media player.-- [ ] Seek forward and back. Confirm playback continues and the selected title- remains usable.-- [ ] Stop playback, reopen the same torrent, and confirm it can start again.-- [ ] Open the plugin configuration while playing and confirm status shows the- active file, peers, and transfer rates.-- [ ] Stop playback and confirm the session disappears from status shortly after- the host sends its stop message.-- [ ] Use **Stop all torrent sessions** and confirm playback stops and status- returns to ready.-- [ ] Disable the plugin and select a torrent stream. Confirm StreamVault gives- a clear disabled or missing-plugin message and does not start the magnet in- the media player. Re-enable the plugin afterward if desired.--## Configuration and cleanup--- [ ] Change the buffer target and download/upload caps; confirm the displayed- values persist after leaving and reopening the configuration Activity.-- [ ] If the device has removable app-private storage, choose it and confirm a- new session can use it. Otherwise verify the default private app storage.-- [ ] Clear downloaded torrent data while idle and confirm the action succeeds.-- [ ] Confirm the stream server remains local to the device and is not reachable- from another device on the network.--If a multi-file torrent is available, also verify a stream with `fileIdx` selects-that file and a stream without an index chooses the largest supported video.-Record addon name, title, device/AVD, first-frame result, seek result, stop/replay-result, and any error shown. Redact magnet hashes, tracker URLs, and account or-authorization data from screenshots and logs.diff --git a/docs/STREMIO_UX_AND_FUNCTIONALITY_PLAN.md b/docs/STREMIO_UX_AND_FUNCTIONALITY_PLAN.mddeleted file mode 100644index 34ed61d5..00000000--- a/docs/STREMIO_UX_AND_FUNCTIONALITY_PLAN.md+++ /dev/null@@ -1,334 +0,0 @@-# Stremio and Extensions UX and functionality improvement plan--- Date: 2026-10-16.-- Status: Implementation checks are complete, including plugin Messenger request/reply coverage. Debug APK is installed on the requested emulator; configured-emulator UX and real-torrent acceptance remain pending.-- Reviewed baseline: `f1ac7d3d` on `feature/stremio-addons`.-- Worktree: `D:\antigravity-scratch\iptv-player\.worktrees\stremio-addons`.--## Purpose and scope--Bring Stremio browsing and both Extensions management sections up to the app's-current layout and behavior standard. Preserve the existing theme and colors,-correct the integration defects found after merging develop and modern visuals,-and make navigation with a TV remote predictable.--This plan reconciles the five agreed UI directions with the subsequent code-review. It supplements the original Stremio implementation plan and handoff;-historical verification in those documents is not proof that the merged-baseline passes the new acceptance criteria below.--## The five agreed UI decisions--| Decision | Resulting behavior | Review issues addressed |-| --- | --- | --- |-| 1. Keep installation and management in Extensions | Once add-ons exist, show a compact heading with installed count and an Add button. Use the larger introduction only for an empty installation. | The current hero and repeated headings consume most of the viewport. |-| 2. Give browsing a dedicated content screen | Browse opens a full content page using the Movies/Series visual language. Back returns to Extensions management. | Browsing is currently nested below Extensions tabs, a large introduction, and another tab row. |-| 3. Make installed add-ons compact rows | Show logo, name, enabled switch, and capability badges. Open details for version, server origin, catalog settings, refresh, ordering, and removal. | Large management cards expose infrequent controls and do not explain what each add-on supplies. |-| 4. Make browsing content-first | Use a compact catalog/type/filter/search toolbar and a poster grid consistent with Movies/Series. | Long genre-chip strips, per-catalog search fields, and repeated panels push posters below the fold. |-| 5. Use one main vertical content scroller per screen | Management uses a list; browsing uses a grid. Give selected state and current remote focus distinct appearances. | Content is squeezed into a small scrolling region, and focus can be confused with tab selection. |--A short toolbar may remain above the scroller. It must leave room for complete-poster cards and titles on the target TV viewport. Filters and add-on details-can use compact dialogs or sheets with their own bounded scrolling when needed.--## Review findings--The findings below are based on source inspection and existing unit tests.-The torrent and legacy-upgrade failures were traced in code, not reproduced-through a real torrent session or an emulator database upgrade during this review.--| ID | Priority | Finding and effect | Implementation evidence |-| --- | --- | --- | --- |-| R1 | P1 | Torrent handoff applies HTTP header validation to the original magnet URL. This rejects a valid plugin-resolved torrent and can mask the useful missing-plugin error. | `feature/playback/.../player/PlayerViewModel.kt`, header validation after stream resolution; `domain/.../stremio/StremioMediaRequestHeaders.kt`. |-| R2 | P1 | Earlier Stremio and develop schemas independently used versions 79-80. The earlier Stremio v80 lacks the merged Xtream receipt columns and corrected episode index. The current upgrade chain does not repair those differences. Upgrading that schema can fail final Room validation. | Historical schema at `2d275bc1`; current `FeatureMigrationsV78To79.kt`, `FeatureMigrationsV79To80.kt`, and `FeatureMigrationsV82To83.kt`. |-| R3 | P1 UX | The large hero and two navigation layers sit outside the content scroller. Management controls and browse posters are pushed into the bottom of the screen. | `feature/stremio/.../presentation/AddonsScreen.kt`. |-| R4 | P1 UX | Catalog search uses a normal editable text field with no separate navigation-focus and editing states. | `StremioCatalogBrowseContent.kt`; the existing shared `SearchInput.kt` already supports click/select activation. |-| R5 | P1 UX | Episode sources are appended after the full episode list. Selecting an early episode in a long series can leave its sources far offscreen. | `StremioItemDetailContent.kt`, episode items before the streams section. |-| R6 | P2 | Player Back explicitly targets the add-on root, skipping title details. Browse lacks deliberate restoration of the focused poster. | `feature/stremio/.../navigation/StremioGraph.kt`; Stremio browse composables. |-| R7 | P2 | All eligible catalog rows start loading, including offscreen rows. Stream resolution waits for all providers before publishing usable results. | `StremioCatalogBrowseViewModel.refreshRows`; `StremioResourceResolver.resolveMany` uses `awaitAll`. |-| R8 | P2 | Retry after a pagination failure resets the query to page one, clears loaded items, and can serve the first page from cache. It does not retry the failed offset. | `StremioCatalogBrowseViewModel.retry`, request reset, and page-cache lookup. |-| R9 | P2 | Removal is immediate, manifest refresh is absent, and add-ons without catalogs still expose a Catalogs action. | `AddonsScreen`, `AddonsViewModel`, and `StremioAddonRepositoryImpl`. |-| R10 | P2 | Some unexpected repository failures lack cleanup of loading state; some detail exceptions are swallowed and can appear as an empty/no-provider result. | Install/management operations in `AddonsViewModel`; exception paths in `StremioItemDetailViewModel`. |-| R11 | P1 UX | The Plugins page also spends a fixed header area on the Extensions tabs, a title/description, and an install panel before the installed-plugin list. The install panel remains visible after setup, while the list is confined to the remaining viewport. | `feature/system/.../presentation/plugins/PluginsScreen.kt`; `PluginsContent` and `PluginInstallPanel`. |-| R12 | P2 UX | Plugin rows repeat enabled state as both a status pill and switch, expose package/version details in the main row, and configuration keeps the Plugins/Stremio tabs above a full-page form. | `PluginsScreen.kt`; `PluginCard`, `PluginConfigurationPanel`, and `ExtensionsSectionTabs`. |--### Requirements clarified by the existing handoff--- **Visibility is an agreed product choice:** Stremio remains open by default,- controlled by the separate Settings > Privacy > Hide Stremio Add-ons option.- The historical handoff records that this is independent of global parental- levels, and existing tests enforce it. The review initially raised this as an- open question; this plan preserves the recorded choice. A different adult- category policy would require new user direction.-- **Upgrade-origin scope needs explicit verification:** the database invariants- document excludes some discarded version-79/80 branch schemas. Establish- whether that exclusion covers the earlier Stremio schemas before applying it- to them. Identify actual supported Stremio upgrade origins and preserve their- data. Do not infer that an earlier installed Stremio database has no users.-- **User acceptance remains user-owned:** the existing handoff reserves manual- UI/UX and real-torrent acceptance for the user. Agent verification covers code- tests and builds; install the requested build on the designated emulator for- the user's acceptance pass.--## Intended user experience--### Extensions navigation and Plugins--- Keep Extensions as a full-screen app destination in the existing app shell.- The current Plugins and Stremio routes already work this way; selecting- Extensions should continue to open a normal destination with the app's- navigation shell, not a drop-down attached to the top navigation bar.-- Keep a compact, clearly selected **Plugins | Stremio-compatible Add-ons**- section switcher near the page title. Both are substantial destinations, and- visible tabs make the alternate section discoverable and easy to reach with a- TV remote. Avoid adding a second large navigation strip.-- When plugins are installed, replace the introductory title/description and- permanent install panel with a compact **Plugins · N installed** header,- **Add plugin** action, and refresh action. **Add plugin** offers install from- URL or APK. Keep explanatory copy and both install choices in the empty state.-- Make the installed-plugin list the main vertical scroller. Use compact rows- with plugin name, capability badges, one enabled switch, and Configure when- supported. Move package name, version, and less-used diagnostics into plugin- details/configuration so they do not dominate the list.-- Treat configuration as a nested full-screen page within Extensions. Replace- the section tabs with a clear Back-to-Plugins header, plugin name, and Save /- Refresh actions while the form is open. Keep the form itself as one bounded- vertical scroller and preserve draft values and focus on recoverable errors.-- Preserve visible focus and selected-tab styling, a useful empty state, local- APK picking, URL installation, refresh, enable/disable, and manifest-declared- capability badges. Do not conflate the Android companion-plugin install path- with Stremio manifest URL installation.--### Extensions management--- Keep the Plugins/Stremio section selector in Extensions.-- With installed add-ons, replace the hero with a compact header such as- **Stremio add-ons · 2 installed**, plus **Add add-on** and **Browse** actions.-- Each compact row shows logo or fallback, name, enabled switch, and declared- capabilities: Catalogs, Streams, and/or Subtitles. Capability labels come- from the manifest, rather than catalog count alone.-- Selecting a row opens add-on details. Expose catalog toggles only when the- add-on has catalogs. Offer refresh, ordering, server origin/version, and- removal confirmation there.-- Preserve the install dialog's content-sized height. Show installation errors- within the dialog, retain the entered URL after a recoverable error, and- prevent duplicate submissions.-- Explain streams-only and subtitles-only add-ons. An enabled streams-only- add-on can supply sources for compatible titles from another catalog.-- Distinguish no installed add-ons, no enabled add-ons, and no enabled catalogs;- provide an appropriate next action for each state.--### Dedicated browsing--- Keep the app shell and a short page toolbar; remove the management hero and- Extensions sub-navigation from this content page.-- Select an available catalog using a compact picker showing catalog name and- supplying add-on. Offer Movies/Series selection when relevant to the available- catalogs. Do not imply that an arbitrary type filter is supported by an add-on.-- Show only filters declared by the selected catalog. Use a compact genre picker- rather than an unbounded strip of chips. Explain unsupported required filters.-- Search applies to the selected catalog and appears only when that catalog- supports it. Search-required catalogs wait for a query and show a clear prompt.-- Reuse the shared search control: D-pad focus only highlights it; click/OK- opens editing and the keyboard. Back exits editing and restores control focus;- Search/Done closes editing and moves to results. Preserve the query when the- keyboard closes. Mouse activation must also work.-- Keep debouncing and stale-request cancellation. Preserve existing results- while a replacement query loads, with a clear loading indication. Do not label- old results as the new query's results.-- Reuse the Movies/Series poster proportions, title treatment, spacing, focus- behavior, and responsive grid sizing. Missing images have a stable fallback.-- Load the selected catalog and subsequent pages on demand, with bounded- concurrency and memory. Keep any prefetch deliberate and limited.-- Retain catalog, filters, query, loaded pages, scroll position, and focused item- when returning from details. If an item disappears, restore focus to a nearby- valid item or the relevant control.-- Place Continue Watching in the browsing experience without adding another- permanent header layer. Preserve exact playback identity and resume behavior.--### Title, episode, sources, and player--- Use a compact season/episode selection flow for series. Selecting an episode- immediately opens its source picker; sources do not sit below the episode list.-- Show the exact title/episode being resolved. Publish successful source results- as providers complete while showing which providers are still loading.-- Preserve configured provider ordering and source attribution even when results- arrive out of order. Keep successful sources available beside provider errors.-- Preserve useful source name/title/description fields and show a clear reason- when a source kind is unsupported.-- For torrents, check plugin availability before playback. Offer a clear route- to plugin management when unavailable. Preserve plugin resolution errors and- validate the plugin's resulting playable stream through the existing policy.-- Scope add-on HTTP headers to direct HTTP media; preserve the torrent plugin's- resolved-stream behavior. Cover both successful and unsuccessful handoffs.-- Expected Back flow: **Player > Sources/Title > Browse > Extensions management**.- Retain the chosen episode, source selection, and browse focus as appropriate.-- Preserve current history/resume, inline and add-on subtitles, and direct-stream- header behavior throughout the navigation changes.--## Implementation sequence and completion gates--### Phase 1 - Correct playback and upgrade compatibility--Addresses R1-R2.--- [x] Repair magnet handoff without applying the direct-HTTP header requirement- to the original magnet URI; preserve meaningful plugin failures.-- [x] Audit supported upgrade origins against the historical Stremio and develop- schemas, including the episode index and four Xtream receipt columns.-- [x] Add an appropriate forward compatibility migration for supported legacy- variants and the already-installed current schema. Follow the database- invariants, export the final schema, and preserve providers, add-on settings,- recordings, and playback history.-- [x] Cover direct HTTP header scoping, invalid headers, unavailable torrent- capability, explicit magnet plugin routing, safe/unsafe loopback output, and- populated supported upgrade origins.-- [x] Exercise the Android Messenger bind/request/reply/unbind path for both a- handler-reported failure and successful magnet preparation response.--Gate: targeted playback tests pass, supported database upgrades validate the-final Room schema and foreign keys, and a current debug APK builds.--### Phase 2 - Split navigation and compact management--Addresses UI decisions 1-3 and 5; R3, R6, R9, R11, and R12.--- [x] Separate management and dedicated browse routes with explicit Back targets.-- [x] Replace the installed-state hero with the compact header and add-on rows.-- [x] Apply the same compact installed-state hierarchy to Plugins: put URL/APK- installation behind Add plugin, retain refresh, and make its list the primary- vertical content area.-- [x] Keep Extensions as a full-screen shell destination with compact section- tabs; make plugin configuration a nested page with a Back-to-Plugins header- and no duplicate section tabs.-- [x] Add capability-aware details, catalog settings, ordering, and removal- confirmation. Make repeated actions safe.-- [x] Implement explicit remote-focus restoration after a row is reordered or- removed, with a fallback target if the operation fails.-- [ ] Verify reorder and removal focus on a configured TV emulator. The current- `emulator-5558` install opens first-run provider setup and has no add-ons to- exercise those actions.-- [x] Add manifest refresh preserving install identity, enabled state, catalog- choices, ordering, and history. Keep the saved manifest if refresh fails.- Invalidate affected browse data after successful refresh.-- [x] Preserve the larger empty-install introduction and compact install dialog.--Gate: management state/action tests pass; the user can inspect the refreshed-management screen and its empty, disabled, and streams-only states.--### Phase 3 - Build full browsing and explicit search activation--Addresses UI decisions 2, 4, and 5; R3-R4 and the catalog portion of R7-R8.--- [x] Use the established browsing grid/components with a compact toolbar.-- [x] Implement capability-aware catalog selection, search, and filter pickers.-- [x] Use shared click/OK-to-edit search and retain the draft/query on exit.-- [x] Fetch the selected catalog on demand and cancel obsolete work.-- [x] Preserve results during replacement requests and show distinct loading,- empty, required-input, unsupported, and failed states.-- [x] Retry a failed page at its original offset while retaining prior pages.- Distinguish retry from an explicit refresh; refresh must bypass stale cache.-- [x] Restore grid position and focus after returning from details.--Gate: request/state regressions pass; user acceptance confirms complete poster-cards and titles are visible on entry and D-pad focus never opens the keyboard.--### Phase 4 - Fix episode/source flow and contextual Back navigation--Addresses R5-R7 and the playback-facing portion of R1.--- [x] Add season/episode selection and an immediate source picker.-- [x] Publish provider outcomes progressively with stable attribution/order.-- [x] Preserve successful sources on partial failure and retry only the failed- provider. Cancel stale episode lookups.-- [x] Add torrent capability feedback and clear unsupported-source behavior.- Check enabled magnet-capable plugins before enabling Play, and offer Plugins- when none is available.-- [x] Return from the player to the selected title/episode context, then restore- the browse catalog, query, filters, position, and focused poster on Back.-- [x] Cover exact history replay/resume identity, scoped playback handoff,- inline subtitle handoff, and inline/add-on subtitle picker behavior.--Gate: exact-episode, cancellation, partial-failure, player-return, history, and-subtitle tests pass; user acceptance covers a long series and multiple providers.--### Phase 5 - Harden operation states and complete acceptance--Addresses R8-R10 and verifies all five UI decisions.--- [x] Ensure install, refresh, toggles, ordering, removal, metadata, catalog, and- source operations handle expected/unexpected errors and clear loading state.-- [x] Separate an actual empty result, no eligible provider, unsupported resource,- and request failure. Keep retry actions tied to the failed operation.-- [x] When the selected add-on/catalog is disabled or removed, select another- available catalog and show a useful explanation; cover disable/removal cases- in browse state tests.-- [x] Classify and back up the Hide Stremio Add-ons preference as a portable- global setting. The full data suite caught the missing classification and- import/export mapping; a restore regression now covers it.-- [x] Retain URL/token sanitization in UI errors, logs, and stored history.-- [x] Obtain clean runs of the relevant Stremio, playback, app, and data unit- suites; build and install the debug APK on the requested emulator.-- [x] Record implementation verification separately from user UI and- real-playback acceptance; those acceptance items remain open until inspected- on a configured emulator and a real stream is exercised.--Gate: required code checks pass and user-owned acceptance results are recorded.--## Verification baseline and acceptance matrix--The review baseline ran 107 existing tests with no failures: 30 Stremio-feature/state, 17 Stremio domain, 48 Stremio data, and 12 targeted playback-tests. Implementation verification passed `:feature:stremio:testDebugUnitTest`,-`:feature:playback:testDebugUnitTest`, `:app:testDebugUnitTest`, and the full-`:data:testDebugUnitTest` suite. The first full data run exposed an-unclassified `hide_stremio_addons` preference; the registry and backup-import/export mappings were fixed, and the full suite then passed. The debug APK-`1.0.19-debug` built and installed on `emulator-5558`. That emulator is currently-at first-run provider setup, so add-on management focus could not be exercised-there. `PluginMessengerClientTest` now exercises the Messenger round trip for a-reported handler failure and a successful magnet preparation reply, including-request metadata and service unbinding. These checks do not establish visual-quality or real torrent playback.--| Area | Required evidence after implementation |-| --- | --- |-| Management layout | User inspects compact Stremio add-on and companion-plugin rows, empty and installed states, install error/retry, refresh, configuration, reorder, disable, and removal confirmation. |-| Extensions navigation | User confirms Extensions opens as a full-screen app destination, the compact section switcher is easy to reach with a remote, and plugin configuration has a clear nested Back path. |-| Browse layout | User inspects complete posters/titles, long catalogs, filters, missing artwork, and Continue Watching on the target viewport. |-| Search interaction | Focus causes no keyboard; click/OK opens editing; Back preserves text and control focus; Search/Done closes editing and reaches results. |-| Catalog requests | Tests cover selected-only loading, required/unsupported extras, stale-response cancellation, page retry retaining previous items, and explicit refresh/cache behavior. |-| Sources and series | Tests cover exact episode IDs, long episode lists, progressive providers, partial failures, retry, and rapid episode changes; user verifies the source-picker flow. |-| Navigation | User verifies player-to-title-to-browse Back behavior and retained selection, filters, scroll, and focus; automated state/navigation checks cover the same contracts where practical. |-| Playback and subtitles | Tests cover direct HTTP headers, invalid headers, magnet capability/routing/output policy, Messenger handler failure/success replies, handoff headers, resume identity, and inline/add-on subtitles. Real stream/torrent acceptance remains open. |-| Database upgrade | Migration tests use populated supported historical variants and verify final schema, episode uniqueness, Xtream columns, preserved data, and foreign keys. |-| Visibility | Tests retain independent Hide Stremio Add-ons behavior and prevent content access through hidden Stremio routes. |--If a live-TV regression is investigated while shared player code is changed,-follow `AGENTS.md`: sustained two-second screenshot cadence, frame hashes,-healthy media-session state, sanitized log evidence, and multiple channels when-the issue affects live TV generally. A build, install, or single screenshot is-not evidence that a live-playback regression is resolved.--## Existing behavior to preserve--- Theme palettes, colors, and the shared browse visual system.-- Full-screen Extensions destination in the app shell and separate companion APK versus Stremio manifest install flows.-- Exact episode IDs, resource capability/prefix routing, and catalog provenance.-- Cancellation and protection from stale catalog/episode responses.-- Successful providers remaining usable alongside failed providers.-- Configured install identities and URL-free playback history.-- Resume behavior and inline/add-on subtitle support.-- Scoped direct-media headers and configured-URL sanitization.-- Separate Stremio visibility preference and the user's ownership of acceptance.--## Related project records--- `docs/STREMIO_ADDONS_IMPLEMENTATION_PLAN.md`-- `docs/STREMIO_ADDONS_PLAN_REVIEW.md`-- `docs/STREMIO_ADDONS_HANDOFF.md`-- `docs/STREMIO_ADDONS_ACCEPTANCE_CHECKLIST.md`-- `docs/STREMIO_TORRENT_P6_ACCEPTANCE.md`-- `docs/UI_VISUAL_SYSTEM.md`-- `docs/DATABASE_MIGRATION_INVARIANTS.md`-- `AGENTS.md`diff --git a/docs/Sports-IMPLEMENTATION.md b/docs/Sports-IMPLEMENTATION.mddeleted file mode 100644index 7250f6db..00000000--- a/docs/Sports-IMPLEMENTATION.md+++ /dev/null@@ -1,285 +0,0 @@-# Sports Hub v1 — Integration Map--**Updated:** 2026-10-17 — canonical league modeling and EFL guide regression verification.--## Existing integration points--- EPG programmes are exposed as `Program` through `EpgRepository`.-- `EpgRepository.getResolvedProgramsForChannels` applies StreamVault's existing- EPG-to-channel mapping and returns programs keyed by the mapped stream ID or- EPG channel ID.-- `ChannelRepository` and `CombinedM3uRepository` expose playable channels for- the active provider or combined M3U profile.-- Live playback already crosses the feature boundary through- `LiveChannelPlaybackRequest` and the app's existing player mapper.-- The app shell derives its top-level navigation from- `AppTopLevelDestination`; TV browse colors and focus behavior live in- `:core:ui`.--## Current implementation--- Added Sports as a top-level app destination and a route owned by `:feature:live`.-- Read EPG time windows for channels in the active live source, classify- competitive sports programmes from title, description, genre/category, and- channel metadata, extract recognized league names, and merge duplicate event- broadcasts within a 15-minute start-time tolerance.-- Support On Now, the remaining schedule for the local calendar day, and the- next seven calendar days after today. On Now refreshes every minute; date- windows reload when selected and at local midnight.-- Cache classified Today and Upcoming event snapshots in memory for five- minutes. Provider EPG sync metadata, external source refreshes, source- assignments, combined-profile membership, and hidden live channel/category- preferences invalidate the cache and reload the selected window.-- Filter assembled events by Football, Basketball, Motorsport, Other, and- detected league in memory, without issuing another EPG query when a filter- changes. Show the distinct playable-channel count for the visible events.-- Emit classifier and deduplication diagnostics only when the Android `SportsHub`- log tag is enabled at DEBUG level. Enable it with- `adb shell setprop log.tag.SportsHub DEBUG`. With diagnostics enabled, read- persisted channel-mapping confidence in one batched query per provider.-- Show a detected league on event cards; clean matchup titles by removing the- league prefix and rendering team pairs consistently.-- Open a TV-friendly details dialog from featured and regular event cards,- showing the schedule, description, and all playable channel choices.-- Add a `Find another channel` picker to event details. Empty search ranks- event-specific candidates and direct mappings; typed search covers the- current visible, playable channel index and returns at most 40 results.-- Use the existing live-channel presentation setting for quality variants:- grouped mode supplies the group's retained variants and quality options to- Sports, while raw mode leaves each channel separately selectable. Sports- does not discard playable alternatives or merge language/region variants- with a new global rule.-- Keep equal-confidence fallback results in neutral channel-name order when- no explicit language or region preference is available. Do not apply a- fixed geography preference. Direct channel choices still open the existing- live player; event-only CH+/CH− cycling is deferred because the current- playback request represents one channel.-- Let the user choose a channel for this event, remember it for seven days,- and forget it later. Revalidate saved picks against the active playable- index, including hidden, adult, protected, and stream-URL rules.-- Focus the first picker result when it appears, keep search focus while the- user types, debounce edits by 200 ms, and avoid rerunning event-wide fallback- scoring for typed queries. Keep only the top eight automatic event matches- and top 40 manual results to bound transient work on large guides.-- Keep the screen event-first. Show a featured event and focused event cards- with each matched playable channel as a direct playback choice. Upcoming- cards include the event date; the LIVE badge appears only while the EPG- programme is airing.-- Reuse existing app playback and browse styling. Localize Sports labels and- screen states in every advertised locale.-- Keep scores, external sports feeds, a persisted event index, and new database- migrations out of the current implementation.-- Reuse compiled normalization patterns and pre-normalized sport/channel terms.- Compute event fingerprints only for competitive candidates unless diagnostics- are enabled, then reuse each fingerprint during grouping and event creation.-- Keep aliases in a shared registry. Added common MUFC, BVB, and Bayern München- spellings, plus aliases for Copa, UEFA, EFL, Scottish, Saudi, and Liga MX- competitions where the source names are distinctive.-- Use real-guide-informed negative classification for news, weather, traffic,- edition-style programmes, and schedule-time strings that can look like- matchup competitors. Added French `basket-ball` recognition and the `LNB Pro- A` league alias after the configured guide exposed a real event.-- Review configured-guide false negatives and add focused fixture coverage.- Added `fudbal` as a football term, compact matchup parsing for a single- unspaced hyphen inside a competition-prefixed title, trailing `Etapa N`- session extraction, ATP 1000 tour-code recognition, and tennis `QF N`- quarterfinal sessions. The guide examples now classify as competitions;- team fixtures expose both competitors and ATP QF4 exposes `Quarterfinal 4`.-- Run Today/Upcoming classification and assembly on `Dispatchers.Default`,- checking coroutine cancellation during channel/program scans so large guide- windows do not monopolize the UI thread.-- Parse event-shaped title data in `SportsEventParser`, with a list-based- competitor model, canonical aliases, content type, and sport-specific- session. Keep the original `Program` records on each assembled event for- fallback presentation and diagnostics. Golf, tennis, motorsport, and fight- cards can carry sessions without fabricated competitors.-- Deduplicate exact event identities with confidence, league, session, and- content-type compatibility checks. Keep a list of groups per identity so- repeated same-team fixtures and partially described league variants remain- separate when the metadata conflicts. Use a 15-minute window for team- fixtures and a 30-minute window for non-team schedules.--## Current limitations--- On Now still queries once per minute. Today and Upcoming snapshots are- in-memory only, and guide changes trigger a full selected-window rebuild.- A debug-only `SportsPerf` tag now records aggregate device timings for visible- channel preparation, resolved-program loading, classification, event- assembly, fallback-index construction, and cold/cache-hit windows. Enable it- with `adb shell setprop log.tag.SportsPerf DEBUG`; entries contain stage- names, elapsed milliseconds, and numeric counts only.-- There is no durable Sports index. The existing programs table is already the- persisted guide source, while Sports events are derived from resolved- programs, active-source membership, channel mappings, and visibility rules.- A second Room index would duplicate derived state. Incremental rebuilds also- need changed programme IDs plus affected source/channel/time ranges, which- current EPG refresh APIs do not expose. Keep the bounded in-memory cache and- existing invalidation until that change feed exists. Extracting the loader- from the ViewModel into a feature-owned repository is a useful future- separation, but by itself would not make the index durable or incremental.-- Provider/profile and EPG-refresh invalidation could not be exercised on the- configured AVD without changing user setup. It has one saved Xtream provider,- no combined profile, and no standalone EPG source. The provider sync dialog- exposes no EPG-only refresh; no provider/catalog sync was run. The TV Guide- screen's Refresh action reloads its local snapshot, not the provider feed.-- Sport filters group every classification outside Football, Basketball, and- Motorsport under Other, including unknown sports.-- League recognition and team aliases remain curated sets. The new parser has- an initial session vocabulary; broad multilingual event-name equivalence and- noisy IPTV channel-name normalization remain future work.-- Event details are available in a dialog; richer team/competition detail- fields still depend on what the EPG provides.-- Team and series preferences are optional and deferred; only event-scoped- remembered choices are implemented.-- Sports respects the shared live channel grouping preference rather than- forcing grouped or raw variants in one feature. No explicit user/source- language-ranking signal is passed to fallback matching, so equal-score- choices remain alphabetic and geography-neutral.-- Earlier cold-load observations were On Now 57 s (334 available channels),- Today 93 s (616), and Upcoming 93 s (585). The next pass recorded On Now at- about 50 s (347), Today at 95.1 s (580), and Upcoming at 100.4 s (585), with- five-minute revisits taking 6.6 s and 5.5 s. After hot-path optimization, a- debug-instrumented run on `emulator-5590` measured `window-cold` at 18.8 s- for On Now, 40.7 s for Today, and 53.5 s for Upcoming. The respective guide- resolved channel-program entry counts were 6,497, 198,808, and 102,256;- visible channel rows were 28,398 in each range. Latest stage timings were:-- | Range | Visible channels | Resolved programs | Classification | Assembly | Fallback index | Window |- | --- | ---: | ---: | ---: | ---: | ---: | ---: |- | On Now | 13.7 s | 0.57 s | 2.9 s | 0.16 s | 1.47 s | 18.8 s |- | Today | 14.1 s | 9.84 s | 16.3 s | 0.40 s | 0.03 s | 40.7 s |- | Upcoming | 13.8 s | 1.02 s | 38.0 s | 0.70 s | 0.02 s | 53.5 s |-- A warm Today revisit logged `window-cache-hit elapsedMs=0` and displayed- 564 available channels. Resolved-program timing varied between Today runs- (4.5–9.8 s), so the aggregate shows guide resolution as a material cost but- does not isolate individual Room statements. Caching `ChannelNormalizer`- patterns reduced visible-channel preparation from about 40 s to about 14 s.- Precomputing channel sports metadata and removing a duplicate sport-term scan- reduced the latest Today classification stage from 19.4 s to 16.3 s. The- configured guide is large and Upcoming remains CPU-heavy; classification- continues on `Dispatchers.Default`, so this work does not block the UI thread.-- The Golf mapping remains the stable two-minute playback pass. The two WSL- Sport TV choices were retested on 2026-10-16 and still fail; current evidence- is recorded below. Playback across every displayed channel choice is not- verified.--## Large-guide CPU microbenchmark--The same production Kotlin classifier and event assembler were run in a-standalone JVM harness with synthetic programmes. Each dataset used 90%-entertainment programmes and 10% sports matchups, with three channel broadcasts-per matchup. The harness included classification, candidate fingerprinting,-and event assembly; it excluded database queries, EPG resolution, Android-runtime costs, and UI work.--| Synthetic programmes | Before median | After median | Improvement |-| ---: | ---: | ---: | ---: |-| 5,000 | 1,203.72 ms | 80.81 ms | 14.9× |-| 20,000 | 4,794.96 ms | 266.62 ms | 18.0× |-| 50,000 | 11,993.92 ms | 871.93 ms | 13.8× |--Each timing is the median of three runs after one warmup, on the local Windows-JVM (Microsoft OpenJDK 17.0.20). These figures quantify the classifier and-dedupe CPU path only; they are not an end-to-end device performance claim.--## Device verification record — 2026-10-16--The user configured a provider on the isolated Android TV AVD-`SportsHub_Worktree_20261016` (`emulator-5590`). The installed APK was built-from this worktree, and its local/device SHA-256 matched. The older emulator-was not used. Guide values below describe this run only; provider names, URLs,-and credentials are intentionally omitted.--| Check | Observation |-| --- | --- |-| On Now | WSL event displayed once with two mapped Sport TV choices. A Golf card exposed `EXYU| SPORT KLUB GOLF HD`; a fight card exposed a beIN Sports choice. |-| On Now / Today / Upcoming | Earlier cold loads were 57 s / 334 channels, 93 s / 616, and 93 s / 585; the current pass loaded On Now in about 50 s / 347, Today in 95.1 s / 580, and Upcoming in 100.4 s / 585. Remote navigation and screenshots confirmed Today and Upcoming were selected. Revisits within the five-minute cache window took 6.6 s for Today and 5.5 s for Upcoming, with the expected event and channel count still visible. |-| Filters / details | Basketball filter showed 55 channels; LNB Pro A narrowed to one channel. Asvel vs Roanne and its French description were visible, and Program Details opened. |-| News false positive | `2 News Nevada vs 5:00p` no longer appeared as a competitive event. |-| Stable playback | Golf mapped channel reached `PLAYING`, `error=null`; 61 screenshots at roughly two-second intervals produced 61 unique SHA-256 hashes over about two minutes. HLS prepare and first-frame logs were present; no fatal/stuck error or MPEG-TS fallback was found. Final frame showed Buick LPGA Shanghai coverage. Back returned to Sports. |-| Earlier FHD capture | `PT| SPORT TV 6 FHD` for the WSL event showed one unique image across 46 screenshots at two-second intervals. The session ended in `NONE`, `error=null`; logs showed HLS first-frame success followed by no-candidate recovery with TS fallback disabled. Superseded by the paced retest below. |-| Earlier HD capture | `PT| SPORT TV 6 HD` stayed on the buffering screen. Although 61 screenshots differed because the loading spinner animated, no video frame or HLS first-frame log appeared. Earlier logs recorded a network source error and selected `XTREAM_TS_FALLBACK`; the final session snapshot was `BUFFERING`, `error=null`. Superseded by the paced retest below. |-| WSL FHD paced retest | On 2026-10-16, 61 screenshots at a 2.00 s average interval covered 120 s and produced 2 unique SHA-256 hashes: video appeared, then froze. The media session ended at `NONE`, `error=null`. Sanitized logs showed HLS prepare and first-frame success, two decoder stalls, then `live-recovery no-candidate` with TS fallback disabled; no fatal error or MPEG-TS fallback was observed. |-| WSL HD paced retest | On 2026-10-16, 61 screenshots at a 2.00 s average interval covered 120 s and produced 61 unique hashes because the buffering indicator animated; no video frame appeared. The final media session was `BUFFERING`, `error=null`. Sanitized logs showed a network timeout, one retry, HLS prepare, and no first-frame success; no MPEG-TS fallback was observed in this retest. |-| Second short playback | The fight event's beIN channel reached `PLAYING`, `error=null`, and HLS first-frame success. Only a short static-event-bumper observation was made, so this is not counted as a stable-feed pass. |-| Phase C/D/E build | The latest debug APK from this worktree was installed with `adb install -r` on `emulator-5590`; local and installed SHA-256 both equal `2D269DB83A791006E593A4480A53DA3349A8FC46445832785E7A2A8706D0F33E`. The configured provider remained available and the WSL event loaded in Sports after relaunch. |-| Phase F picker/search | On the final Phase F build, a guide-backed event opened with the first result focused. D-pad Up returned to search. Query `ESPN` returned configured channels; after the soft keyboard was dismissed, D-pad Down moved focus to the first result. The app remained resumed, and after logcat was cleared before the query, no `OutOfMemoryError`, fatal exception, or ANR appeared. No channel was chosen and no playback was started. |-| Phase F build | Built from this worktree and installed with `adb install -r` on `emulator-5590`, preserving the configured provider. Local and installed SHA-256: `72F05CA007ED06D5A8CA333AFDD56ABEFD97B82733D2F18644C66D05FD1DDFD3`. |-| Performance build | Regex caching and per-channel classification context were installed on `emulator-5590` with `adb install -r`, preserving provider data. Cold windows: On Now 18.8 s, Today 40.7 s, Upcoming 53.5 s; warm Today cache hit 0 ms. The build showed 386/564/585 available channels respectively. Local and installed APK SHA-256 matched: `19965856F24487EA7A05AC3378E82C005D3A2149C00DE8DE73D5E7DEC65DC9B6`. |-| Visibility refresh | Hid `PT| SPORT TV 6 FHD` in Live TV, then Sports reloaded with 28,397 visible channel rows. Unhid that individual channel and refreshed Sports again; the count returned to 28,398. The provider data was preserved. |-| Channel safety tests | Focused fallback-matcher and event-pick policy classes passed (14 + 3 tests), including adult, protected, and unplayable channel exclusions. |-| Real-guide false negatives | Four guide titles were repaired and verified as competitive: `Fudbal - Španska liga: Deportivo - Levante`, `Fudbal - Francuska liga: Le Mans - Toulouse`, `Live Bundesliga: Eintracht Frankfurt-Koln Etapa 6`, and `ATP1000 '26: Shanghai Masters QF4`. Team pairs were extracted for football; ATP QF4 produced `Quarterfinal 4`. A follow-up resolved `Burnley vs Wolverhampton Wanderers - EFL - English Football League SkyBet - Championship 2026/2027` as EFL Championship despite a generic Premier League description. |-| Fallback precision sample | The loaded guide produced zero automatic fallback candidates because all assembled events had direct mappings. The mapped event's picker showed its two direct Sport TV options only. No real unresolved event was available to measure fallback precision or tune thresholds. |-| Provider/profile and EPG refresh | The isolated AVD had one Xtream provider, no combined profile, and no standalone EPG source. The sync dialog had no EPG-only refresh. No provider/catalog sync was run; TV Guide Refresh only reloaded its local snapshot. |-| Sports JVM tests | On 2026-10-17, `:feature:live:testDebugUnitTest --tests 'com.streamvault.feature.live.sports.*'` passed: 50 tests across 7 suites, 0 failures or errors. |-| Phase C league model | Canonical league IDs drive alias-aware merging, event identity, filter keys, and UI grouping. The EFL Championship label uses localized resources for all 38 advertised locales. On `emulator-5590`, the EFL Championship filter showed Burnley vs Wolverhampton Wanderers; the featured opponents no longer include the competition suffix. See `artifacts/sports-ui-review/league-regression.png`. |-| Latest build | Built and installed on `emulator-5590`; local and installed APK SHA-256 matched: `D4319147C105FD943411A5A9BBA589ABDACB426715E500105093DCCFA097FC1A`. The configured provider remained available. |--Remaining checks: provider/combined-profile switching and provider/external-EPG refresh need an AVD with those sources configured; fallback precision-needs a real event without direct mappings; and the two WSL playback failures-need a stream/provider diagnosis or code-level resolution. The cache and-resolved-program stages are measured; individual Room statements and-fallback-search time are not isolated. The four original guide false negatives-and the later EFL league/title mismatch are covered by focused-parser/classifier fixtures.--## Boundaries--- Programme and channel data remains user-owned; only already configured- channels can be played.-- Sports events are derived when the hub loads from the existing resolved EPG- API; Compose recomposition does not trigger another EPG query.-- Event status describes the EPG broadcast schedule, not independently- verified match status.--## Revised plan progress--- Phase A guide-backed UI, filter, details, and mapping checks are complete on- the isolated AVD. Stable playback succeeded on the Golf channel for the full- two-minute capture. The two WSL Sport TV choices failed their paced- progression retests, so every surfaced choice has not yet been verified.-- The 48-test sports JVM suite passes across classification, metadata- registries, event identity/assembly, broadcast status, XMLTV fixtures, and- conservative channel fallback matching.- Added event-type/session, alias, same-team repeat, league-conflict,- confidence, non-team tournament, and time-tolerance coverage. The fixture set- covers the local-news schedule-time false positive and French LNB Pro A- basketball programme. Thirty-nine existing data-layer tests passed for EPG- resolution and persisted/manual overrides.-- Phase C/D introduced typed competitors, `SportsEventType`, `session`, raw- `Program` references, and the parser boundary; Phase D adds confidence and- metadata-aware grouping, separate replay/show content, multilingual team- aliases, and separate non-team sessions. Broad league enrichment remains- open where no guide evidence justified it.-- Phase E adds a cached normalized index of visible, playable channels and- ranked fallback candidates from team pairs, fight pairs, and event-specific- non-team phrases. ISO, named-month, and unambiguous numeric dates reject- mismatched event channels; ambiguous numeric dates provide no date bonus.- Direct EPG broadcasts remain first, and fallback channels are added only- when an event has no playable direct stream. Runtime playback failures do- not yet invoke this matcher automatically; the configured WSL event had- working direct mappings, so automatic fallback playback remains unverified.-- Phase F adds manual event search, seven-day event-scoped picks, forgetting,- and active-index validation. The picker defaults to an event-specific- suggestion when available and searches only the current visible/playable- channel set. Typed queries are debounced and bounded to prevent a large-guide- scan from exhausting the Android TV heap. Focused matcher and preference- tests pass; team/series preferences remain optional and deferred.-- `LiveGraphBehaviorTest` passed on the isolated worktree AVD (two test- methods). The Phase F picker/search received a device smoke check, including- D-pad Down from the search field after keyboard dismissal; persistent- choice and forget were validated by unit tests rather than a device playback- session.-- No external sports provider, score provider, or backend was added. The- existing resolved EPG-to-channel path remains the primary mapping.--- Phase H found and repaired four real-guide false negatives: two compact- football matchups, a Bundesliga title with a trailing `Etapa 6` session, and- an ATP1000 quarterfinal title. Focused classifier/XMLTV coverage and the full- sports JVM suite pass. Fallback precision remains unmeasured because every- loaded event had a direct mapping; the mapped-event picker showed only the- two direct choices. Provider/profile switching and provider/external EPG- refresh also remain unexercised because the isolated AVD lacks those sources.-diff --git a/docs/Sports-PERFORMANCE.md b/docs/Sports-PERFORMANCE.mddeleted file mode 100644index 89aceca2..00000000--- a/docs/Sports-PERFORMANCE.md+++ /dev/null@@ -1,85 +0,0 @@-# Sports loading performance — 2026-10-17--Worktree: `D:/antigravity-scratch/iptv-player/.worktrees/sports-integration`-Branch: `codex/sports-integration`-Device: `emulator-5590`, existing configured playlist and guide retained.--## Changes — first pass--- Resolve provider portal configuration once per provider per channel presentation pass, including null results for non-Stalker providers. Previously the callback queried Room for every presented channel.-- Keep one observed channel snapshot per active provider while the Sports ViewModel is alive. Range changes and minute refreshes reuse it. Catalog/presentation/visibility changes replace it and invalidate derived events; combined-profile membership changes restart the appropriate subscriptions.-- Reuse prepared classifier channel contexts within each snapshot. Programme resolution still runs for On Now each minute, so changes in what is airing are not hidden behind a stale event cache.-- Serialize event-cache invalidation through the loading collector, including explicit Retry. A failed channel subscription can be restarted with Retry.-- Skip absent literal tags before running normalization regexes. Existing regex boundaries and decoration order remain authoritative for possible matches.-- Defer the full channel fallback index until an event lacks a playable direct choice or manual channel search requests it. Remembered picks use the visible channel entries independently of that index.-- Share repeated token strings within the fallback index; construct canonical-name and EPG-ID maps lazily. Cache identity uses the actual channel entries instead of allocating a second 28,398-row signature list.-- Add an `initial-content` debug timing covering the initial channel subscription through publication of the Sports UI state. The existing `window-cold` timing now measures processing after the observed channel snapshot is available; it should not be read as total initial navigation latency.--No user-facing text or localization resources changed. No playback path changed, and no durable Sports database was introduced.--## Tests — first pass--- `:domain:test --tests '*ChannelNormalizerTest'`: 17 tests, no failures/errors.-- `:data:testDebugUnitTest --tests '*ChannelRepositoryImplTest'`: 19 tests, no failures/errors.-- `:feature:live:testDebugUnitTest --tests '*sports.*'`: 56 tests, no failures/errors.-- `:app:assembleDebug`: passed; installed with replacement on the configured emulator.-- `git diff --check`: passed.--The new ViewModel tests cover catalog subscription reuse across a minute tick and range changes, category visibility invalidation, changed playback URLs, provider switching, retry after an initial catalog failure, and manual search/remembered choices with deferred indexing. Repository tests verify one portal query for 100 raw or grouped channels, including absent portal configuration. Normalizer coverage includes embedded-token rejection, mixed-case decorations, accented names, and URL-derived transport/quality metadata.--The first test invocation exposed a JUnit setup return-type error in the new test fixture; it was corrected before the passing run. Final verification used `--no-configuration-cache` because the existing feature-boundary task reports configuration-cache incompatibilities.--## Device measurements — first pass--Debug `SportsHub` and `SportsPerf` logging remained enabled throughout these runs. The guide supplied 28,398 visible channels, 6,404 On Now programme groups, and 133 assembled events in the two fresh-process runs below.--| Stage | First pass in this session | Final implementation |-| --- | ---: | ---: |-| Initial visible-channel snapshot | 16,942 ms | 8,843 ms |-| Initial programme resolution | 8,678 ms | 6,100 ms |-| Initial classification | 9,567 ms | 5,611 ms |-| Initial event assembly | 285 ms | 123 ms |-| Eager fallback index | 5,047 ms | Not needed / not built |-| Initial state publication, including channel wait | 41,423 ms | 21,223 ms |-| First automatic On Now refresh | Process ran out of heap during the following EPG read | 6,143 ms; no channel reload |-| Second automatic On Now refresh | Not completed | 5,829 ms; no channel reload |--These are individual debug emulator observations, not a statistically controlled benchmark. The first-pass run already included the portal-query fix and observed channel snapshots, but still built the eager fallback index and lacked the literal normalization guard. Retained pre-change warm-process logs measured approximately 21–25 seconds per minute rebuild, including 14–15.5 seconds preparing channels each time; they are not a fresh-process cold-entry baseline.--The first-pass memory failure was an `OutOfMemoryError` on a 192 MB managed-heap limit during EPG resolution. The final run's initial loaded state showed about 36 MB Dalvik heap allocation in `dumpsys meminfo`, rising to about 37 MB allocated after the capture.--Final UI verification captured 61 screenshots over 151 seconds, using a two-second pause between captures (ADB screenshot/pull overhead made the observed cadence approximately 2.5 seconds). Process 31610 survived throughout, with zero fatal AndroidRuntime entries for that process. Logs show exactly one visible-channel preparation, zero fallback-index builds, the initial window load, and two automatic refreshes. The second refresh changed the event count from 133 to 132 as a programme stopped matching On Now. The final screenshot and UI hierarchy both retained the Sports controls, featured fixture, and league cards. Static screenshots are expected after loading; this was a tab-load test, not a video frame-progression test.--Evidence is under `artifacts/sports-performance/`: `normalizer-build.log`, `before-retained.log`, `after-first-pass.log`, `first-pass-crash.log`, and the final device capture/logs. Screenshots validate tab loading and UI survival, not moving video. This is not live-playback stability certification.--## Continuation — classification cache, retained revisits and Today query--Loading, observed channel snapshots, event snapshots, and filters now live in a feature-owned `@Singleton SportsHubRepository`. The ViewModel delegates to it, so a replacement ViewModel can immediately expose the existing valid state. The repository uses the application's repository coroutine scope and pauses EPG loads when the state has no screen observers. Lightweight guide/source observation and channel invalidation continue while the tab is hidden. Re-entry prunes expired fixtures and rejects a retained snapshot after five minutes or a local-date change; refreshing then runs against the existing channel snapshot. This is an in-process cache, not disk persistence.--`SportsClassificationCache` is a content-based LRU capped at 8,192 entries and an estimated 8 MiB. Keys include title, description, genre, category, detected channel sport, sports-channel evidence, and group title. Programme IDs, schedule timestamps, raw channel identities and stream URLs are not retained in the key. Classification is independent of those fields; event fingerprints are still derived separately for each candidate, preserving channel-dependent fallback identity. Changed text/context misses the cache, negative results are cached, and unusually large individual descriptions bypass storage. Explicit Retry clears the classification cache.--Today now queries `[now, next local midnight)` through the existing overlap queries (`end_time > start` and `start_time < end`), retaining programmes already in progress without fetching programmes that have already ended. Today/Upcoming event-cache hits are also pruned by the current window before presentation.--Guide-source policy is included in revision invalidation alongside sync metadata, guide sources, assignments, hidden categories/channels, profile membership and observed channel presentation changes. No user-facing text changed.--Validation: `:feature:live:testDebugUnitTest --tests '*sports.*'` passed 66 tests with no failures/errors; `:app:assembleDebug` passed. The new tests cover content/context cache identity, negative caching, LRU/byte limits, immediate retained state during a blocked refresh, hidden-category invalidation while unobserved, no EPG reads while unobserved, expired-event removal and the narrowed Today query with an ongoing programme. Existing classifier/parser/assembly/fallback tests remain included.--The first fresh-process device run of this continuation published 133 events in 18,404 ms, including 8,952 ms for 28,398 visible channels, 5,014 ms programme resolution, 3,524 ms classification and 128 ms assembly. Classification already reused 2,793 inputs within that first load, with 3,611 misses and approximately 4.17 MB estimated cache storage. The first automatic refresh took 1,493 ms: 562 ms resolution, 688 ms classification and 82 ms assembly. All 6,404 classifications were cache hits. Debug logging settings were retained from the first pass; these remain individual emulator observations.--The second automatic refresh took 1,457 ms, with 6,400 hits and four misses for changed inputs. A new 61-frame capture with two-second pauses spanned 149.4 seconds. Process 32455 survived both refreshes, with zero fatal AndroidRuntime entries; approximately 38 MB Dalvik heap allocation was observed afterwards. The Sports controls, featured event and league cards remained visible.--The tab was then left on Home for a measured 81-second interval. Sports window-load count stayed at three throughout that interval. Returning exposed 127 retained, time-pruned events (`retained-presentation elapsedMs=0`, indicating state availability rather than screen rendering time), while a background refresh published 131 current events after 1,646 ms. There was no channel reload. The first Sports revisit screenshot at 22:25:25.293 UTC already contained the fixture/filter UI, before background refresh publication at 22:25:25.973 UTC.--Cold Today loading after that revisit took 6,729 ms: 555 ms for 17,688 resolved programme entries, 5,813 ms classification, and 182 ms assembly, yielding 250 events. Classification used 11,776 hits and 5,912 misses. The cache stayed below its byte cap at 8,387,502 estimated bytes and 7,312 entries. This is the current guide/time window, not a controlled comparison against the older full-day Today measurements above.--Today remained loaded through a 31-frame capture with no fatal error. Switching to On Now took 1,891 ms after some classifier entries had been evicted by the larger Today working set (5,658 hits / 746 misses). Switching back to Today logged `window-cache-hit elapsedMs=0 items=250` and did not issue another resolved-programme query. The final cache estimate observed was 8,387,836 bytes, below the 8,388,608-byte cap. The app was left on Today with the same process still running.--Continuation artifacts are under `artifacts/sports-performance/retained-cache/`; the passing build log is `artifacts/sports-performance/retained-cache-final-build.log`.--## Remaining work--- Cold entry still spends substantial time preparing the shared channel catalog, resolving EPG data, and classifying programmes. It is not instant.-- Programme rows still need resolution on On Now refreshes, even when classification hits the cache. A durable or incremental Sports index remains outside this change.-- Process recreation still pays the cold cost; retained revisits apply within the running app.-- Cold Upcoming performance and large-catalog manual-search memory use need separate device measurements. The deferred index changes when that cost is paid; manual search still needs an index.-- This pass does not validate guide refresh or combined-profile switching on the configured device, which has one saved provider. Provider switching and visibility invalidation are covered with controlled unit fixtures.diff --git a/docs/Sports-PLAN-3-Generic-Providers.md b/docs/Sports-PLAN-3-Generic-Providers.mddeleted file mode 100644index ed5788ea..00000000--- a/docs/Sports-PLAN-3-Generic-Providers.md+++ /dev/null@@ -1,2636 +0,0 @@-# StreamVault Sports Hub — PLAN 3: Generic Sports Data Providers--**Purpose:** Add a provider-neutral, user-configured sports-data system on top of the Sports Hub.-**Sequence:** Implement after the related Sports Plan 2 channel-discovery and resilience improvements are stable.-**Core principle:** External providers enrich or optionally drive event discovery, but StreamVault playback always resolves to the user's own M3U/Xtream channels.-------# 0. Relationship to Plan 2--Plan 3 is **not a replacement** for Plan 2.--Implement Plan 2 first, especially the pieces that create a stable local Sports foundation:--- canonical event model;-- improved team/non-team event parsing;-- stronger normalization and aliases;-- confidence-aware deduplication;-- reliable EPG-to-channel resolution;-- fallback event-channel matching;-- manual channel selection;-- remembered channel preferences;-- fixture and integration tests;-- real-device verification.--Plan 3 depends on those foundations because external APIs introduce additional event identities, team names, league names, kickoff times, broadcaster names, and partial/conflicting data.--The intended progression is:--```text-PLAN 1-EPG-first Sports Hub- ↓-PLAN 2-Real-world IPTV resilience-(IPTV resilience improvements)- ↓-PLAN 3-Generic / BYOK Sports Data Providers-```--Do not pause Plan 2 halfway through merely to start connecting APIs.--However, once the canonical event model and normalization boundaries are stable, provider interfaces may be scaffolded without implementing real providers yet.-------# 1. Goal--Allow users to configure one or more sports-data providers using their own:--- API key;-- bearer token;-- username/password where appropriate;-- OAuth sign-in where a supported provider requires it;-- base URL / endpoint where configurable;-- custom REST/JSON source.--Providers may supply different capabilities, including:--```text-event discovery / fixtures-live scores-game state / clock / period-standings-team metadata-league metadata-artwork-broadcast/network metadata-lineups-statistics-```--StreamVault must not assume every provider supports every capability.--The system must work with:--```text-no provider configured-```--using the existing EPG Sports Hub.-------# 2. Major architectural change--The current Sports Hub is EPG-first.--Plan 3 generalizes this to a **capability-based source strategy**.--Do not think of the whole Sports Hub as globally:--```text-EPG-first-```--or:--```text-API-first-```--Instead decide independently which source is authoritative for each capability.--The important capabilities are:--```text-1. Event discovery-2. Live scores / game state-3. Standings-4. Team / league metadata-5. Broadcaster metadata-6. Playback/channel discovery-```--Playback/channel authority is special:--> **Only the user's configured M3U/Xtream sources can provide playable StreamVault channels.**--An external API may help identify broadcasters, but it must never inject arbitrary third-party streams.-------# 3. Target architecture--```text- EVENT SOURCES-- +----------+-----------+- | | |- v v v- EPG Provider A Provider B- | | |- +----------+-----------+- |- v- Event Resolver- / Normalization- |- v- Canonical SportEvent- |- +---------------+----------------+- | | |- v v v- Live Scores Standings Metadata- | | |- +---------------+----------------+- |- v- Broadcast Resolver- |- +---------------+----------------+- | | |- v v v- API broadcaster XMLTV event-channel names- | | |- +---------------+----------------+- |- v- User M3U / Xtream- |- v- PLAY-```-------# 4. Source modes--Expose an event-discovery strategy in Settings.--Recommended user-facing options:--```text-Sports event source--● Automatic-○ TV Guide / EPG-○ <configured provider capable of events>-```--## 4.1 Automatic--Recommended default.--Behavior:--```text-if a configured provider supports EVENTS:- prefer that provider for canonical event discovery- merge/corroborate EPG information-else:- use EPG event discovery-```--Automatic should not be tied to a particular vendor.--## 4.2 TV Guide / EPG--Force the current local behavior.--Useful when:--- the user's guide is excellent;-- provider quota is limited;-- API coverage is worse than the user's EPG;-- user prefers local-only behavior.--## 4.3 Specific provider--Allow a provider to become the event-discovery source only if it advertises the required capability.--Example:--```text-Sport Provider A-Capabilities:-✓ Events-✓ Live scores-✓ Standings-✗ Broadcasters-```--It may be selected for event discovery even without broadcaster data.--Channel discovery can still rely on EPG + playlist matching.-------# 5. Provider capability model--Define explicit capabilities.--Example:--```kotlin-enum class SportsCapability {- EVENTS,- LIVE_SCORES,- GAME_STATUS,- STANDINGS,- TEAM_METADATA,- LEAGUE_METADATA,- ARTWORK,- BROADCASTERS,- LINEUPS,- STATISTICS-}-```--A provider adapter declares:--```kotlin-interface SportsProvider {- val id: String- val displayName: String- val capabilities: Set<SportsCapability>-}-```--Do not infer a capability from successful HTTP calls.--Capabilities should be explicitly declared by the adapter/configuration.-------# 6. Provider roles are independent--A user may configure different providers for different jobs.--Example:--```text-Event discovery:-Provider A--Live scores:-Provider A--Standings:-Provider B--Team metadata:-Provider C--Playback:-Automatic / local playlist-```--Internally, support this from the beginning.--The first UI may simplify this to:--```text-Automatic-```--for most capabilities.-------# 7. Recommended Settings UX--Top-level:--```text-Settings- Sports- Data Providers- Event Source- Live Scores- Standings- Metadata-```--## Data Providers screen--Example:--```text-Sports Data Providers--Provider A-Connected-Fixtures · Live scores · Standings--Provider B-Connected-Live scores · Team metadata--Custom Sports Provider-Connected-Fixtures · Live scores--+ Add provider-```--Do not expose secrets in normal UI after entry.--Provide:--```text-Test connection-Edit-Disable-Remove-```-------# 8. Adding a known provider--Flow:--```text-Add Provider- ↓-Choose provider type- ↓-Configure credentials / endpoint- ↓-Test connection- ↓-Discover/validate capabilities- ↓-Save-```--Example:--```text-Provider: Sportmonks--Base URL:-[ default value ]--API key:-[••••••••••••••]--Test connection-```--For known providers, users should not have to manually enter every endpoint path.--The provider adapter knows its routes.-------# 9. Base URL configuration--Each provider descriptor may define:--```kotlin-data class ProviderEndpointConfig(- val defaultBaseUrl: String,- val allowOverride: Boolean-)-```--For official hosted APIs:--```text-default URL-```--should normally be sufficient.--Allow override when useful for:--- regional endpoints;-- self-hosted compatible servers;-- API gateways;-- mirrors explicitly supported by the provider;-- enterprise deployments.--Do not require the user to enter a separate URL for every API operation for known adapters.-------# 10. Authentication model--Support reusable authentication types.--Example:--```kotlin-sealed interface ProviderAuth {- data object None : ProviderAuth-- data class ApiKeyHeader(- val headerName: String- ) : ProviderAuth-- data class ApiKeyQuery(- val parameterName: String- ) : ProviderAuth-- data object BearerToken : ProviderAuth-- data object BasicAuth : ProviderAuth-- data class OAuth2(- val providerId: String- ) : ProviderAuth-}-```--Provider adapters declare which scheme they use.-------# 11. API-key handling--Keys belong to the user.--Do not ship a shared StreamVault production API key.--Store credentials securely using Android's supported encrypted/Keystore-backed mechanism appropriate to the project's architecture.--Requirements:--- never log API keys;-- never include API keys in diagnostics;-- avoid exposing query-string keys in logs;-- redact credentials from exception messages;-- do not include credentials in backups unless existing secure-settings behavior explicitly allows it and the user understands that;-- do not sync credentials through unrelated preference export unless intentionally designed.-------# 12. OAuth providers--OAuth cannot be fully generic in practice.--Different providers may vary in:--```text-authorization endpoint-token endpoint-PKCE requirements-client ID-client secret rules-redirect URI-scopes-device-code support-refresh-token behavior-token lifetime-```--Therefore:--> Build a reusable OAuth framework, but configure/implement OAuth per supported provider.--Do not pretend one generic "OAuth URL" field supports all services safely.--Prefer PKCE/device authorization where appropriate for installed apps.--Never embed a confidential client secret in the APK when the provider requires that secret to remain private.-------# 13. Provider adapter interface--Do not create one giant interface with mandatory methods.--Prefer capability-specific interfaces.--Example:--```kotlin-interface SportsProvider {- val descriptor: SportsProviderDescriptor-}--interface EventProvider : SportsProvider {- suspend fun events(- request: EventRequest- ): ProviderResult<List<ProviderEvent>>-}--interface LiveScoreProvider : SportsProvider {- suspend fun liveScores(- request: ScoreRequest- ): ProviderResult<List<ProviderScore>>-}--interface StandingsProvider : SportsProvider {- suspend fun standings(- request: StandingsRequest- ): ProviderResult<ProviderStandings>-}--interface BroadcastProvider : SportsProvider {- suspend fun broadcasters(- request: BroadcastRequest- ): ProviderResult<List<ProviderBroadcaster>>-}--interface TeamMetadataProvider : SportsProvider {- suspend fun teamMetadata(- request: TeamMetadataRequest- ): ProviderResult<ProviderTeamMetadata>-}-```--A single adapter may implement several interfaces.-------# 14. Provider descriptor--Example:--```kotlin-data class SportsProviderDescriptor(- val id: String,- val displayName: String,- val capabilities: Set<SportsCapability>,- val authType: ProviderAuthType,- val defaultBaseUrl: String?,- val supportsCustomBaseUrl: Boolean,- val requiresAccount: Boolean,- val attribution: ProviderAttribution?,- val configurationVersion: Int-)-```--Do not include legal/commercial claims in the descriptor unless verified.--Provider integration documentation should separately record reviewed terms.-------# 15. Provider-neutral event model--External events must first become provider-neutral DTOs.--Example:--```kotlin-data class ProviderEvent(- val providerEventId: String,- val sport: String?,- val league: ProviderLeague?,- val title: String?,- val competitors: List<ProviderCompetitor>,- val eventStart: Instant?,- val eventEnd: Instant?,- val status: ProviderGameStatus?,- val broadcasters: List<ProviderBroadcaster>,- val metadata: Map<String, String>-)-```--Then normalize into StreamVault's canonical `SportEvent`.--Do not expose provider JSON models directly to the UI.-------# 16. Separate event time from broadcast time--Plan 3 introduces a critical distinction.--An API may say:--```text-Kickoff: 21:00-```--while XMLTV says:--```text-TV coverage: 20:30–23:30-```--Both are correct.--Model separately:--```kotlin-data class SportEventTiming(- val eventStart: Instant?,- val eventEnd: Instant?,- val broadcastStart: Instant?,- val broadcastEnd: Instant?-)-```--UI can then show:--```text-Kickoff 21:00-Coverage from 20:30-```--when both are known.--Do not treat normal pre-game coverage as an API/EPG conflict.-------# 17. Event provenance--Once multiple sources exist, provenance becomes essential.--Each canonical event should know its source references.--Example:--```kotlin-sealed interface SportsSourceRef {- data class Epg(- val programmeId: String,- val channelId: String- ) : SportsSourceRef-- data class Provider(- val providerId: String,- val externalEventId: String- ) : SportsSourceRef-}-```--A canonical event may contain:--```text-EPG source-+-Provider A source-+-Provider B source-```-------# 18. Field provenance--Where practical, preserve provenance for enriched fields.--Example:--```kotlin-data class SourcedValue<T>(- val value: T,- val source: SportsSourceRef,- val updatedAt: Instant?-)-```--This is particularly useful for:--```text-score-status-league-event start-team metadata-artwork-broadcaster-```--Do not necessarily wrap every UI field in `SourcedValue`; the internal resolver may keep provenance separately if that is cleaner.-------# 19. Event resolver--Introduce a provider/EPG event resolver.--Responsibilities:--```text-normalize provider event-normalize EPG event-generate candidate identities-match equivalent events-merge trusted fields-preserve source references-cache provider-event mappings-```--Input:--```text-EPG SportEvent candidates-ProviderEvent candidates-```--Output:--```text-Canonical SportEvent-```-------# 20. External-event matching--Match on:--```text-sport-league-competitors-event title/session-kickoff time-event date-```--## Team sports--Strong signals:--```text-same canonical competitor pair-same league-event start within tolerance-```--## Fights--Use:--```text-fighter pair-promotion-card date-```--## Motorsport--Use:--```text-series-grand prix/event-session-date/time-```--## Golf--Use:--```text-tour-tournament-round/date-```--## Tennis--Use:--```text-tour/tournament-player pair when available-round-time-```--Do not use one universal fuzzy-title matcher for every sport.-------# 21. External ID mapping cache--After a high-confidence match:--```text-StreamVault event identity-↕-provider event ID-```--cache that association.--Example:--```kotlin-data class ProviderEventLink(- val providerId: String,- val providerEventId: String,- val localEventFingerprint: String,- val confidence: Float,- val linkedAt: Instant-)-```--This reduces repeated fuzzy matching during score refreshes.--Invalidate/re-evaluate when:--```text-event identity changes materially-provider season changes-kickoff moves significantly-teams change-cached link fails repeatedly-```-------# 22. Source conflict policy--Providers and EPG may disagree.--Do not silently overwrite values without a defined policy.--Example rules:--## Event identity--Configured event provider wins when selected as event authority and confidence is high.--## Broadcast times--EPG wins for:--```text-broadcastStart-broadcastEnd-```--## Kickoff/event start--Configured event provider wins when available.--## Playback channels--Local StreamVault EPG/channel mapping and user's playlist win.--## Live score/status--Configured live-score provider wins.--## Description--Prefer EPG description unless provider metadata is explicitly selected.--## Artwork--Use configured metadata/artwork provider according to priority.-------# 23. Automatic source strategy--`Automatic` should be deterministic.--Suggested initial policy:--```text-EVENTS:-1. explicitly selected EventProvider-2. highest-priority enabled provider with EVENTS-3. EPG--LIVE SCORES:-1. explicitly selected LiveScoreProvider-2. highest-priority enabled provider with LIVE_SCORES-3. none--STANDINGS:-1. explicitly selected StandingsProvider-2. highest-priority enabled provider with STANDINGS-3. unavailable--METADATA:-1. selected metadata provider-2. enabled provider priority-3. EPG/local metadata--PLAYBACK:-always local M3U/Xtream-```--Do not automatically make a provider authoritative merely because it happens to return data.-------# 24. API-first event discovery--When a provider is selected for `EVENTS`:--```text-Provider- |- v-ProviderEvent[]- |- v-normalize- |- v-Canonical SportEvent[]- |- +--------------------------+- | |- v v-EPG corroboration no EPG match- | |- v v-mapped channels fallback channel matcher-```--The API may show events the user's EPG completely omits.--Those events may still appear in Sports.--If no playable StreamVault channel is found:--```text-No matching channel in your TV sources-```--Do not hide the event merely because playback is unavailable.-------# 25. EPG-first with provider enrichment--When EPG is selected for events:--```text-EPG- |- v-SportEvent- |- v-ProviderEventMatcher- |- +--> score- +--> real game state- +--> league metadata- +--> team metadata- +--> standings link-```--This preserves the existing Sports behavior while improving data quality.-------# 26. Hybrid event discovery--Automatic may eventually merge event sets from both sources.--Example:--```text-API events-+-EPG-only sports events-```--This is useful when a provider covers football/basketball but the user's EPG also contains:--```text-wrestling-local sports-regional competitions-minor leagues-```--that the API does not cover.--Do not drop valid EPG sports merely because an API is enabled.--Recommended behavior:--```text-canonical provider events-+-unmatched high-confidence EPG events-```--with deduplication between them.-------# 27. Broadcaster data--Some providers may supply broadcaster/network information.--Model separately from playable channels.--Example:--```kotlin-data class ProviderBroadcaster(- val name: String,- val country: String?,- val language: String?,- val type: BroadcastType?-)-```--Possible types:--```text-LINEAR_TV-STREAMING_SERVICE-RADIO-UNKNOWN-```--Provider broadcaster data is a **matching signal**, not a playable stream.-------# 28. Broadcast resolver--Signals, strongest to weakest:--```text-1. existing resolved EPG -> StreamVault channel-2. user's remembered event/team/series choice-3. exact EPG/channel identifier-4. provider broadcaster + exact/canonical local network match-5. event-named IPTV channel-6. EPG title near API event time-7. manual selection-```--Exact order may vary when a user explicitly overrides a choice.--Do not let broad fuzzy broadcaster names auto-route dangerously.--Example:--```text-FOX-TNT-ABC-```--may be too ambiguous without region/network context.-------# 29. Poor-EPG repair--One major benefit of API event discovery is repairing weak XMLTV.--Example:--API:--```text-FC Barcelona vs Real Madrid-LaLiga-Kickoff 21:00-```--EPG:--```text-Live Football-20:30–23:30-beIN Sports 1-```--Resolver may infer a high-confidence match from:--```text-sport-time overlap-league/channel context-provider broadcaster-other available signals-```--Then StreamVault can display:--```text-FC Barcelona vs Real Madrid-LaLiga-Kickoff 21:00--Watch on:-beIN Sports 1-```--while preserving the EPG broadcast window.--This inference must be confidence-gated and testable.-------# 30. Provider priority--Allow ordering enabled providers.--Example:--```text-Provider priority--1. Provider A-2. Provider B-3. Custom Server-```--Use priority only among providers that support the requested capability.--Do not call providers lacking the capability.-------# 31. Rate limiting and quota awareness--BYOK means each user generally consumes their own quota.--Still, StreamVault must behave responsibly.--Each provider adapter should define refresh policy guidance.--Example:--```kotlin-data class ProviderRatePolicy(- val liveRefresh: Duration,- val upcomingRefresh: Duration,- val standingsRefresh: Duration,- val metadataRefresh: Duration-)-```--Use caching.--Suggested conceptual behavior:--```text-live score:-frequent--upcoming fixtures:-minutes/hours--standings:-tens of minutes--team metadata:-days-```--Do not use one universal polling interval.-------# 32. HTTP cache / application cache--Provider responses should be cached according to capability.--Examples:--```text-event schedule cache-score cache-standings cache-team metadata cache-artwork cache-```--Avoid re-downloading static metadata every Sports-screen opening.--Cache keys must include:--```text-provider-account/config identity where necessary-sport/league/team/event-query period-```--Never include raw API keys in cache keys.-------# 33. Error isolation--A failing provider must not break the Sports Hub.--Examples:--```text-Provider A score request fails- ↓-show event without score--Provider B standings fails- ↓-show "Standings unavailable"--Event provider unavailable- ↓-Automatic may fall back to EPG if allowed-```--One malformed provider event must not discard an entire league response.-------# 34. Provider health--Track lightweight runtime health:--```text-last successful request-last error category-authentication failure-rate-limited-temporarily unavailable-invalid configuration-```--Settings may show:--```text-Provider A-Connected--Provider B-Authentication failed-```--Do not expose raw sensitive server errors unnecessarily.-------# 35. Retry policy--Classify failures:--```text-authentication error-rate limit-server 5xx-network timeout-parse/schema error-configuration error-```--Rules:--- do not retry invalid credentials aggressively;-- respect `Retry-After`;-- use bounded backoff for transient failures;-- do not hammer a broken endpoint;-- retain stale cached data where safe and clearly applicable.-------# 36. Custom Sports Provider--Add an advanced generic integration mode.--Target users:--```text-self-hosted API users-advanced users-custom backend users-unsupported legitimate APIs-```--This should not require a StreamVault-specific provider adapter for simple JSON APIs.-------# 37. Custom provider configuration--Example:--```text-Custom Sports Provider--Name:-My Sports API--Base URL:-https://example.com/api--Authentication:-Bearer Token--Events endpoint:-/events--Live scores endpoint:-/scores/live--Standings endpoint:-/standings-```--Endpoints may be optional.--Capabilities are enabled only when the required mapping/configuration exists.-------# 38. Custom JSON mapping--Provide a declarative mapping format.--Example conceptual configuration:--```json-{- "events": {- "path": "$.data.events",- "id": "$.id",- "sport": "$.sport.name",- "league": "$.league.name",- "title": "$.name",- "start": "$.start_time",- "homeName": "$.home.name",- "awayName": "$.away.name",- "homeScore": "$.home.score",- "awayScore": "$.away.score",- "status": "$.status"- }-}-```--Actual implementation may use JSONPath or a simpler internal field-selector language.--Do not execute arbitrary user code/scripts in v1.--Prefer declarative mapping.-------# 39. Custom request templates--Advanced configuration may need:--```text-query parameters-headers-date placeholders-league placeholders-event ID placeholders-pagination-```--Example:--```text-/events?date={date}&league={leagueId}-```--Design a safe template language.--Do not allow arbitrary shell/code execution.--Potential placeholders:--```text-{date}-{fromDate}-{toDate}-{leagueId}-{teamId}-{eventId}-{page}-```-------# 40. Custom authentication--Support:--```text-none-header API key-query API key-Bearer-Basic-```--OAuth for arbitrary custom providers should be deferred unless a secure generic flow can be designed.--Known provider adapters can support OAuth explicitly.-------# 41. Pagination--Provider adapters must own pagination logic.--Possible patterns:--```text-page/pageSize-offset/limit-cursor-next URL-```--Do not expose pagination to Sports UI.--Custom provider mapping may eventually support common pagination modes.--For v1 custom-provider support, it is acceptable to support only simple non-paginated/single-page event feeds if clearly documented.-------# 42. Provider-specific adapters--Known providers should have dedicated adapters.--Benefits:--- better validation;-- better pagination;-- better error handling;-- provider-specific status mapping;-- provider-specific league/team identity;-- correct authentication;-- richer capability support.--The custom provider is a fallback, not a replacement for quality first-class adapters.-------# 43. Adding a provider checklist--Every built-in adapter must document:--```text-provider name-official developer documentation-commercial-use status / terms review-auth type-base URL-capabilities-rate limits known to the user/account-required attribution-endpoint list-pagination-time format-league identity-team identity-live status mapping-score representation-broadcast representation-known limitations-```--Do not add a provider simply because an endpoint works technically.-------# 44. Undocumented / reverse-engineered providers--Do not include provider-specific Play-build adapters for undocumented third-party services merely disguised behind codenames.--A user-supplied URL does not change the fact that StreamVault would be shipping provider-specific parsing logic.--Therefore:--```text-official/allowed provider adapter- ✅ appropriate for built-in support--generic Custom REST/JSON mapping- ✅ provider-neutral--undocumented provider-specific parser- ❌ not part of Plan 3 Play implementation-```--If the project later makes a separate distribution decision for an experimental GitHub-only adapter, it must remain isolated from the Play build.--That is outside this plan.-------# 45. No codenames as a compliance mechanism--Do not use:--```text-Provider X-Provider Y-```--to hide the identity of an integration.--Codenames do not materially change what the software does.--Provider names may be abstracted internally for architecture, but legal/terms decisions are based on actual behavior, not labels.-------# 46. Provider module isolation--Suggested architecture:--```text-sports/-├── providers/-│ ├── core/-│ │ ├── SportsProvider.kt-│ │ ├── SportsCapability.kt-│ │ ├── ProviderConfig.kt-│ │ ├── ProviderAuth.kt-│ │ ├── ProviderRegistry.kt-│ │ ├── ProviderResult.kt-│ │ └── ProviderHealth.kt-│ │-│ ├── matching/-│ │ ├── ProviderEventMatcher.kt-│ │ ├── ProviderEventLink.kt-│ │ └── SourceMergePolicy.kt-│ │-│ ├── custom/-│ │ ├── CustomProvider.kt-│ │ ├── CustomProviderConfig.kt-│ │ ├── JsonFieldMapping.kt-│ │ └── RequestTemplate.kt-│ │-│ └── <known-provider>/-│ ├── <Provider>Adapter.kt-│ ├── <Provider>Api.kt-│ ├── <Provider>Mapper.kt-│ └── <Provider>Models.kt-```--Adapt to the actual StreamVault module structure.--Do not restructure unrelated code solely to match this example.-------# 47. Provider registry--Use a registry.--Example:--```kotlin-interface SportsProviderFactory {- val descriptor: SportsProviderDescriptor-- fun create(- config: SportsProviderConfig- ): SportsProvider-}-```--Registry:--```kotlin-class SportsProviderRegistry(- factories: Set<SportsProviderFactory>-)-```--This avoids giant `when(providerType)` blocks across the app.-------# 48. Provider configuration versioning--Saved provider configuration must be versioned.--Example:--```kotlin-data class SportsProviderConfig(- val instanceId: String,- val providerType: String,- val configVersion: Int,- val enabled: Boolean,- val baseUrl: String?,- ...-)-```--Adapters may migrate their own configuration if fields change.--Do not make users re-enter API keys because a non-secret config format changed.-------# 49. Multiple accounts of the same provider--Design IDs so this can be supported eventually.--Example:--```text-Sport API — Personal-Sport API — Family-My self-hosted API-```--Even if v1 limits one account per provider, avoid using provider type itself as the unique configuration ID.--Use:--```text-provider instance ID-```-------# 50. Provider request client--Centralize:--```text-timeouts-user agent-credential injection-redaction-Retry-After handling-common response limits-network errors-JSON parse errors-```--Do not let every adapter reinvent unsafe HTTP behavior.--Still allow adapters to perform provider-specific calls.-------# 51. Response size protection--Custom endpoints could accidentally return enormous payloads.--Set reasonable safeguards for:--```text-maximum response size-maximum events parsed per request-maximum nested mapping work-pagination bounds-```--Fail gracefully.--Do not allow a broken custom endpoint to exhaust memory on Android TV.-------# 52. Time handling--Convert provider timestamps to `Instant`.--Support provider formats such as:--```text-ISO 8601-Unix seconds-Unix milliseconds-provider-specific documented format-```--For custom providers, require the user to specify format if automatic parsing is ambiguous.--Never treat a timezone-less timestamp as safely local without an explicit rule.-------# 53. League/team normalization reuse--Plan 3 must reuse Plan 2's normalization system.--Do not build provider-specific team alias systems inside each adapter unless the provider requires an initial translation.--Flow:--```text-provider raw team- ↓-provider mapper- ↓-ProviderCompetitor- ↓-shared TeamNormalizer- ↓-canonical Competitor-```--Provider IDs remain attached as source references.-------# 54. Broadcaster normalization reuse--Normalize:--```text-ESPN-ESPN HD-ESPN US-beIN Sports 1-beIN SPORTS 1 HD-Sky Sports F1-```--through the same channel/broadcaster normalization concepts developed in Plan 2.--Do not create separate broadcaster identity logic for every provider.-------# 55. Standings--Standings are provider data, not EPG data.--Model independently.--Example:--```kotlin-data class StandingsTable(- val league: CanonicalLeagueRef,- val season: String?,- val groups: List<StandingsGroup>,- val source: SportsSourceRef,- val updatedAt: Instant-)-```--Do not try to force every sport into identical columns.--Different sports may expose:--```text-W/L-points-goal difference-games behind-conference/division-driver championship points-constructor points-```--Use sport-aware presentation.-------# 56. Live scores--Scores are optional enrichment.--Example:--```kotlin-data class LiveScore(- val eventRef: CanonicalEventRef,- val competitorScores: Map<CanonicalCompetitorRef, String>,- val state: GameState?,- val clock: String?,- val period: String?,- val detail: String?,- val source: SportsSourceRef,- val updatedAt: Instant-)-```--Do not require numeric scores because:--```text-tennis-cricket-combat sports-racing-golf-```--may require different representations.--Allow provider-specific structured extensions later.-------# 57. Game-state normalization--Normalize provider states into a small canonical set:--```kotlin-enum class GameState {- SCHEDULED,- LIVE,- SUSPENDED,- DELAYED,- POSTPONED,- CANCELLED,- FINAL,- UNKNOWN-}-```--Preserve provider-specific detail:--```text-74'-Q3 04:12-Top 7th-Set 3-Rain Delay-```--as display detail.-------# 58. Provider event coverage--Different providers cover different sports/leagues.--A configured provider must not suppress valid EPG events outside its coverage.--Example:--```text-Provider covers:-football-basketball--EPG additionally contains:-WWE-local hockey-regional motorsport-```--Automatic mode should retain unmatched high-confidence EPG events.-------# 59. Capability-specific user choice--Advanced Settings can expose:--```text-Event discovery-Automatic / EPG / Provider A--Live scores-Automatic / Off / Provider A / Provider B--Standings-Automatic / Off / Provider B--Team metadata-Automatic / Off / Provider A-```--Only show providers that implement the capability.-------# 60. Simple mode vs advanced mode--Default Settings should stay understandable.--## Simple mode--```text-Sports Data Providers-+ Add provider--Use providers automatically [ON]-```--## Advanced--```text-Event source-Score source-Standings source-Metadata source-Provider priority-Refresh settings-```--Do not force ordinary users to understand capability routing.-------# 61. Quota display--If the provider exposes quota headers or account usage information, optionally show:--```text-Requests remaining-Reset time-Rate-limited until-```--Do not invent quota values when the API does not provide them.--Avoid polling merely to display quota.-------# 62. User-controlled polling--For expensive providers, optionally allow:--```text-Live score refresh:-Automatic-30 seconds-1 minute-2 minutes-5 minutes-```--But adapter/provider minimums and rate-limit safety must override unsafe selections.--Do not allow users to configure request rates that obviously violate provider rules.-------# 63. Background refresh--Do not add aggressive background polling in the first implementation.--Initial behavior should focus on:--```text-Sports screen open-event details open-user refresh-normal scheduled cache refresh-```--Background notifications/watchers can be designed later.-------# 64. Offline behavior--When offline:--```text-EPG Sports remains available from local data-cached external metadata remains available where appropriate-live score displays stale/last-updated state or is hidden-```--Do not block Sports because a configured provider cannot be reached.-------# 65. Attribution--Some providers may require attribution.--Provider descriptor/configuration should support:--```kotlin-data class ProviderAttribution(- val text: String,- val url: String?,- val placement: AttributionPlacement-)-```--Do not hide required attribution.--Settings should clearly identify the data source where required.-------# 66. Artwork policy--Do not assume a sports-data API's logos may automatically be redistributed or cached indefinitely.--Each provider integration should document:--```text-logo/artwork rights-hotlinking rules-cache rules-attribution-```--If unclear, do not ship artwork use merely because the JSON includes a URL.-------# 67. Terms/commercial review per provider--Before adding an official built-in adapter:--- [ ] verify developer/API documentation;-- [ ] verify commercial app use;-- [ ] verify BYOK use is allowed;-- [ ] verify client-side key usage expectations;-- [ ] verify redistribution/display rights;-- [ ] verify caching rules;-- [ ] verify attribution;-- [ ] verify rate-limit behavior;-- [ ] verify logo/artwork terms;-- [ ] document source URLs/date of review.--This review is separate from the provider's technical adapter.-------# 68. Testing architecture--Every provider adapter needs:--```text-parser fixture tests-error tests-auth tests where possible-pagination tests-status mapping tests-time parsing tests-capability tests-```--Use captured/anonymized static fixtures.--Do not hit live provider APIs in normal unit tests.-------# 69. Contract tests--Create provider-neutral contract tests.--Example:--Every `EventProvider` must:--- return stable provider event IDs;-- convert timestamps to UTC `Instant`;-- not throw on one malformed event if others are usable;-- expose declared capabilities accurately;-- sanitize errors;-- never expose credentials in exceptions.--Every `LiveScoreProvider` must:--- associate results with a provider event ID or matchable identity;-- report `updatedAt` where possible;-- normalize game state;-- tolerate missing score fields.-------# 70. Event resolver tests--Fixtures should cover:--```text-EPG + API exact match-EPG coverage starts before kickoff-API event with no EPG match-EPG event with no API match-team alias differences-league alias differences-kickoff shifted by 5/15/60 minutes-same teams twice in one day-multilingual EPG-provider duplicate events-replay vs live event-F1 race vs qualifying-fight card vs prelims-```-------# 71. Broadcast resolver tests--Cover:--```text-API broadcaster matches exact local channel-API broadcaster has no local channel-EPG mapping beats fuzzy broadcaster-event-named channel fallback-remembered user choice-wrong-region ambiguous broadcaster-multiple local variants-no playable result-```-------# 72. Provider Settings tests--Cover:--```text-add-edit-disable-remove-test connection-bad key-bad base URL-rate limit-OAuth cancelled-OAuth refresh failure-config migration-secret redaction-```-------# 73. Custom-provider tests--Cover:--```text-header API key-query API key-Bearer-Basic-array JSON root-nested JSON root-missing field-bad timestamp-bad JSON-huge response-unsupported pagination-mapping validation-```-------# 74. Diagnostics--Add provider diagnostics behind a dedicated debug tag or the existing Sports diagnostics mechanism.--Useful:--```text-provider instance ID-capability-request type-HTTP status-duration-cache hit/miss-events parsed-events rejected-event match confidence-source merge decision-rate-limit state-```--Never log:--```text-API key-Bearer token-password-OAuth refresh token-full sensitive URL query-credentials-```-------# 75. Migration from current Sports Hub--Do not rewrite current Sports events immediately.--Recommended migration:--## Step 1--Introduce provider interfaces with no active providers.--Existing EPG flow remains unchanged.--## Step 2--Wrap current EPG event production as a conceptual `EpgEventSource` / resolver input.--Do not force a large refactor if a lightweight adapter suffices.--## Step 3--Introduce source provenance.--## Step 4--Add ProviderEvent model + event matcher.--## Step 5--Add one legitimate BYOK provider as the reference adapter.--## Step 6--Add source strategy Settings.--## Step 7--Add live-score enrichment.--## Step 8--Add Custom Sports Provider.--Do not implement five providers at once before the abstraction is proven.-------# 76. First provider strategy--Choose one provider that has:--```text-clear documentation-user API keys-reasonable developer terms-events-live scores-good sport coverage-stable schema-```--Use it to validate the framework.--The purpose of the first adapter is not maximum provider count.--It is to prove:--```text-BYOK config-auth-events-matching-scores-caching-error handling-settings-```--Then generalize.-------# 77. Recommended implementation phases--## Phase 3.1 — Provider core--- [x] `SportsCapability`-- [x] provider descriptor-- [x] provider instance/config model-- [x] secure credential storage-- [x] provider registry-- [x] provider health/error model-- [x] common HTTP client behavior-- [x] provider configuration versioning-- [x] tests--Implemented 2026-10-17. See [Phase 3 implementation record](Sports-PLAN-3-IMPLEMENTATION.md)-for boundaries, persistence/transport policy, verification, and remaining phases.--No external provider required yet.-------## Phase 3.2 — Capability interfaces--- [x] `EventProvider`-- [x] `LiveScoreProvider`-- [x] `StandingsProvider`-- [x] `BroadcastProvider`-- [x] metadata provider interfaces-- [x] provider-neutral DTOs-- [x] contract tests--Implemented 2026-10-17. See [Phase 3 implementation record](Sports-PLAN-3-IMPLEMENTATION.md)-for contracts, fixtures, validation, and the Phase 3.3 handoff.-------## Phase 3.3 — Source provenance and event resolver--- [x] `SportsSourceRef`-- [x] provider event link model-- [x] source merge policy-- [x] event resolver-- [x] event/provider identity matching-- [x] event-link cache-- [x] eventStart vs broadcastStart distinction-- [x] tests--The Phase 3.3 implementation and focused resolver tests are complete. See-`Sports-PLAN-3-IMPLEMENTATION.md` for coverage and validation.-------## Phase 3.4 — Provider settings--- [x] Data Providers list-- [x] Add provider-- [x] credential entry-- [x] base URL override where allowed-- [x] Test connection-- [x] disable/remove-- [x] capability display-- [x] secret-safe UI-- [x] tests--Focused ViewModel tests cover saving credentials in the dedicated store and-testing a draft connection without persisting its credentials.-------## Phase 3.5 — First official BYOK adapter--- [x] provider review/documentation-- [x] API client-- [x] auth-- [x] events-- [x] live scores-- [x] mappings-- [x] cache policy-- [x] error policy-- [x] fixtures/tests--Implemented 2026-10-17 with TheSportsDB as the single reference adapter. See-[`sports/providers/thesportsdb.md`](sports/providers/thesportsdb.md) for the-technical and terms review. Its current scope is events, live scores, and game-status; source selection and Sports Hub presentation remain in later phases.-Plan 4 still owns the production release/compliance gate and additional-provider-specific capabilities.--Do not add more providers until this adapter validates the abstractions.-------## Phase 3.6 — Event source selection--- [x] Automatic-- [x] EPG-- [x] configured EventProvider-- [x] provider capability filtering-- [x] fallback to EPG in Automatic on provider failure where safe-- [x] preserve unmatched EPG events outside API coverage-- [x] tests--Phase 3.6 now stores source selection independently from provider credentials,-supports per-account league scopes for APIs that require them, and routes event-requests through enabled providers that declare `EVENTS`. See-[`Sports-PLAN-3-IMPLEMENTATION.md`](Sports-PLAN-3-IMPLEMENTATION.md) for behavior-and validation details.-------## Phase 3.7 — API-first broadcast matching--- [x] API event -> EPG event matching-- [x] provider broadcaster -> local broadcaster matching-- [x] local EPG mapping remains preferred where available-- [x] Provider-neutral fallback channel matcher from Plan 2-- [x] manual correction integration-- [x] tests--Implemented 2026-10-17. Provider event broadcasters now participate in the-existing local-channel fallback and manual correction flow. See-[`Sports-PLAN-3-IMPLEMENTATION.md`](Sports-PLAN-3-IMPLEMENTATION.md) for matching-rules and verification.-------## Phase 3.8 — Live-score enrichment--- [x] score source selection-- [x] event-link cache reuse-- [x] score/status/clock UI-- [x] stale-state handling-- [x] live refresh policy-- [x] quota-aware caching-- [x] provider failure degradation-- [x] tests--Implemented 2026-10-17. See-[`Sports-PLAN-3-IMPLEMENTATION.md`](Sports-PLAN-3-IMPLEMENTATION.md) for-selection, refresh, failure, and verification details.-------## Phase 3.9 — Standings and metadata--- [x] standings source selection-- [x] sport-aware tables-- [x] team/league metadata enrichment-- [x] attribution-- [x] cache policy-- [x] tests--Implemented 2026-10-17. Provider standings and metadata can be selected-independently, preserve provider provenance, and degrade to cached stale data-when a provider fails. See-[`Sports-PLAN-3-IMPLEMENTATION.md`](Sports-PLAN-3-IMPLEMENTATION.md) for routing,-cache policy, localization, and verification details.-------## Phase 3.10 — Custom Sports Provider--- [x] custom provider config-- [x] auth modes-- [x] endpoint templates-- [x] JSON mapping-- [x] mapping validation-- [x] safe response limits-- [x] event support-- [x] live-score support-- [x] optional standings reviewed and deferred because this mapping model does not cleanly represent provider-specific table structures-- [x] tests--Implemented 2026-10-17. The generic adapter supports declarative HTTPS JSON event and optional live-score mappings, encrypted definitions and credentials, bounded selectors and response mapping, five authentication modes, and same-origin endpoint templates. Pagination, arbitrary headers/scripts, OAuth, and standings remain out of scope for this first version. See [`sports/custom-provider.md`](sports/custom-provider.md) for the configuration schema and current limits.-------## Phase 3.11 — Multiple-provider routing--- [x] provider priority-- [x] capability-specific provider selection-- [x] Automatic provider choice-- [x] field/source provenance-- [x] conflict policy-- [x] partial provider failure-- [x] tests--Implemented across Phases 3.6–3.10. Event, score, standings, and metadata each use capability-aware account selection. Automatic selection follows provider priority and falls through typed failures; explicit account choices remain pinned. Event identity matching controls merges, EPG playback fields remain authoritative, and merged provider fields retain source provenance. Scores, standings, and metadata keep their own retry and stale-cache behavior. See [`Sports-PLAN-3-IMPLEMENTATION.md`](Sports-PLAN-3-IMPLEMENTATION.md) for routing and conflict details.-------## Phase 3.12 — Production hardening--- [x] Android TV performance-- [x] large event-set performance-- [x] provider cache validation-- [x] secret redaction audit-- [x] offline behavior-- [x] rate-limit behavior-- [x] settings UX review-- [ ] Terms/attribution checklist for each built-in adapter — deferred to Plan 4's built-in-provider release gate-- [x] Play-build dependency review--The Android TV measurements and navigation review are recorded in-[`Sports-PERFORMANCE.md`](Sports-PERFORMANCE.md) and-[`Sports-UI-REVIEW.md`](Sports-UI-REVIEW.md). The current emulator session exposes-`emulator-5554`; the earlier `emulator-5590` device is not attached in this-session, so the existing device evidence was retained rather than repeated.-Provider cache, offline, rate-limit, redaction, and large-feed evidence is-recorded in [`Sports-PLAN-3-IMPLEMENTATION.md`](Sports-PLAN-3-IMPLEMENTATION.md).-Provider terms and attribution remain in Plan 4, whose release gate owns review-of each built-in adapter.-------# 78. What is explicitly not in Plan 3--Do not implement:--```text-StreamVault-hosted shared API keys-StreamVault-owned sports backend-pirated sports streams-automatic scraping-DRM/token bypass-undocumented provider adapters disguised with codenames-arbitrary user JavaScript-arbitrary shell commands-API keys logged to diagnostics-external provider controlling playback URLs-```-------# 79. Success criteria--Plan 3 succeeds when all of the following are true.--## No provider--```text-EPG Sports works exactly as before.-```--## Score-only provider--```text-EPG provides event/channel-API adds score/status-```--## Event provider without broadcasters--```text-API provides fixtures/events-EPG + Plan 2 channel matcher finds playback-```--## Event provider with broadcasters--```text-API provides event + broadcaster-EPG/local channels corroborate and resolve playback-```--## API event absent from EPG--```text-event appears-fallback channel matching runs-manual channel selection available-event remains visible even if no channel is found-```--## Weak EPG--```text-API identity repairs generic EPG metadata-without losing EPG broadcast window/channel-```--## Multiple providers--```text-capability routing is deterministic-source provenance is preserved-one provider failure does not break Sports-```--## Custom provider--```text-advanced user can configure a documented/self-hosted JSON sports source-without StreamVault shipping a new adapter-```-------# 80. Final design principles--1. **The Sports Hub must always work without an external API.**-2. **Providers are capability-based, not all-or-nothing.**-3. **Event discovery may be EPG-first or API-first.**-4. **Playback always comes from the user's own StreamVault TV sources.**-5. **An API broadcaster is metadata, not a stream.**-6. **EPG broadcast time and real event kickoff are separate concepts.**-7. **Multiple sources must preserve provenance.**-8. **User-supplied credentials belong to the user and use their quota.**-9. **A provider failure must degrade gracefully.**-10. **Plan 2 normalization/matching is reused, not duplicated.**-11. **Generic Custom REST/JSON support is preferable to hidden provider-specific reverse engineering.**-12. **Every built-in provider requires a technical and terms/commercial review.**-13. **Do not sacrifice the existing local Sports experience to add API features.**-14. **Automatic should be the simple default; advanced source routing should remain available.**-------# 81. Immediate execution order--The agent should **not start Plan 3 immediately if Plan 2's core improvements are still incomplete**.--Recommended order:--```text-1. Finish Plan 2 verification + tests-2. Finish Plan 2 event model / non-team parsing / dedupe-3. Finish Plan 2 fallback channel matching + manual correction-4. Verify Plan 2 on a real provider/EPG-5. Begin Plan 3 provider core-6. Implement one legitimate BYOK provider-7. Add API-first event mode-8. Add live scores-9. Add Custom REST/JSON-10. Add multiple-provider routing-```--This minimizes rework.--The most important dependency is:--> **Do not build external event matching until the canonical local event identity and normalization system are trustworthy.**--That identity layer is what allows EPG, API events, live scores, broadcaster metadata, and user channel mappings to meet cleanly.diff --git a/docs/Sports-PLAN-3-IMPLEMENTATION.md b/docs/Sports-PLAN-3-IMPLEMENTATION.mddeleted file mode 100644index a1bf9fd3..00000000--- a/docs/Sports-PLAN-3-IMPLEMENTATION.md+++ /dev/null@@ -1,492 +0,0 @@-# Sports Plan 3 implementation--## Phase 3.1 — Provider core (2026-10-17)--The provider core is separate from the existing feature/live Sports implementation.-The local Sports repository, canonical event identity, channel matching, playback,-and settings have not been changed by this phase. No external adapter is registered-and no provider requests run when Sports opens.--### Boundaries--- `domain/.../sports/provider` owns capabilities, authentication declarations,- provider descriptors, account configurations, registry/factory contracts,- health, typed results, and the persistence contract.-- `data/.../sports/provider` owns encrypted persistence and HTTP transport.-- At this phase the factory set was empty. The registry, singleton encrypted- store, and dedicated client use the existing app user-agent identity. The- TheSportsDB reference adapter is registered with `@IntoSet` in Phase 3.5.-- Sports data capabilities contain no stream URL or playback capability.-- Provider labels and error presentation remain for the settings phase. There- are no new user-facing strings in this phase; internal enum names and exception- markers must be mapped to localized resources before being displayed.--### Configuration and credentials--Provider type IDs identify adapters; instance IDs identify individual accounts.-Adapter configuration versions are independent of the storage-envelope version.-Factories can migrate old configuration versions while preserving account and-type identity. Future versions, unsupported migrations, duplicate adapter types,-and prohibited endpoint overrides fail validation.--The store writes one encrypted envelope atomically using the existing-`CredentialCrypto` implementation. It lives at-`Context.noBackupFilesDir/sports_providers.enc`, outside Room, DataStore,-preferences export, and backup. The entire envelope is encrypted, including-endpoint metadata and usernames. Failed encryption does not replace the prior-file; malformed/future envelopes are errors rather than an empty account list.-No plaintext write fallback is allowed. Reads and writes are bounded to 256 KiB-of encrypted data, with a 128 KiB plaintext write limit.--Configuration updates preserve the existing secret when no replacement is-provided. Credential reads are explicit and separate from configuration reads.-Removing an instance deletes its credentials as well. Credentials have a redacted-string representation; storage errors carry no raw cause or server text.--Base URLs currently require HTTPS and prohibit inline credentials, query strings,-and fragments. Authentication declares key placement independently of endpoint-configuration. OAuth2 is an adapter declaration and bearer transport only at this-stage; authorization, refresh, PKCE/device-code flows are not implemented.--### HTTP behavior--The dedicated OkHttp client has no shared request logger, disk cache, cookies, or-automatic redirects. It supports no authentication, header/query API keys,-Bearer, Basic, and adapter-managed OAuth access tokens. HTTPS is the default;-the transport has an explicit cleartext opt-in for future self-hosted adapters,-but configuration validation currently remains HTTPS-only.--Connect/read/overall timeouts are 15/20/30 seconds. Responses are bounded to 2 MiB-by default (including decompressed/chunked payloads), configurable up to 8 MiB.-Errors return categories and optional status/retry time, without URLs, response-bodies, or exception messages. `Retry-After` supports delay seconds and HTTP dates.-Cancellation cancels the underlying call and parser cancellation propagates.--There are no automatic retries or polling in this phase. Adapters/capability-repositories must use the typed failures and retry time to implement bounded-backoff, quota-aware caching, stale-data policy, and refresh scheduling later.-No real provider has been contacted.--### Verification--Focused tests cover deterministic capability filtering, multiple accounts,-configuration migration, endpoint validation, health recovery, credential-persistence/rotation/removal, failed writes, corrupt/future storage, auth-injection, redirect isolation, error sanitization, rate limiting, cancellation,-and fixed/chunked/gzip response limits. Storage tests use fake crypto with-Robolectric; they test the persistence boundary, not Android hardware Keystore.--The focused suites passed: 27 tests, zero failures/errors (10 domain, 6 storage,-11 HTTP). Commands:--```text-gradlew.bat :domain:test --tests "com.streamvault.domain.sports.provider.*"-gradlew.bat :data:testDebugUnitTest --tests "com.streamvault.data.sports.provider.*"-```--An initial storage test detected coroutine debug stack recovery attaching a-cause to the sanitized exception marker. The marker now explicitly initializes-its null cause; the full focused suite passed on the rerun.--`:app:assembleDebug` also passed, including app-level Hilt dependency generation-and compilation. `git diff --check` passed. No emulator install or playback-validation was performed: this phase adds no screen behavior or playback changes.--### Phase 3.1 handoff--Phase 3.2, recorded below, adds capability-specific interfaces and provider-neutral-DTOs before event resolution or UI integration. Reuse the Plan 2 identity and normalization-boundaries when Phase 3.3 starts. Keep the outstanding Plan 2 device checks and-the documented WSL stream failures visible; this foundation does not resolve or-reclassify those findings.--## Phase 3.2 — Capability interfaces (2026-10-17)--All ten declared capabilities now have independent interfaces in the domain-module: events, live scores, game status, standings, broadcasters, team metadata,-league metadata, artwork, lineups, and statistics. Adapters implement only the-interfaces they support. There are no mandatory unsupported-operation methods.--The registry checks every created adapter's declared capabilities against its-implemented interfaces. A descriptor can advertise a subset of the implemented-interfaces (for example an account tier), but implementing an interface alone-does not enable a capability for routing. Configuration priority and eligibility-still use explicit declarations.--### Provider-neutral data--`SportsProviderModels.kt` and `SportsProviderCapabilities.kt` define request and-response contracts without Gson, vendor JSON models, Android UI, local channel-IDs, or playback URLs. External IDs are scoped to the receiving provider account-instance. Requests use a half-open competition-time interval or explicit external-IDs; adapters own their API pagination and batching.--Events retain raw competitor/league names and optional session, status, and-kickoff/end times. Times are `Instant`; missing kickoff remains unknown. These-fields do not represent the EPG coverage window. Plan 2 alias and canonical-event-normalization remain the resolver's responsibility in Phase 3.3.--Scores support nullable text values, optional game state/clock/period, and-optional update times. Standings contain groups with independent named column-keys and nullable text cells, allowing tied rankings and sport-specific tables.-Broadcasters are names/region/language/type metadata only. Artwork is a separate-typed HTTPS URI whose string representation omits the URL; loading and caching-remain subject to the future adapter's rights/attribution review.--### Shared adapter mapping--`parseProviderTimestamp` supports explicitly selected offset ISO timestamps,-Unix seconds, and Unix milliseconds. It preserves fractional seconds and never-guesses the device timezone or numeric unit. Other provider-specific formats must-be explicitly converted by their adapter. Call it inside the HTTP decoding or-item-mapping error boundary so raw parsing exceptions never reach presentation.--`mapProviderItems` retains valid records, counts rejected records without keeping-their raw values or exceptions, and propagates cancellation. An entirely malformed-nonempty feed returns `INVALID_RESPONSE`; a valid empty feed returns a successful-empty batch. Mapping work is bounded to 10,000 attempted records by default,-configurable from 1 to 100,000, counting invalid records too. Exceeding that budget-returns `RESPONSE_TOO_LARGE`, leaving adapters responsible for smaller API pages.--### Contracts and verification--Reusable `EventProviderContract` and `LiveScoreProviderContract` test suites live-under `data/src/test/.../sports/provider/contract`. Future data-layer adapters can-subclass them, supply static fixture scenarios and expected IDs/times, and use-MockWebServer rather than a live account. The suites exercise stable event IDs,-UTC kickoff/update conversion, capability declarations, mixed valid/invalid-records, empty versus invalid event feeds, optional score fields, non-numeric-scores, normalized live state, and sanitized authentication failures.--Test-only fixture adapters run those suites through the real shared HTTP client-and mapping helper using JSON resources in `data/src/test/resources/sports/providers`.-They are not registered in production. Additional domain tests cover all-capability-declaration rejection, undeclared interface eligibility, fractional timestamps,-timezone-less rejection, cancellation, mapping budgets, non-team sessions,-standings schemas, text scores, and artwork URL redaction.--Validation passed:--```text-gradlew.bat :domain:test --tests "com.streamvault.domain.sports.provider.*" :data:testDebugUnitTest --tests "com.streamvault.data.sports.provider.*"-gradlew.bat :app:assembleDebug-```--The combined provider suites now have **52 tests, zero failures/errors**, including-25 new checks for this phase. The debug APK built successfully. No user-facing-strings, real provider connections, UI behavior, or playback behavior changed;-no emulator installation or playback validation was performed.--## Phase 3.3 — Source provenance and event resolver (2026-10-17)--`SportsEventProvenance.kt` defines account-scoped provider references, EPG-programme references, field-level source values, independent event and broadcast-times, source selection, and deterministic field precedence. EPG keeps control-of descriptions and its broadcast window. A selected event provider can replace-title, league, and competition times only after a high-confidence identity match;-the selected score and metadata providers have separate roles.--`SportsProviderEventMatcher` reuses Plan 2's sport, team-alias, league, and title-normalization. It rejects known sport, team, league, and session conflicts, skips-replays and studio programming, requires kickoff to fall within the EPG broadcast-window (with a 30-minute edge allowance) for team fixtures, and needs at least-0.8 confidence with a 0.12 uniqueness margin before linking. Broadcaster names-are only corroborating metadata and never become playback routes.--`SportsProviderEventResolver` preserves unmatched EPG events and selected-provider-only events, matches score-provider events independently, and retains-the source for each accepted value. The account-scoped in-memory link cache is-bounded to 10,000 links, expires links after seven days, rejects kickoff drift-over 60 minutes, and evicts after three recorded failures. The resolver is a-foundation for later source-selection and UI work; this phase does not change-the Sports Hub presentation or contact an external provider.--Focused resolver tests now verify high-confidence event merging, source-provenance, preservation of the EPG broadcast window and description, cached-event links, and retention of unmatched provider events as data-only records.-Validation passed:--```text-:feature:live:testDebugUnitTest --tests "com.streamvault.feature.live.sports.SportsProviderEventResolverTest"-```--Both tests passed. `:app:assembleDebug` also passed. No playback behavior-changed.--## Phase 3.4 — Provider settings--Settings now has a Sports category with a Data Providers page. It lists saved-accounts and registered adapters, shows each adapter's declared capabilities,-and supports adding, editing, testing, enabling, disabling, and removing an-account. API keys, bearer secrets, and Basic credentials are masked during-entry and remain in the encrypted sports-provider store; the normal account-list never reads or displays them. Custom endpoints are shown only for-descriptors that allow overrides and accept HTTPS URLs without embedded-credentials or query parameters.--Adapters can implement `SportsProviderConnectionTester` to provide a typed,-sanitized connection result. The settings page reports when an adapter does not-offer a test, and shows a removable unavailable account if its adapter is no-longer registered. The registry includes the TheSportsDB reference adapter,-which requires a user-provided Premium API key.--All new settings strings are translated in the 38 advertised locales. The-Phase 3.4 implementation and focused ViewModel tests are complete. Tests verify-credential storage on save and connection testing of a draft without persisting-it. The provider name and Premium API key label added for Phase 3.5 are also-translated in all 38 advertised locales. Provider selection in the Sports Hub-and API-first broadcast matching remain later phases.--Verification for Phase 3.4: `:feature:settings:compileDebugKotlin` and-`:app:assembleDebug` passed. Resource XML and formatting placeholders were-checked in all 38 advertised locales. Focused settings tests passed:--```text-:feature:settings:testDebugUnitTest --tests "com.streamvault.feature.settings.presentation.SportsProviderSettingsViewModelTest"-```--Both tests passed; the full Settings suite was not run in this continuation.--## Phase 3.5 — TheSportsDB reference adapter (2026-10-17)--TheSportsDB was selected to satisfy Plan 3's requirement for one legitimate-BYOK adapter. Plan 3.5 uses it to exercise the provider contracts; Plan 4 still-owns release/compliance gating and production expansion.--The adapter uses the Premium V2 base URL and `X-API-KEY` header. It implements-connection testing, league-season schedule lookup, live-score lookup, and game-status mapping. Schedule requests require a numeric league ID because the-provider exposes schedules by league and season; event-source selection must-therefore supply league IDs in Phase 3.6. Returned events are filtered by the-requested time range and optional sport. Schedule timestamps without offsets-are interpreted as UTC, as documented in-[`sports/providers/thesportsdb.md`](sports/providers/thesportsdb.md).--Seasons are cached for 24 hours, schedules for 15 minutes, and live scores for-two minutes in a bounded process-local cache. Live scores are fetched from the-provider's all-sports endpoint and filtered by requested external event IDs.-The adapter does not implement standings, broadcasters, artwork, or source-selection, and it does not feed data to the Sports Hub yet.--Verification passed:--```text-:data:testDebugUnitTest --tests "com.streamvault.data.sports.thesportsdb.*" --tests "com.streamvault.data.sports.provider.*"-:app:assembleDebug-```--The focused run passed **45 tests**. The two new Settings labels (provider name-and Premium API key) are present and translated across all 38 advertised-locales. The current terms review requires a paid subscription for app-store-apps, source mention, and separate artwork-rights review; production release-approval and point-of-use Sports Hub attribution remain Plan 4 / later-phase-work. No live API account or playback path was used.--## Phase 3.6 — Event source selection--Sports event source is now a persisted setting with Automatic, TV Guide / EPG,-and enabled event-provider account choices. Automatic orders accounts by their-configured priority, filters through the registry's declared `EVENTS`-capability, and moves to the next provider after a typed request failure. If no-provider succeeds, it uses the existing EPG path. EPG mode skips provider-requests, while a specific account selection only tries that account.--Provider accounts now store an optional, bounded list of provider-neutral-league IDs. Event adapters receive one request per configured league, and-adapters that support broad discovery receive one request without a league ID.-This gives TheSportsDB the league scope its schedule API requires without-putting TheSportsDB identifiers into the shared event model. The value is part-of encrypted provider configuration; the source choice remains in normal app-preferences and contains no credentials.--Provider events are resolved against assembled EPG events. Strong matches can-contribute selected event metadata while EPG descriptions, broadcast windows,-and channel choices remain intact. Unmatched EPG events stay in the list, and-unmatched provider events appear as data-only events with no channel attached.-The existing fallback channel matcher continues to run for EPG events that lack-a direct playable choice. Provider event scopes and source choice participate-in the local event-index cache key.--All five new Settings strings are translated and XML-checked in the 38-advertised locales. Focused tests cover EPG-only routing, capability and enabled-account filtering, provider priority fallback, multi-league requests and event-deduplication, explicit account selection, resolver provenance and unmatched-events, persisted source preferences, provider-scope storage, and existing-Sports Hub behavior. The focused run passed **26 tests** across the live,-settings, and data modules with zero failures. `:feature:live:verifyFeatureLiveBoundary`-and `:feature:settings:verifyFeatureSettingsBoundary` passed. The final-integration build passed with `:app:assembleDebug`.--## Phase 3.7 — API-first broadcast matching--Provider events continue to resolve against EPG events through the existing-confidence-aware matcher and provider-event link cache. The selected event-provider is also selected for broadcaster metadata, so its provider-neutral-`ProviderBroadcaster` values remain attached to matched and unmatched events.--When an event has no playable EPG mapping, broadcaster names are normalized-with the shared channel normalizer and matched exactly against the user's-playable local channel catalog. These matches join the existing Plan 2 event-and date signals, and the existing manual picker can search, select, and-remember the local channel. Playable EPG mappings remain first-choice; the-fallback never creates or accepts a provider-supplied playback URL. Provider--only events can use the same local catalog matching path.--Verification passed: all **188** `:feature:live:testDebugUnitTest` tests passed-with zero failures or errors, including 16 channel-matcher tests, 3 provider-resolver tests, and 11 Sports Hub ViewModel tests. The feature boundary check-passed, `git diff --check` was clean, and `:app:assembleDebug` succeeded. No-user-facing strings or live TV playback behavior changed.--## Phase 3.8 — Live-score enrichment (2026-10-17)--Live-score source is an independent setting with Automatic, Off, and enabled-provider-account choices. Automatic prefers the selected event account when it-also provides events and live scores, then follows provider priority. A-different score account must expose events as well as scores so its-provider-scoped event IDs can be matched safely to local fixtures.--The score router reuses the event load when both source roles use the same-account. For a separate account it loads that provider's event records and-reuses the existing confidence-checked event-link cache to join scores to EPG-fixtures. The sports cards now show competitor scores, provider status, period,-and clock. A live provider status also drives the existing localized live-badge; retained scores and clocks are dimmed while stale.--The repository checks for score updates every 60 seconds while a live fixture-is visible (and continues refreshing the On now range). Score responses are-cached for two minutes, score-provider event lists for five minutes, and a-last successful score response can be retained as stale for up to ten minutes-after provider failure. Failed sources are held until the provider's `retryAt`-or for two minutes when it supplies none. Automatic selection falls through-failed providers; an explicit account selection stays on that account.-Requests and response mapping remain provider-neutral, while each adapter-continues to own its API limits and typed failures.--The two new Settings labels are translated and XML-checked in all 38 advertised-locales. Verification passed: **195** `:feature:live:testDebugUnitTest` tests,-**1,396** `:data:testDebugUnitTest` tests, all 3 focused-`SportsProviderSettingsViewModelTest` tests, and `:app:assembleDebug`. The-settings ViewModel tests cover source selection, while router and resolver-tests cover independent accounts, event-link reuse, two-minute refresh-caching, automatic fallback, provider retry times, and stale-score retention.-The full Settings test task still reports one `SettingsLocalizationCoverageTest`-failure in the separate `settings_redesign.xml` resources; the score labels use-regular `strings.xml` resources and are present in each advertised locale.--## Phase 3.9 — Standings and metadata (2026-10-17)--Standings and team/league metadata now have independent Automatic, Off, and-provider-account preferences. Standings routing uses the selected event-provider's league ID only when the standings adapter has the same provider-type; otherwise it uses that account's configured league scope. Responses-must match the requested league identity. Provider-defined groups, column-labels, and cell values are retained so different sports can use different-table shapes. Standings are loaded on demand from an event details view to-avoid unnecessary quota use.--Standings results are cached for 30 minutes, retained as stale for up to 12-hours after a failure, and retried after the provider's `retryAt` or a-five-minute default cooldown. The in-memory cache is bounded to 64 league-entries. Metadata lookup requires the provider type to match the event source,-so provider-scoped team and league IDs never cross API namespaces. Requests-are bounded to 24 teams and 12 leagues per enrichment pass. Successful team-and league metadata is cached for 24 hours and can remain stale for seven days;-failed sources cool down for the supplied `retryAt` or ten minutes by default.-Metadata caches are bounded to 256 teams and 64 leagues.--Selected metadata is merged into the canonical event with field-level source-references and provider attribution. The event details view shows available-team/league metadata, the metadata source, and the provider's standings table.-Disabling or removing a selected provider resets affected capability choices-to Automatic. The two new Settings and ten Sports Hub labels are translated-and placeholder-checked in all 38 advertised locales.--Verification passed: **201** `:feature:live:testDebugUnitTest` tests, all **4**-focused `SportsProviderSettingsViewModelTest` tests, and the-`PreferenceBackupRegistryTest`. `:app:assembleDebug` succeeded, and-`git diff --check` was clean. The standings and metadata router tests cover-provider selection, provider-ID namespace safety, scoped lookup, dynamic-table preservation, successful caching, stale fallback, event provenance,-attribution, and Off mode.--## Phase 3.11 — Multiple-provider routing audit (2026-10-17)--This phase was delivered incrementally in Phases 3.6–3.10. Event, live-score,-standings, and metadata choices are independently capability-filtered. In-Automatic mode, event requests follow priority and move to the next eligible-provider after failure; score, standings, and metadata routers apply their-own account preferences, fallback, retry, and stale-data policies. Explicit-account selection does not silently switch sources.--The event resolver merges provider fields only after confidence-aware identity-matching. EPG broadcast timing, descriptions, and playable channel choices-remain authoritative; selected provider title, league, event timing, status,-score, and broadcaster data retain field-level source references. Unmatched-provider events remain data-only, so provider payloads cannot become playback-URLs. The full **201-test** `:feature:live:testDebugUnitTest` suite passed with-zero failures, including source routing, conflicts, provenance, partial-failures, provider-ID namespace safety, and stale fallback.--## Phase 3.10 — Custom JSON sports provider (2026-10-17)--Custom provider accounts store their declarative JSON mapping in the existing-encrypted, no-backup sports-provider envelope. Credentials remain a separate-encrypted field. The mapping supports HTTPS event feeds and optional live-scores, with `none`, API-key header, API-key query, Bearer, and Basic-authentication. Account capabilities and display names come from the saved-definition, so an account without a score mapping does not appear as a score-source and multiple custom APIs are distinguishable in Settings.--Endpoint templates accept bounded date, league, sport, and event-ID-placeholders. They append beneath the configured API base path, percent-encode-values, and remain on the same HTTPS host and port. Field selectors are-bounded dot-separated JSON object paths; the provider executes no user code-and follows no supplied URL. The shared client caps each response at 2 MiB;-the adapter also caps configuration, selector depth, scalar lengths, and-mapped event/score counts. Pagination and generic standings remain deferred.-The configuration schema and example are in-[`sports/custom-provider.md`](sports/custom-provider.md).--The new three Settings labels are translated and XML-checked in all 38-advertised locales. Verification passed all **201** Sports Hub unit tests,-all **205** domain tests, the **24** focused custom-provider, encrypted-store,-and HTTP-client tests, and all **5** focused provider-settings ViewModel-tests. `:feature:live:verifyFeatureLiveBoundary`,-`:feature:settings:verifyFeatureSettingsBoundary`, and-`:app:assembleDebug` passed. `git diff --check` was clean.--## Phase 3.12 — Production hardening (2026-10-17)--The large-feed resolver now indexes guide events by canonical competitor pair-and title, validates cached guide links by local ID, and indexes provider-assignments and scores before merging. A synthetic regression case with 1,400-guide events and 400 provider events completes in **0.096 seconds** in the JVM-test run, while retaining ambiguity and conflict checks. Resolver duration is-also available through the bounded `SportsPerf` diagnostics stages.--The shared built-in response cache now partitions entries by account, canonical-endpoint, and a SHA-256 credential fingerprint. Cache keys contain no raw-credentials. Regression tests confirm event/season and score responses do not-cross credential changes, nor do responses cross endpoint changes; bounded-cache size and TTL behavior remain covered. The provider HTTP client maps-offline I/O to typed network failures, maps HTTP 429 and parses both supported-`Retry-After` forms, and exposes neither response bodies nor exception messages-in failure results. Router tests cover network/rate-limit fallback and stale-data behavior. The credentials object redacts `toString`; a source audit found-no sports-provider URL, API key, or credential logging.--The Settings source review covered capability-filtered account choices, custom-provider name display, multiline JSON editing, test/save flow, and TV focusable-controls. The three new strings were verified as nonempty translations in all-38 advertised locales. A repeat device review was not possible in this session-because only `emulator-5554` was attached; the prior Android TV measurements-and D-pad review remain linked from the Plan 3 checklist.--The Play release dependency review found no `mockwebserver` dependency in-`:app:releaseRuntimeClasspath`. Full verification passed:-`:data:testDebugUnitTest` (**1,406 tests**),-`:feature:live:testDebugUnitTest` (**202 tests**), both feature-boundary checks,-and `:app:assembleDebug`, all with zero test failures. The remaining terms and-attribution review is explicitly deferred to Plan 4's release gate for built-in-providers.diff --git a/docs/Sports-PLAN-4-Built-in-Providers.md b/docs/Sports-PLAN-4-Built-in-Providers.mddeleted file mode 100644index 99fce130..00000000--- a/docs/Sports-PLAN-4-Built-in-Providers.md+++ /dev/null@@ -1,2602 +0,0 @@-# StreamVault Sports Hub — PLAN 4: Built-in Sports API Providers--**Research date:** 2026-10-16-**Depends on:** Sports Plan 2 and Sports Plan 3-**Purpose:** Define which real sports-data APIs StreamVault should support as first-class built-in providers, what each provider is allowed to do, what the user must supply, and the implementation/release order.--> This document is an engineering/product plan based on the providers' published documentation and terms reviewed on the research date above. It is not legal advice. Provider terms can change; every built-in provider must pass the release-gate checklist in this document again before shipping.-------# 0. Why this is Plan 4--The intended progression is:--```text-PLAN 1-EPG-first Sports Hub- ↓-PLAN 2-Real-world IPTV resilience-(IPTV resilience improvements)- ↓-PLAN 3-Generic provider framework-(BYOK, capability routing, API-first/EPG-first/Automatic)- ↓-PLAN 4-Concrete built-in provider adapters-(real providers, real auth, real terms)-```--Do **not** call this Plan 2.5.--Plan 2 improves the local Sports engine.--Plan 3 defines the generic provider system.--Plan 4 fills that system with vetted provider adapters.-------# 1. Core product decision--StreamVault should support two kinds of sports-data integrations.--## 1.1 Built-in providers--StreamVault knows:--```text-provider name-base URL-authentication method-endpoints-pagination-response schema-capabilities-cache policy-rate-limit behavior-error behavior-attribution requirements-```--The user supplies only the credentials/account information required by that provider.--Example:--```text-Add Provider- ↓-TheSportsDB- ↓-API key: ••••••••••- ↓-Test connection- ↓-Connected-```--No endpoint entry.--No JSON mapping.--No technical configuration for ordinary users.--## 1.2 Custom REST/JSON provider--This remains the advanced Plan 3 option for unsupported/self-hosted APIs. The settings form offers an editable starter mapping and setup instructions; the complete schema and examples are in [`sports/providers/custom-json.md`](sports/providers/custom-json.md).--Users may configure:--```text-base URL-auth-endpoint templates-field mappings-```--The built-in provider list must **not** be replaced by a generic endpoint editor.-------# 2. Provider status taxonomy--Every investigated provider belongs to one of these groups.--## GREEN — first-class candidate--Published terms/docs are sufficiently clear that the provider is a strong candidate for a built-in StreamVault BYOK adapter, subject to the normal release review.--## GREEN-WITH-GATE — strong candidate, one material question remains--Technically and commercially promising, but StreamVault should obtain clarification or satisfy a specific term before enabling the adapter in production.--These colors track terms and release rights, not test maturity. The app marks TheSportsDB and Highlightly as **Beta** while live-account validation is unavailable; Beta does not alter either provider’s compliance gate.--## YELLOW — technically useful but rights/terms require caution--May be implemented behind the generic architecture, but do not ship as an ordinary built-in provider until the outstanding terms/licensing issue is resolved.--## ENTERPRISE — contract-specific--Official commercial API, but production rights depend on an individual commercial agreement/order form. A random consumer API key is not enough.--## RED — do not ship built-in adapter--Undocumented/reverse-engineered/scraped source or otherwise outside the clean provider strategy.-------# 3. Summary matrix--| Provider | Status | API-first events | Live scores | Standings | Broadcasters/TV | Auth | Main release requirement |-|---|---|---:|---:|---:|---:|---|---|-| TheSportsDB | **GREEN** | Yes | Yes (premium) | Yes | **Yes** | V2 `X-API-KEY` | Paid subscription for app-store apps + attribution |-| BALLDONTLIE | **GREEN** | Yes | Yes | Yes | No known TV feed | `Authorization` API key | Respect plan capabilities; no raw-data resale |-| Highlightly | **GREEN** | Yes | Yes | Yes | No dedicated TV feed found | `x-rapidapi-key` | Avoid assuming logo/image rights |-| Sportmonks | **GREEN-WITH-GATE** | Yes | Yes | Yes | **Yes** | API token / `Authorization` | Confirm direct BYOK native-client use; protect token |-| football-data.org | **GREEN-WITH-GATE** | Yes | Yes on applicable plans | Yes | No | `X-Auth-Token` | Attribution; one-application rule; no logo rights |-| OddsPapi | **GREEN-WITH-GATE** | Yes | Yes | Limited/no general standings focus | No | `apiKey` | Use fixtures/scores only; verify app-display use |-| API-SPORTS | **YELLOW** | Yes | Yes | Yes | Not a core TV source | `x-apisports-key` | Terms say provider does not grant publication rights for competitions |-| SportDB.dev | **YELLOW** | Yes | Yes | Yes | No known TV feed | `X-API-Key` | Production is paid; downstream third-party rights remain user's responsibility |-| SportDevs | **YELLOW / PENDING** | Yes | Yes | Yes | Unknown | Bearer token | Current terms page must be successfully reviewed |-| SportsDataIO | **ENTERPRISE** | Yes | Yes | Yes | Depends on feed | `Ocp-Apim-Subscription-Key` | Commercial contract must authorize StreamVault/property/use case |-| Sportradar | **ENTERPRISE** | Yes | Yes | Yes | Product-dependent | API key | Production Order Form / authorized Properties |-| OpenLigaDB | **OPTIONAL OPEN DATA** | Yes, limited | Results/live-ish depending feed | Yes | No | None | ODbL attribution/share-alike obligations |-| ESPN site API | **RED** | Yes technically | Yes | Yes | Some | None | Undocumented site API; no clean third-party commercial license |-| scoreboard-api | **RED** | Yes technically | Yes | No | No | None | Scrapes ESPN HTML |-| SportTime.live | **RED** | Site only | N/A | N/A | Yes on site | N/A | No supported public API identified; do not scrape |-| Apple/private sports feeds | **RED** | Technically possible | Possible | Possible | Possible | Private | Reverse-engineered/private provider access |-| Unauthorized stream resolvers | **RED** | N/A | N/A | N/A | Streams | Various | Outside StreamVault's clean Sports-data architecture |-------# 4. Recommended implementation waves--## Wave 1 — prove the framework with the cleanest/highest-value adapters--Implement:--1. **TheSportsDB**-2. **BALLDONTLIE**-3. **Highlightly**--Why these three:--```text-TheSportsDB- -> broadcaster/TV metadata + simple sports model--BALLDONTLIE- -> very clear commercial data-use terms + many distinct sport APIs--Highlightly- -> one multi-sport key + uniform all-sports structure-```--Together they test:--```text-header auth-different capability sets-provider-event normalization-provider-specific sport routing-TV broadcaster metadata-live-score enrichment-standings-quota handling-API-first mode-```--Do not implement ten providers before these three validate Plan 3.-------## Wave 2 — high-value specialist providers--Implement after Wave 1 architecture is stable:--4. **Sportmonks** — after direct-native-BYOK release clarification-5. **football-data.org**-6. **OddsPapi** — fixtures/scores only-------## Wave 3 — conditional providers--Implement adapters only after the release gate is cleared:--7. **API-SPORTS**-8. **SportDB.dev**-9. **SportDevs**--The code may be prototyped using their documented APIs, but the production adapter must remain disabled/not shipped until its outstanding rights/terms issue is resolved.-------## Wave 4 — enterprise adapters--Only when there is actual user/customer demand:--10. **SportsDataIO**-11. **Sportradar**--These are not normal consumer BYOK integrations.--A valid API key is not sufficient by itself; the user's commercial agreement must authorize the StreamVault use case/property.-------## Optional open-data adapter--12. **OpenLigaDB**--Useful mostly as:--```text-free/open football fixture/results source-regional German-football coverage-testing/reference provider-```--Do not prioritize above the commercial/multi-sport providers.-------# 5. Provider 1 — TheSportsDB--**Status:** GREEN-**Priority:** Wave 1-**Recommended role:** Events + live scores + metadata + **broadcast/TV matching**--Official sources reviewed:--- https://www.thesportsdb.com/docs_terms_of_use.php-- https://www.thesportsdb.com/documentation-- https://www.thesportsdb.com/docs/api--## 5.1 Why it is especially valuable to StreamVault--TheSportsDB is one of the few providers we found that exposes explicit TV/broadcast information.--Relevant capabilities include:--```text-event lookup-schedules-livescores-team/league metadata-event TV broadcasts-TV schedule by day-TV filtering by channel/country/sport-```--This makes it useful not only for scoring but also for:--```text-API event- ↓-TheSportsDB broadcaster- ↓-StreamVault broadcaster normalization- ↓-user's M3U/Xtream channel-```--## 5.2 Terms/release notes--Current terms state, in substance:--- API-returned content may be copied/modified through official endpoints.-- Website scraping is not allowed.-- Free API usage is for development projects.-- **Apps cannot be published to an app store using the free tier.**-- Paid API subscribers may develop apps/services within rate limits.-- TheSportsDB must be mentioned as the data source.-- Image licensing/third-party rights remain a separate issue.--Therefore:--> For Play Store StreamVault support, require a user's **paid/premium TheSportsDB key** for production data integration.--Do not silently fall back to the shared free `123` key for the paid app.--## 5.3 Auth--Prefer V2:--```text-X-API-KEY: <user key>-```--Do not prefer V1 URL-key authentication for new StreamVault work.--## 5.4 Provider capabilities--Implement:--```text-EVENTS-LIVE_SCORES-GAME_STATUS-STANDINGS-TEAM_METADATA-LEAGUE_METADATA-BROADCASTERS-```--Do not implement video highlights initially.--## 5.5 StreamVault configuration--UI:--```text-TheSportsDB--Premium API key-[••••••••••••••]--[Test connection]--Attribution:-Data provided by TheSportsDB-```--## 5.6 Test connection--Test:--```text-authentication-V2 access-basic event endpoint-live-score endpoint capability-TV endpoint capability-```--Return:--```text-Connected-Premium V2-Events ✓-Live scores ✓-TV broadcasts ✓-```--## 5.7 Attribution--Implement provider attribution infrastructure from Plan 3.--Display TheSportsDB attribution in an appropriate visible Sports/About/provider location according to its terms.--## 5.8 Artwork--Do not assume all team/league images may be used commercially merely because the API returns a URL.--Prefer:--```text-EPG/channel art already used by StreamVault-```--until image rights are separately reviewed.-------# 6. Provider 2 — BALLDONTLIE--**Status:** GREEN-**Priority:** Wave 1-**Recommended role:** Events + live scoring + standings + broad multi-sport metadata--Official sources reviewed:--- https://www.balldontlie.io/terms.html-- https://www.balldontlie.io/docs-- https://www.balldontlie.io/account/--## 6.1 Why it is a strong candidate--Its current terms contain unusually explicit downstream permission.--They state that data may be used for lawful:--```text-personal purposes-commercial purposes-media/publishing-analytics-fantasy/gaming-AI/ML-lawful betting products-redistribution-```--without separate permission/attribution by default, while prohibiting:--```text-competing with BALLDONTLIE-selling/reselling the raw data unchanged-sharing/reselling API access/keys outside permitted plans-```--That is a much cleaner foundation than an undocumented site endpoint.--## 6.2 Coverage--Current docs expose 20+ leagues/sports, including examples across:--```text-NBA / basketball leagues-EPL-La Liga-Serie A-Champions League-Bundesliga-Ligue 1-MLS-World Cup-NFL-NCAAF-MLB-NHL-ATP-WTA-PGA-Formula 1-MMA-esports-```--Coverage varies by sport and plan.--## 6.3 Auth--Use the documented API key authorization header.--StreamVault settings should only ask for the user's key.--## 6.4 Account introspection--Strongly consider using the Account API to detect:--```text-subscription tier-sports subscribed-available capabilities-rate limits-```--This is better than asking the user to tell us which plan they bought.--## 6.5 Provider capabilities--Capabilities vary per sport.--Adapter architecture:--```text-BalldontlieProvider- |- +-- sport-specific capability resolver-```--Do not declare every capability globally.--Example:--```text-NFL free- games ✓- standings maybe plan-dependent--MMA- events ✓- fights paid- rankings paid--some basketball leagues- games paid- standings free/paid depending API-```--Use provider capability discovery rather than hardcoded assumptions where possible.--## 6.6 No broadcaster dependency--No general TV-broadcaster API was identified.--Therefore:--```text-BALLDONTLIE event- ↓-Plan 2/3 broadcast resolver- ↓-EPG-temporary event channels-manual selection-```--## 6.7 Artwork--Treat logos/images as separately reviewable.--Do not make remote provider artwork necessary for the adapter.-------# 7. Provider 3 — Highlightly--**Status:** GREEN-**Priority:** Wave 1-**Recommended role:** Unified multi-sport events + scores + standings + metadata--Official sources reviewed:--- https://highlightly.net/terms/-- https://highlightly.net/sport-api/-- https://highlightly.net/sport-api/documentation/--## 7.1 Terms--Current terms explicitly state that:--```text-distribution, transfer, and storage of API data are allowed-data may be used in applications/products-```--while prohibiting:--```text-reselling/sublicensing direct API access-proxy/pass-through API services-systematic extraction to create a competing database/service-```--Visual assets/logos remain the user's responsibility for commercial rights.--This is suitable for a normal application-data adapter.--## 7.2 Coverage--The current All Sports API exposes a shared base with multiple sport prefixes, currently documented for:--```text-football-american-football-nba-baseball-nhl-cricket-basketball-hockey-rugby-volleyball-handball-```--Common capabilities include:--```text-matches / schedules / live scores-standings-teams-players-statistics-lineups-```--Coverage differs by sport.--## 7.3 Auth--Direct Highlightly:--```text-x-rapidapi-key: <user key>-```--The same key can be used against the Highlightly All Sports base for subscribed products.--RapidAPI and direct Highlightly accounts are separate.--## 7.4 StreamVault implementation--Support two account modes only if necessary:--```text-Highlightly direct-RapidAPI-```--Prefer direct Highlightly initially.--Avoid making RapidAPI mandatory.--## 7.5 Provider configuration--```text-Highlightly--API key-[••••••••]--Account source-● Highlightly-○ RapidAPI-```--If direct-only initially, omit the account-source choice.--## 7.6 Quota--Read quota headers and expose:--```text-remaining requests-plan tier-```--when available.--Implement capability-specific caching because one All Sports quota is shared across sport prefixes.--## 7.7 Highlights/videos--Do not implement video-highlight playback in the first adapter.--That introduces separate content/geo-rights questions unrelated to the core Sports Hub.--## 7.8 Artwork--Do not treat Highlightly image URLs as automatically commercially licensed.--Prefer local/EPG artwork unless rights are verified.-------# 8. Provider 4 — Sportmonks--**Status:** GREEN-WITH-GATE-**Priority:** Wave 2 after confirmation-**Recommended role:** Football API-first events + live scoring + standings + **TV stations**--Official sources reviewed:--- https://www.sportmonks.com/terms-of-service/-- https://www.sportmonks.com/football-api/-- https://www.sportmonks.com/glossary/learn-how-to-retrieve-football-broadcast-data-using-the-sportmonks-football-api-v3-access-tv-stations-broadcaster-logos-and-fixtures-showing-on-each-channel/-- https://docs.sportmonks.com/v3/welcome/authentication--## 8.1 Terms--Sportmonks explicitly says its data may be used to build:--```text-apps-websites-games-other products-```--and commercial monetization of the resulting product is generally allowed.--It prohibits direct resale of its data as a competing data product.--Its enterprise summary also says customers may display and use data in their own product.--This makes it a strong commercial candidate.--## 8.2 Why it is especially valuable--Sportmonks exposes TV-station records linked to fixtures.--This directly supports:--```text-Sportmonks fixture- ↓-TV stations- ↓-canonical broadcaster names- ↓-StreamVault local channel resolver-```--For football, this is arguably the richest provider we found for StreamVault's exact use case.--## 8.3 Release gate: direct BYOK client use--Sportmonks documentation recommends keeping API tokens behind middleware/backend rather than directly in a frontend.--StreamVault's model is different:--```text-user enters their own token-token stored locally-calls originate from user's device-```--Before enabling this adapter in the Play build:--- [ ] ask Sportmonks whether user-owned tokens may be used directly from a native third-party client;-- [ ] confirm that this does not violate account/domain restrictions;-- [ ] document their response.--If confirmed, ship.--If not confirmed, leave Sportmonks available only through:--```text-Custom provider / user's own proxy-```--or another architecture they approve.--## 8.4 Auth--Use header auth rather than query-string token:--```text-Authorization: <user token>-```--Store locally using secure credential storage.--## 8.5 Capabilities--Implement:--```text-EVENTS-LIVE_SCORES-GAME_STATUS-STANDINGS-TEAM_METADATA-LEAGUE_METADATA-BROADCASTERS-```--Sportmonks is football-centric in this adapter.--Other Sportmonks products such as F1/cricket should be separate capability modules unless their APIs are structurally compatible enough to share code.-------# 9. Provider 5 — football-data.org--**Status:** GREEN-WITH-GATE-**Priority:** Wave 2-**Recommended role:** Football fixtures + live scores + standings--Official sources reviewed:--- https://www.football-data.org/about-- https://www.football-data.org/pricing-- https://www.football-data.org/documentation/api--## 9.1 Terms--Important requirements:--- API key applies to a single application.-- Credentials must be kept confidential.-- Attribution is required:- `Football data provided by the Football-Data.org API`-- Graphics/team logos/profile photos require separate permission from their legal owners.-- After subscription cancellation, previously obtained football data may no longer be referenced through the user's service.-- Free/paid plans differ in live-score freshness, competitions, and call rate.--## 9.2 BYOK interpretation--A user supplying a key for StreamVault should treat StreamVault as the one application associated with that key.--Before production release:--- [ ] confirm the provider is comfortable with user-owned API keys entered into the StreamVault native client;-- [ ] document attribution placement.--## 9.3 Auth--Use the documented API token header (`X-Auth-Token` in the API documentation).--## 9.4 Capabilities--Implement:--```text-EVENTS-LIVE_SCORES-GAME_STATUS-STANDINGS-TEAM_METADATA-LEAGUE_METADATA-```--No broadcaster capability.--## 9.5 Subscription cancellation behavior--Do not persist provider-derived data indefinitely.--When provider access is removed/invalid:--```text-expire cached provider event/standings data-retain only local EPG-derived Sports data-```--## 9.6 Artwork--Do not use football-data.org-provided team logos in the commercial app unless separate rights are obtained.-------# 10. Provider 6 — OddsPapi--**Status:** GREEN-WITH-GATE-**Priority:** Wave 2-**Recommended role:** Multi-sport fixtures + score enrichment--Official sources reviewed:--- https://oddspapi.io/en/legal/terms-- https://oddspapi.io/en/docs-- https://oddspapi.io/en/docs/get-fixtures-- https://oddspapi.io/en/docs/get-scores--## 10.1 Why support it at all--Although primarily an odds provider, it exposes useful non-odds data:--```text-sports-tournaments-fixtures-participants-scores-fixture status-```--This can provide an event/score source over a wide sports catalogue.--## 10.2 Terms--Terms prohibit:--```text-reselling/repackaging/redistributing data as a standalone product-API key sharing-abuse/scraping-```--and refer to third-party tools built using the data.--Before making it a normal built-in provider:--- [ ] obtain/confirm that displaying fixtures/scores inside a paid media-player app is within their intended use;-- [ ] document response.--## 10.3 Critical product restriction--StreamVault should **not implement odds/betting features** as part of this adapter.--Only expose:--```text-EVENTS-LIVE_SCORES-GAME_STATUS-basic participant/tournament metadata-```--Do not expose:--```text-bookmaker odds-betting markets-player props-settlements-```--This keeps the provider integration aligned to the Sports Hub rather than adding gambling functionality.--## 10.4 Auth--Current docs place `apiKey` in the request query.--Redact it from all logs and diagnostics.--If OddsPapi later supports secure header auth, prefer the header.-------# 11. Provider 7 — API-SPORTS / API-Football family--**Status:** YELLOW-**Priority:** Wave 3 only after legal/product review-**Recommended role if cleared:** events + live scores + standings across multiple sports--Official sources reviewed:--- https://api-sports.io/terms-- https://api-sports.io/-- https://api-sports.io/documentation/football/v3--## 11.1 Technical fit--Very good technically.--Features:--```text-football-basketball-NBA-NFL/NCAA-baseball-hockey-Formula 1-MMA-AFL-handball-and others-```--Each API has a documented official endpoint and user key.--Auth example:--```text-x-apisports-key: <user key>-```--## 11.2 Why it is YELLOW--The terms simultaneously say the data is provided for building projects such as applications/websites, but explicitly state that API-SPORTS does **not** provide the user a license to publish data for competitions where third-party rights may apply.--The customer is responsible for obtaining required permissions from:--```text-leagues-federations-event organizers-other rights holders-```--The same warning applies to logos/images/trademarks.--Therefore an API key alone is **not** a clean rights grant.--## 11.3 Plan--We may implement the adapter internally after the provider framework exists, but do not enable it in the normal Play Store provider catalogue until one of these is true:--1. API-SPORTS provides written clarification that StreamVault's factual scores/fixtures display use is permitted for the intended competitions; or-2. we complete a legal review defining what can be displayed safely; or-3. the user/provider has a contractual license that clearly covers the use.--## 11.4 If eventually shipped--Default to text/factual data.--Do not automatically use:--```text-logos-player images-league marks-```--without a separate rights policy.-------# 12. Provider 8 — SportDB.dev--**Status:** YELLOW-**Priority:** Wave 3-**Recommended role if cleared:** multi-sport events + live scores + standings--Official sources reviewed:--- https://sportdb.dev/-- https://sportdb.dev/tos.html--## 12.1 Technical capabilities--Current API advertises:--```text-live scores-fixtures-standings-match details-lineups-stats-clubs-players-transfers-multiple sports-```--Authentication uses an API key.--## 12.2 Terms issue--Terms state:--```text-free tier for testing-production requires paid plan-no API resale/sublicensing-downstream use must comply with third-party terms/IP rights-```--They do not give as explicit a downstream commercial-display permission as BALLDONTLIE/Highlightly.--## 12.3 Release gate--Before built-in release:--- [ ] obtain written confirmation for paid commercial app display;-- [ ] confirm end-user BYOK through a third-party native app;-- [ ] clarify any attribution/artwork requirements.--Until then:--```text-Custom Sports Provider-```--may be used by advanced users who configure their own compatible endpoint.-------# 13. Provider 9 — SportDevs--**Status:** YELLOW / PENDING TERMS-**Priority:** Wave 3 only after terms verification--Official sources reviewed:--- https://docs.sportdevs.com/docs-- https://www.sportdevs.com/... product pages--The documentation links to:--```text-https://sportdevs.com/terms-```--but the terms page could not be reliably fetched during this review.--## 13.1 Technical fit--SportDevs markets use cases including:--```text-live score apps-sports news sites-mobile sports apps-data analysis-betting platforms-```--and offers broad sport coverage with REST/WebSocket APIs.--Auth:--```text-Bearer token-```--## 13.2 Release rule--Do **not** ship a built-in provider based only on marketing examples.--Required first:--- [ ] fetch/read current Terms of Service successfully;-- [ ] verify commercial display/use;-- [ ] verify BYOK/native-client rules;-- [ ] verify redistribution/data rights;-- [ ] verify image/logo terms.-------# 14. Provider 10 — SportsDataIO--**Status:** ENTERPRISE-**Priority:** Wave 4, demand-driven-**Recommended role:** enterprise-grade events/scores/standings/metadata--Official sources reviewed:--- https://sportsdata.io/help/data-rights-and-licensing-questions-- https://sportsdata.io/developers-- https://sportsdata.io/terms-of-service-- https://sportsdata.io/developers/api-documentation/global--## 14.1 Commercial model--SportsDataIO explicitly distinguishes:--```text-personal/non-commercial Discovery Lab-commercial licenses-```--Commercial/public-facing/revenue-generating products require a commercial license.--Commercial licenses may permit:--```text-display of raw scores/schedules/stats-caching/storage-derived analytics-```--within the licensed scope.--## 14.2 Important limitation for BYOK--Commercial rights are tied to the customer's license/use case.--Therefore StreamVault cannot assume:--```text-valid SportsDataIO key-=-permission to display data inside StreamVault-```--The user's agreement must authorize that use/property.--## 14.3 Auth--Use:--```text-Ocp-Apim-Subscription-Key: <key>-```--rather than query-string keys.--## 14.4 Implementation strategy--Do not show SportsDataIO in the default consumer `Add Provider` list initially.--Possible later UX:--```text-Enterprise providers- SportsDataIO-```--with an explicit notice:--```text-Requires a production commercial license that authorizes use in StreamVault.-```--## 14.5 Trial behavior--Free trial/dev data may be scrambled and is not suitable for production display.--Adapter tests may use the trial schemas, but do not treat trial keys as production-capable.-------# 15. Provider 11 — Sportradar--**Status:** ENTERPRISE-**Priority:** Wave 4, demand-driven--Official sources reviewed:--- https://developer.sportradar.com/sportradar-updates/page/terms-and-conditions-- https://developer.sportradar.com/sportradar-updates/page/master-terms-and-conditions-for-non-betting-services-- https://developer.sportradar.com/getting-started/docs/your-account-- https://developer.sportradar.com/getting-started/docs/mcp-server--## 15.1 Commercial model--Free trial access is for:--```text-internal testing/evaluation-```--and does not authorize commercial/public data display.--Production access requires a customer relationship/order form.--The order form can define:--```text-Products-Properties-rate limits-fees-licensed use-```--## 15.2 BYOK rule--A Sportradar production key is usable in StreamVault only if the customer's agreement authorizes StreamVault/the relevant property/use.--Therefore:--> This is a contract-gated enterprise adapter, not a generic consumer BYOK integration.--## 15.3 Coverage--Technically exceptional:--```text-football-soccer-basketball-baseball-hockey-racing-tennis-golf-MMA-cricket-rugby-volleyball-darts-snooker-many other sports-```--## 15.4 Implementation--Only build once there is a real user/customer requesting it.--Use the provider's official schema/OpenAPI/MCP documentation to map the exact products licensed by that user.--Do not assume one Sportradar account contains all sports.-------# 16. Optional provider — OpenLigaDB--**Status:** OPTIONAL OPEN DATA-**Priority:** Low--Official sources reviewed:--- https://openligadb.de/-- https://api.openligadb.de/-- https://openligadb.de/lizenz--Current site states API data is provided under the **Open Database License (ODbL)**.--## 16.1 Benefits--```text-no API key-community-maintained-fixtures/results/tables-good regional/testing value-```--## 16.2 Downsides--```text-limited coverage compared with commercial providers-community data quality-ODbL attribution/share-alike obligations need to be respected-```--## 16.3 Implementation--If added:--- [ ] include ODbL attribution;-- [ ] document whether StreamVault creates/stores a derivative database;-- [ ] ensure any required share-alike obligations are understood;-- [ ] keep it isolated from proprietary provider data so database-license obligations do not accidentally contaminate unrelated cached datasets.--Do not make it the default global provider.-------# 17. Explicitly rejected built-in providers/sources--## 17.1 ESPN undocumented site API--Do not implement in the Play provider catalogue.--Reason:--```text-publicly reachable-but undocumented-no clean third-party commercial API license identified-automated/commercial-use Terms concerns-```--No codename changes this.--## 17.2 scoreboard-api--Do not integrate.--The project explicitly scrapes ESPN web pages and extracts embedded ESPN page JSON.--Its MIT code license does not grant ESPN data rights.--## 17.3 SportTime.live--Do not scrape.--It is useful as product inspiration for:--```text-sports schedule-country-specific broadcaster lists-```--but no suitable public developer API/license was established.--## 17.4 Private Apple sports feeds--Do not reverse-engineer or ship.--## 17.5 Unauthorized stream providers/resolvers--Never part of the Sports Data Provider system.-------# 18. What happened to previously discussed "TV Guide API"--StreamVault already has:--```text-user XMLTV / EPG-```--as its primary TV-guide/broadcast source.--Generic TV-guide APIs with restrictive shared quotas are not required for the base Sports architecture.--If a specific TV-guide vendor is later proposed, treat it as:--```text-BroadcastProvider-```--not automatically as an EventProvider.--It must pass the same terms/release review.-------# 19. Built-in provider Settings design--Recommended:--```text-Settings-→ Sports-→ Data Providers-```--Screen:--```text-ADD PROVIDER--Recommended-────────────────────-TheSportsDB-BALLDONTLIE-Highlightly--More providers-────────────────────-Sportmonks-Football-Data.org-OddsPapi--Conditional / Enterprise-────────────────────-[only show when appropriate]--Advanced-────────────────────-Custom REST/JSON-```--Do not expose RED sources.-------# 20. Provider card--Example:--```text-TheSportsDB--Not connected--Provides:-Fixtures-Live scores-Standings-TV broadcasters--[Connect]-```--Connected:--```text-TheSportsDB--Connected-Premium V2--Events ✓-Live scores ✓-Standings ✓-Broadcasters ✓--Quota: ...-Last success: ...--[Configure] [Disconnect]-```-------# 21. Credentials UX--Known providers ask only for required user credentials.--Examples:--```text-TheSportsDB-API key-```--```text-BALLDONTLIE-API key-```--```text-Sportmonks-API token-```--```text-football-data.org-API token-```--No endpoint entry for built-in providers.--Base URLs live inside the adapter.-------# 22. Connection validation contract--Every built-in adapter must implement:--```kotlin-interface ProviderConnectionValidator {- suspend fun validate(- config: SportsProviderConfig- ): ProviderValidationResult-}-```--Return:--```text-VALID-INVALID_CREDENTIALS-PLAN_INSUFFICIENT-RATE_LIMITED-SERVICE_UNAVAILABLE-UNSUPPORTED_CONFIGURATION-TERMS_REVIEW_REQUIRED-```--Validation should detect capabilities when possible.-------# 23. Provider capability discovery--Do not assume the user's paid plan.--Example:--```text-BALLDONTLIE- -> account endpoint- -> subscribed sports + tier-```--Example:--```text-Highlightly- -> plan metadata / response envelope-```--Example:--```text-API-SPORTS- -> status endpoint-```--Example:--```text-TheSportsDB- -> V2/premium endpoint test-```--Where providers do not expose account capabilities, infer conservatively from successful authorized endpoint calls.-------# 24. Shared adapter result model--Every adapter must normalize into Plan 3 DTOs.--Provider raw models must never reach UI code.--```text-Provider JSON- ↓-Provider mapper- ↓-ProviderEvent-ProviderScore-ProviderStanding-ProviderBroadcaster-ProviderTeamMetadata- ↓-Plan 3 resolver- ↓-Canonical SportEvent-```-------# 25. API-first eligibility--A provider may be selected as the user's primary Event Source only if it has:--```text-EVENTS-stable event IDs-event time/date-sport identity-enough competitor/event identity to match EPG/channel data-```--Providers used only for live scores cannot be selected for API-first discovery.-------# 26. Per-provider authority--Recommended default authority:--## TheSportsDB--```text-Events: allowed-Scores: allowed-Standings: allowed-Broadcasters: allowed-Playback: local only-```--## BALLDONTLIE--```text-Events: allowed-Scores: allowed-Standings: allowed when plan/sport supports-Broadcasters: none-Playback: local only-```--## Highlightly--```text-Events: allowed-Scores: allowed-Standings: allowed where sport supports-Broadcasters: none-Playback: local only-```--## Sportmonks--```text-Events: allowed-Scores: allowed-Standings: allowed-Broadcasters: allowed-Playback: local only-```--## football-data.org--```text-Events: allowed-Scores: allowed per plan-Standings: allowed-Broadcasters: none-Playback: local only-```--## OddsPapi--```text-Events: allowed-Scores: allowed-Standings: not primary capability-Odds: deliberately not exposed-Playback: local only-```-------# 27. Broadcaster priority--For providers with broadcaster data:--```text-existing resolved EPG channel- >-provider broadcaster exact/canonical match- >-Plan 2 event-channel matcher- >-manual picker-```--TheSportsDB/Sportmonks broadcaster metadata should improve matching, not override a correct existing EPG mapping.-------# 28. Images/logos policy--The adapter and the artwork capability are separate.--Default release rule:--```text-Provider factual data- ✅--Provider logo/image URL- not automatically enabled-```--A provider can be GREEN for scores/events while its artwork remains disabled.--Use:--```text-EPG logos-existing StreamVault channel logos-generic sport icons-```--until image rights are established.-------# 29. Highlights/video policy--Do not include highlights in the first provider implementations.--Even if an API exposes:--```text-YouTube highlight URLs-video clips-highlight embeds-```--that introduces:--```text-third-party copyright-geo restrictions-platform terms-playback policy-```--Treat highlights as a future separate feature/legal review.-------# 30. Betting/odds policy--The Sports Hub does not need betting functionality.--Even when a provider exposes odds:--```text-Sportmonks-Highlightly-BALLDONTLIE-OddsPapi-API-SPORTS-SportsDataIO-Sportradar-```--do not expose odds in the initial provider adapter.--Provider code may ignore those endpoints entirely.--This keeps Plan 4 focused on:--```text-events-scores-status-standings-metadata-broadcasters-```-------# 31. Caching by provider--Each adapter defines recommended TTLs.--Conceptual defaults:--```text-fixtures/upcoming- 10–60 min depending provider--live scores- provider-safe interval, usually 30–120 sec--standings- 15–60 min--team metadata- 24h+--league metadata- 24h+--broadcasters- cache until event changes / several hours-```--Do not poll all providers simultaneously for the same capability unless configured for fallback.-------# 32. Quota-aware routing--If primary score provider is close to quota:--```text-do not silently spend another provider's quota-```--unless the user enabled automatic fallback.--Possible setting:--```text-Provider failure fallback--● Use another configured provider-○ Fall back only to EPG/local data-```--Default can remain conservative initially.-------# 33. User-owned quota principle--For self-serve BYOK providers:--```text-user account- ↓-user API key- ↓-user subscription- ↓-user quota-```--StreamVault does not ship a shared production key.--Do not proxy ordinary BYOK traffic through an OpenAI/StreamVault backend.-------# 34. Secret handling--All provider credentials:--- encrypted/Keystore-backed at rest;-- never logged;-- never exported through normal debug bundles;-- query-string keys redacted before HTTP logging;-- removed from exception text;-- excluded from screenshots where possible;-- only available to the provider request layer.-------# 35. Terms metadata in code--Each adapter should ship a machine-readable compliance descriptor.--Example:--```kotlin-data class ProviderComplianceInfo(- val termsUrl: String,- val reviewedAt: LocalDate,- val attributionRequired: Boolean,- val appStoreAllowed: Boolean?,- val commercialUseStatus: CommercialUseStatus,- val artworkStatus: ArtworkUseStatus,- val releaseGate: ProviderReleaseGate-)-```--This is informational/internal.--Do not pretend the descriptor itself creates legal rights.-------# 36. Release-gate statuses--```kotlin-enum class ProviderReleaseGate {- APPROVED,- REQUIRES_ATTRIBUTION,- REQUIRES_VENDOR_CONFIRMATION,- REQUIRES_CUSTOMER_CONTRACT,- DO_NOT_SHIP-}-```--The Play build provider registry should only expose adapters whose release gate permits it.-------# 37. Build-time provider registry--Prefer:--```text-clean built-in adapters-```--compiled into both distributions.--Do not compile RED adapters into the Play APK.--Enterprise adapters may be included but hidden unless intentionally enabled, or kept as optional modules if that better fits the codebase.-------# 38. Provider-specific source modules--Suggested:--```text-sports-providers/-├── core/-├── thesportsdb/-├── balldontlie/-├── highlightly/-├── sportmonks/-├── footballdata/-├── oddspapi/-├── apisports/-├── sportdb/-├── sportdevs/-├── sportsdataio/-├── sportradar/-└── openligadb/-```--Use existing StreamVault module conventions rather than creating modules solely for aesthetics.--Conditional providers may exist in source while disabled from release registry only if doing so does not create policy/distribution concerns.--RED providers should not be implemented.-------# 39. First adapter — recommended choice--Implement **TheSportsDB first**.--Reasons:--1. very simple auth;-2. broad sports/event model;-3. premium app-store use explicitly addressed in terms;-4. livescores;-5. event TV-broadcast endpoints;-6. low price barrier for real users;-7. ideal test of API broadcaster → local IPTV matching.--First end-to-end milestone:--```text-user adds TheSportsDB premium key- ↓-StreamVault validates V2- ↓-user selects TheSportsDB as Event Source- ↓-events appear from API- ↓-TV broadcaster/EPG matching finds local channels- ↓-score/status enriches event- ↓-play uses user's M3U/Xtream channel-```-------# 40. Second adapter — BALLDONTLIE--Use it to prove:--```text-multi-sport provider-sport-specific plan capabilities-provider account introspection-score/standing enrichment-API-first without broadcaster feed-```--Milestone:--```text-BALLDONTLIE event- ↓-EPG / Plan 2 channel resolver- ↓-playable user channel-```-------# 41. Third adapter — Highlightly--Use it to prove:--```text-one-key multi-sport base-shared quota across sports-prefix-based sport routing-pagination-standings + lineups + team metadata-```--Do not implement highlights first.-------# 42. Fourth adapter — Sportmonks--Once the BYOK/native-client gate is cleared, use it to prove:--```text-rich football include model-high-quality TV-station matching-configurable league subscription coverage-```--This may become the best premium football provider for StreamVault.-------# 43. Adapter contract tests--Every built-in adapter must pass the Plan 3 provider contract suite.--Add per-provider fixtures for:--```text-upcoming event-live event-finished event-postponed/cancelled event-missing competitor-unknown league-score update-standings-rate-limit response-bad key-plan-insufficient response-schema field missing-```--Broadcaster providers also test:--```text-one TV station-multiple countries-streaming-only service-unknown broadcaster-duplicate broadcaster records-```-------# 44. No live-network dependency in CI--Capture/sanitize provider responses as fixtures where their terms allow it.--Tests must not depend on current live games.--Integration smoke tests against real providers should be optional/manual and require developer-owned credentials.--Never commit real API keys.-------# 45. Terms re-check automation/process--Do not automatically scrape Terms pages.--Maintain:--```text-docs/sports/providers/<provider>-review.md-```--containing:--```text-review date-terms URL-documentation URL-capabilities-auth-attribution-commercial-use summary-open questions-release gate-```--Before each significant release:--- [ ] review providers whose terms changed;-- [ ] re-check any provider marked `REQUIRES_VENDOR_CONFIRMATION`;-- [ ] update review date/status.-------# 46. Provider documentation files--Create:--```text-docs/sports/providers/-├── thesportsdb.md-├── balldontlie.md-├── highlightly.md-├── custom-json.md-├── sportmonks.md-├── football-data.md-├── oddspapi.md-├── api-sports.md-├── sportdb.md-├── sportdevs.md-├── sportsdataio.md-├── sportradar.md-└── openligadb.md-```--Each document separates:--```text-technical facts-terms/licensing findings-StreamVault implementation-open questions-```--Do not mix assumptions into verified terms.-------# 47. Provider list UI release policy--The UI should only advertise providers that are actually releasable.--Initial production list after Wave 1:--```text-TheSportsDB-BALLDONTLIE-Highlightly-Custom REST/JSON-```--Then add Wave 2 providers as their gates clear.--Do not show:--```text-Coming soon ESPN-```--or any unsupported questionable source.-------# 48. API-first defaults--When a provider is configured:--Do not automatically switch the user's Event Source without permission.--After successful connection:--```text-Use TheSportsDB for event discovery?--○ Keep Automatic-○ Use TheSportsDB-```--Recommended default:--```text-Automatic-```--Plan 3 source routing decides whether/when provider events are preferred.-------# 49. Provider removal--On disconnect:--```text-delete local credentials-cancel provider polling-invalidate provider cache-remove provider-event links-fall back to EPG / other configured provider-```--Do not delete:--```text-user playlist-EPG-local manual channel mappings-```--unless those mappings were strictly provider-ID-specific and cannot be resolved without the provider.-------# 50. Attribution removal--When a provider requiring attribution is disconnected and no cached licensed data remains in display, remove its attribution from active Sports UI.--Keep legal/open-source notices that must remain in About/licenses if required.-------# 51. Offline behavior--No provider should make Sports unusable offline.--If API is unavailable:--```text-EPG Sports- continues-```--Cached provider data may be shown only according to the provider's terms/cache rules and with a stale timestamp where useful.-------# 52. Implementation sequence--## Phase 4.1 — Provider compliance registry--- [x] Add internal provider review metadata.-- [x] Add release-gate enum.-- [x] Add attribution capability.-- [x] Add artwork-rights status.-- [x] Add terms/docs source fields.-- [x] Add tests ensuring `DO_NOT_SHIP` adapters cannot appear in Play provider registry.-------## Phase 4.2 — TheSportsDB--The Plan 3 implementation already provides the key UI, premium-key V2 auth, event and live-score mapping, bounded response caching, fixtures, and API-first source selection. These completed items are not work to repeat in Phase 4.2. Their existence does not clear the Phase 4.1 release/compliance gate.--- [x] Premium/V2 credential UI.-- [x] V2 auth.-- [x] event mapping.-- [x] live-score mapping.-- [x] standings mapping — documented V1-only endpoint; all other operations use V2.-- [x] TV-broadcast mapping.-- [x] attribution in every applicable Sports UI surface.-- [x] cache/rate policy.-- [x] fixture tests.-- [x] API-first integration.-- [x] broadcaster → local channel integration.-- [x] Beta status is visible in provider settings because no live Premium account is available.-- [ ] live Premium-account validation — deferred by the user (no key available); the provider remains Beta until a real account check is completed.-------## Phase 4.3 — BALLDONTLIE--- [x] key UI — uses the localized shared provider configuration form.-- [x] account/subscription introspection.-- [x] sport capability resolver.-- [x] event mapping.-- [x] live-score mapping.-- [x] standings where available, with the account tier checked per sport.-- [x] cache/rate policy.-- [x] fixture tests.-- [x] API-first + EPG channel resolver test.--The initial adapter scope is NBA, NFL, MLB, and the English Premier League.-Other BALLDONTLIE sport APIs remain future work. The API-backed behavior was-verified against documented-response fixtures; no live account key was-configured or tested. See `sports/providers/balldontlie.md`.-Account-tier checks distinguish EPL match access (ALL-STAR/Paid) from its-Free standings route; NBA standings require GOAT/Paid Plus, and NFL/MLB-standings require ALL-STAR/Paid.-------## Phase 4.4 — Highlightly--- [x] key UI through the shared provider credentials form.-- [x] direct All Sports base.-- [x] sport-prefix routing.-- [x] bounded offset pagination.-- [x] matches/live scores and game status.-- [x] standings for documented route shapes.-- [x] team and supported league metadata.-- [x] shared quota tracking; show remaining requests and plan tier when supplied.-- [x] fixture tests.-- [x] no highlights/video endpoints.--Implementation and fixture coverage are recorded in-[`sports/providers/highlightly.md`](sports/providers/highlightly.md). Highlightly is marked **Beta** in provider settings until a live account validation can be completed; no account key is available.-------## Phase 4.5 — Sportmonks (skipped per user instruction)--**Status (2026-10-17):** Skipped at the user's direction. No vendor inquiry was-sent and no Sportmonks adapter was implemented or registered. The direct-native-BYOK gate remains uncleared; Sportmonks stays unavailable as a built-in-provider unless this decision is revisited and the gate is cleared.--Before coding production adapter:--- [ ] contact/review confirmation for native BYOK.-- [ ] record answer.-- [ ] if approved, continue.--Then:--- [ ] token UI.-- [ ] secure header auth.-- [ ] fixtures.-- [ ] livescores.-- [ ] standings.-- [ ] TV stations.-- [ ] rich participant/team mapping.-- [ ] rate metadata.-- [ ] fixture tests.--If not approved:--```text-do not ship built-in adapter-support user's Sportmonks proxy through Custom REST/JSON-```-------## Phase 4.6 — football-data.org--- [x] token UI through the shared provider credential form.-- [x] required attribution on provider-backed event and standings surfaces.-- [x] event/score/standings mapping.-- [x] conservative local request cap and provider rate metadata.-- [x] credential-scoped cache cleanup on 401/403.-- [x] no provider logos or artwork.-- [x] single-application/BYOK review recorded from published terms.--Offline implementation and fixture coverage are recorded in-[`sports/providers/football-data.md`](sports/providers/football-data.md).-No live account validation was performed.-------## Phase 4.7 — OddsPapi score-only adapter--- [x] key UI through the shared provider credential form.-- [x] query-key transport remains absent from app logs and typed failures.-- [x] bounded fixture lookup and time filtering.-- [x] participant mapping.-- [x] period-score aggregation.-- [x] fixture-state mapping.-- [x] omit odds endpoints and capabilities.-- [ ] provider-use confirmation before release.--**Release status:** Prototype only. Terms and documented API behavior were-reviewed on 2026-10-17. The terms do not answer whether a user's direct key may-be used to show fixtures/scores in a paid Android media-player app. No vendor-inquiry was sent, so the production release gate remains closed. See-[`sports/providers/oddspapi.md`](sports/providers/oddspapi.md).-------## Phase 4.8 — Conditional providers--The published-term reviews were completed for API-SPORTS and SportDB.dev on-2026-10-17. SportDevs' official terms URL returned HTTP 502 and could not be-reviewed successfully. No provider was contacted and none has an adapter in-this change. See-[`sports/providers/conditional-and-open-data-review-2026-10-17.md`](sports/providers/conditional-and-open-data-review-2026-10-17.md).--For each of:--```text-API-SPORTS-SportDB.dev-SportDevs-```--- [x] finish the available rights/terms review.-- [ ] obtain clarification where public terms do not resolve app display.-- [x] set or retain a closed release gate.-- [x] keep adapters unimplemented/unreleased until their gates pass.--Current gates: API-SPORTS `DO_NOT_SHIP` pending publication permissions;-SportDB.dev `REQUIRES_VENDOR_CONFIRMATION`; SportDevs `DO_NOT_SHIP` until its-terms can be reviewed.--API-SPORTS adapter work may be prototyped against documented schemas but remains disabled if publication rights remain unresolved.-------## Phase 4.9 — Enterprise adapters--Only after demand:--```text-SportsDataIO-Sportradar-```--Deferred because this work contains no customer request or production-agreement for these products. No adapters were added.--Requirements:--- [ ] user has production commercial agreement.-- [ ] agreement permits StreamVault/property/use case.-- [ ] adapter only exposes licensed products.-- [ ] no free-trial data displayed as production.-- [ ] contract-specific attribution/restrictions supported.-------## Phase 4.10 — Optional OpenLigaDB--- [x] ODbL compliance analysis.-- [x] linked source and ODbL attribution on provider event and standings surfaces.-- [x] offline fixture, result/status, and table adapter.-- [x] keep only bounded raw responses in process memory; do not create a derivative database.-- [x] keep as a low-priority optional adapter.--The 2026-10-17 review found that publicly used Produced Works need an-OpenLigaDB/ODbL notice with source and license links; derivative databases have-additional share-alike and machine-readable access duties. The optional adapter-ships only bounded, short-lived raw-response caching, disables provider artwork,-and shows linked attribution on data surfaces. No live OpenLigaDB account was-used. Details are in-[`sports/providers/conditional-and-open-data-review-2026-10-17.md`](sports/providers/conditional-and-open-data-review-2026-10-17.md).--The implementation uses at most five configured `shortcut:season` scopes,-fetches documented group/season-match/table routes, filters fixtures to the-requested half-open time window, and spaces requests by at least 1.2 seconds-across the app process. See [`sports/providers/openligadb.md`](sports/providers/openligadb.md).-------# 53. Provider ranking for StreamVault specifically--## Best overall first adapter--**TheSportsDB**--Why:--```text-app-store terms are explicit-cheap premium key-broad sport coverage-TV broadcasts-scores-simple API-```--## Best legal clarity for commercial factual data--**BALLDONTLIE**--Why:--```text-explicit commercial permission-explicit redistribution permission with restrictions-no mandatory attribution by default-multi-sport-```--## Best simple multi-sport integration--**Highlightly**--Why:--```text-one key-one base-11 sport prefixes-similar endpoint shapes-data allowed in applications/products-```--## Best football+broadcast premium provider--**Sportmonks** (unimplemented candidate; skipped in this change)--Why:--```text-excellent football data-TV stations-commercial product use allowed-rich fixture model-```--but only after the direct-BYOK/native-client question is cleared.--## Best enterprise providers--```text-SportsDataIO-Sportradar-```--but only for users with actual commercial contracts.-------# 54. Final recommendation--For integrations that are enabled or have an approved next step, proceed in this-order. Sportmonks is skipped, OddsPapi and conditional services remain gated,-and enterprise providers wait for a customer contract:--```text-1. TheSportsDB-2. BALLDONTLIE-3. Highlightly-4. football-data.org-5. OpenLigaDB (optional)-6. OddsPapi score-only, after provider-use confirmation-7. conditional APIs as terms clear-8. enterprise adapters only when requested-```--Do not optimize for "largest number of provider logos in Settings."--Optimize for:--```text-clear rights-stable official API-good event IDs-good score data-useful broadcaster metadata-secure BYOK-predictable quota-clean failure behavior-```-------# 55. Final architecture with concrete providers--```text- SPORTS EVENT SOURCES-- +--------------+--------------+--------------+- | | | |- v v v v- EPG TheSportsDB BALLDONTLIE Highlightly- | | | |- | Football-Data OpenLigaDB ...- | | | |- +--------------+--------------+--------------+- |- v- Plan 3 Event Resolver- |- v- Canonical SportEvent- |- +--------------+--------------+- | | |- v v v- Scores Standings Metadata- |- v- Broadcast Resolver- +--------------+----------------+- | | |- v v v- provider TV data XMLTV Plan 2 fallback- (where supported) | event-channel match- +--------------+----------------+- |- v- M3U / Xtream- |- v- PLAY-```--The rule remains:--> **Sports data providers may tell StreamVault what event exists, what the score is, and which broadcaster carries it. Only the user's own configured StreamVault channels determine what can actually be played.**diff --git a/docs/Sports-PLAN-4-IMPLEMENTATION.md b/docs/Sports-PLAN-4-IMPLEMENTATION.mddeleted file mode 100644index 2092b25b..00000000--- a/docs/Sports-PLAN-4-IMPLEMENTATION.md+++ /dev/null@@ -1,285 +0,0 @@-# Sports Plan 4 implementation — Phases 4.1–4.10--Date: 2026-10-17-Branch: `codex/sports-integration`-Worktree: `D:\antigravity-scratch\iptv-player\.worktrees\sports-integration`--This record covers the compliance registry, TheSportsDB completion,-BALLDONTLIE, Highlightly, football-data.org, the gated OddsPapi prototype, and-the optional OpenLigaDB adapter.-Sportmonks was skipped at the user's direction without contacting the provider.-TheSportsDB and Highlightly are marked **Beta** in provider settings because-fixture coverage passed but no live provider accounts were available. This is a-technical verification label; it does not alter either provider’s terms or-release gate. OddsPapi is development-only until provider-use confirmation is-obtained. OpenLigaDB was validated offline only.--## Completed behavior--- Provider review descriptors record terms/docs URLs, review date, commercial- status, app-store availability, attribution, paid-account requirements, artwork- rights, and release gate. These records do not create provider rights.-- Registry defaults to production policy. Filtering removes factories, which- prevents saved configurations from bypassing gates through creation, source- eligibility, display names, or capability lookup. Duplicate registrations- remain invalid even when one would be filtered out.-- App DI enables development access only for the exact debug build type. Beta,- benchmark, nonMinifiedRelease, and release use the production policy. Debug- still excludes DO_NOT_SHIP, prohibited providers, and uncleared artwork.-- The custom REST transport remains available without a vendor review; this is- not an approval of user-configured data sources. Its settings form offers a- loadable mapping example and localized instructions; the schema is documented in- `sports/providers/custom-json.md`. No conditional, enterprise, or RED provider- adapters were added.-- TheSportsDB adds standings, event TV, team metadata, and league metadata to its- existing events/scores/status adapter. No artwork, odds, highlights, or- provider-supplied playback endpoints are exposed.-- TV enrichment skips usable EPG choices, requests at most twelve unresolved- events nearest the current time, and respects per-account cooldowns and- Retry-After. Canonical broadcaster matching outranks event-name fallback;- playback choices still come exclusively from configured user channels.-- Attribution appears on event cards, featured events, details, manual channel- selection, standings, and provider configuration. Card heights accommodate- credits. Standings headers align with their data columns.-- Connection testing checks V2 sports, schedule, live-score, and TV envelopes.- The shared free key is rejected. Standings additionally require successful V2 authorization for the exact credential before V1 is contacted; a denied V2 key cannot fall through to V1. No event-source preference changes on save.-- Response cache keys now include configuration revision as well as account,- credential fingerprint, endpoint, and query, so edits cannot reuse older data.-- Schedule mapping retains unknown league IDs and handles the postponed flag.-- Fixed a pre-existing missing SportsProviderConfig import required for the- Sports Hub repository to compile.-- BALLDONTLIE adds the shared API-key settings flow, account subscription- introspection, and sport-scoped capability resolution for NBA, NFL, MLB,- and EPL. Sports endpoints receive the raw key in `Authorization`; the- account endpoint receives the separate Bearer form.-- BALLDONTLIE maps schedules, participants, status, scores, and supported- standings. Calls check the account's per-sport subscription and endpoint- tier before making a restricted request: EPL matches/scores need ALL-STAR,- NBA standings need GOAT, and NFL/MLB standings need ALL-STAR; EPL standings- are Free. MLB division rank is derived from the published win-percentage- fields. Unsupported sports remain out of this initial adapter.-- BALLDONTLIE requests are bounded to 31 calendar dates, three schedule pages,- and four detail reads per sport. Account, schedule, detail, and standings- caches use 5-minute, 2-minute, 1-minute, and 30-minute TTLs respectively,- scoped by credential fingerprint and config revision.-- A fixture-backed NBA event joins its local EPG event while retaining the- user's playable channel. Provider artwork, broadcasters, odds, highlights,- and playback URLs are not exposed. See `sports/providers/balldontlie.md` for- source links and the scope review.--## Documented API limitation--The official V2 documentation and OpenAPI do not list a standings endpoint.-Standings therefore use the documented V1 table endpoint with the user's-Premium key. All other operations use V2 header authentication. The V1 request-uses the dedicated transport without URL logging, redirects, disk cache, or-cookie storage. Exceptions, URLs, and server bodies do not cross the sanitized-provider-result boundary. See `sports/providers/thesportsdb.md` for the review-and source links.--## Offline verification--Commands run with ANDROID_HOME pointing to the installed Android SDK:--```powershell-.\gradlew.bat :domain:test :data:testDebugUnitTest --tests 'com.streamvault.data.sports.*' :feature:live:testDebugUnitTest --tests 'com.streamvault.feature.live.sports.*' :feature:settings:testDebugUnitTest --tests '*SportsProvider*' :app:assembleDebug --no-configuration-cache --console=plain-.\gradlew.bat :app:compileReleaseKotlin --no-configuration-cache --console=plain-```--Both commands passed. The final targeted suite passed 378 tests with zero-failures, errors, or skips: domain 211, data sports 67, live sports 95, settings-sports 5. Tests cover release-gate bypasses, missing review/rights/credit,-blocked artwork, TV identity/deduplication/countries, malformed/empty data,-standing scope and season, authentication/quota/server failures, account edits,-metadata identity, event states, TV fanout/cooldowns, cancellation, channel-matching priority, preserved EPG mappings, and credit provenance.--Localization verification passed 380 values across all 38 advertised locales:-eight new standings labels, new settings attribution, and the reused live-attribution template. Every key is present once, nonempty, and preserves its-formatting contract. Translations are actual localized text.--Evidence:--- `../artifacts/plan4-validation.log`-- `../artifacts/plan4-release-compile.log`-- `../artifacts/plan4-tests.txt`-- `../artifacts/plan4-localization.txt`--The initial build exposed the missing import above and existing configuration-cache incompatibility in verifyFeatureLiveBoundary. Final verification uses-`--no-configuration-cache`; the unrelated Gradle task was not changed.--Phase 4.3 follow-up verification passed:--```powershell-.\gradlew.bat :data:testDebugUnitTest --tests 'com.streamvault.data.sports.balldontlie.*' --no-configuration-cache --console=plain-.\gradlew.bat :feature:live:testDebugUnitTest --tests '*SportsProviderEventResolverTest' --no-configuration-cache --console=plain-.\gradlew.bat :app:assembleDebug :app:compileReleaseKotlin --no-configuration-cache --console=plain-```--The BALLDONTLIE provider fixture suite passed 8 tests, and the API-first-to-EPG-resolver suite passed 6 tests, with zero failures or errors. The last command-verifies app registration in the debug assembly and release Kotlin-compilation. All Phase 4.3 data validation is offline against-documented-response fixtures; no BALLDONTLIE credential or live account was-used.--## Emulator verification--Started the existing `SportsHub_Worktree_20261016` AVD on port 5590 at the user's-request. The default graphics boot stalled before system_server was available.-A cold start using `-no-snapshot -gpu swiftshader` booted successfully without-wiping user data. The other emulator was not changed.--Installed the updated debug APK with `adb -s emulator-5590 install -r` and-launched the app. Existing IPTV channels and app data remain present. Navigated-with the TV remote controls to Settings > Sports > Sports data providers.-The list displays TheSportsDB's seven implemented capabilities and Custom JSON.-TheSportsDB and Highlightly show a Beta notice that live-account validation is-pending. The Custom JSON form offers an Insert example action and localized-setup guidance. Opened TheSportsDB's Add Provider dialog and visually confirmed provider credit,-league scope, masked Premium credential field, and connection-test controls.-Evidence: `../artifacts/plan4-provider-dialog.png`.--**Live provider validation remains pending:** this AVD has no configured Sports-data provider. The user confirmed they do not have a Premium key and explicitly requested-leaving the live provider test pending. TheSportsDB is shown as Beta until a real-Premium-account check can be completed. No credentials were read/exported, no provider was saved with fake or-shared credentials, and no live API success is claimed. The real-device checkbox-remains open until Premium connection, events/scores/standings, credit on real-provider data, and broadcaster-to-local-channel behavior can be observed.--For the Phase 4.3 UI check, the updated debug APK was installed on-`emulator-5590`. Settings > Sports data providers listed BALLDONTLIE, and its-Add Provider form exposed the shared localized league-scope and API-key fields.-The unsaved form was dismissed without credentials; no BALLDONTLIE connection-test or API request was run.--## Phase 4.4 — Highlightly--Implemented the direct All Sports adapter with one key header, 11 sport-prefix-routes, bounded UTC-date match pagination, live score/status mapping, standings,-and basic team/league metadata. Response quota headers and plan-tier envelope-data are tracked per credential fingerprint and displayed in Sports provider-settings when present. The adapter does not call artwork, odds, lineups,-statistics, highlights, video, or playback endpoints. Scope syntax, terms review,-request/cache bounds, and the live-test limitation are documented in-`sports/providers/highlightly.md`.--Fixture tests passed for multi-prefix schedule pagination, score/status data,-football and NBA standings, metadata, quota sharing, invalid scopes, request-bounds, direct authentication, and sanitized rate-limit failures. Localization-verification covers the two quota labels in all 38 advertised locales. Highlightly-is shown as Beta until live-account testing is possible; no account key is available.--For any live playback stuckness investigation, follow the repository's full-2-second screenshot cadence and media-session/log checks. No live playback bug-was reported or claimed fixed in this change.--## Phase 4.5 — Sportmonks--Skipped per the user's instruction on 2026-10-17. No contact was made with-Sportmonks. Their public documentation recommends middleware to protect API-tokens but does not answer the Plan 4 direct native-BYOK question. The release-gate is therefore uncleared; no Sportmonks adapter is present or enabled.--## Phase 4.6 — football-data.org review--Official terms and API documentation were reviewed on 2026-10-17. The-registration terms explicitly allow the API key to be used by one application-in web and/or mobile form on any platform, require the key owner to keep their-credentials confidential, and require attribution. StreamVault uses each-user's own key in the one StreamVault Android application, stores it in the-existing encrypted no-backup provider store, and sends it only in the-`X-Auth-Token` request header. No shared key, cloud sync, URL token, or artwork-is used. This supports the single-application/BYOK design. The adapter follows-the most restrictive published request tier (10 requests/minute) and clears-that credential's response cache after a 401/403 so data from a lost-subscription is not reused.--Official sources:--- https://www.football-data.org/client/register-- https://www.football-data.org/documentation/faq-- https://www.football-data.org/pricing-- https://docs.football-data.org/general/v4/index.html-- https://docs.football-data.org/general/v4/lookup_tables.html--The adapter uses the shared token-entry/connection-test form, maps fixtures,-score/status, and total/group standings, and displays the provider's required-attribution on event and standings surfaces. Fixture requests are bounded to-14 days and 500 matches, score/status requests to 50 match IDs, and local-traffic to 10 requests/minute. Schedule, score, and standings responses use-short bounded in-memory caches keyed by configuration revision and credential-fingerprint; a 401/403 clears that credential's cached results. Logos and-artwork are not requested. Details and offline verification are recorded in-`sports/providers/football-data.md`.--The first fixture review found that distinct time ranges on one calendar date-could share the same filtered-event cache key. The key now includes the exact-request instants, and a same-day, two-window fixture case covers the regression.--## Phase 4.7 — OddsPapi prototype--Official public terms and API docs were reviewed on 2026-10-17. The adapter-uses the documented `apiKey` query parameter; the shared transport does not log-request URLs and returns only typed errors without response bodies. It maps-bounded fixtures, participants, state, and period scores. It observes the-documented fixture/detail and score endpoint cooldowns, caches by credential-fingerprint/config revision, clears that credential's cache on 401/403, and-does not request or expose odds-related products.--OddsPapi's terms say API keys are personal and prohibit standalone data resale,-but direct paid-app display is not explicitly covered. No contact was made.-The adapter is marked `CONDITIONAL` with `REQUIRES_VENDOR_CONFIRMATION`, so the-production registry excludes it. The debug policy enables the prototype for-offline development only. See `sports/providers/oddspapi.md` and the live-provider-use gate in the main plan.--Offline OddsPapi fixture suite passed five tests, covering the production gate,-query-key placement and sanitized errors, fixture mapping/range filtering,-score aggregation and cached state, and the strict unscoped date-window limit.-No live OddsPapi account or credential was used.--## Phases 4.8–4.10 — remaining provider gates--On 2026-10-17, API-SPORTS and SportDB.dev public terms were reviewed, and the-official SportDevs terms URL was retried but returned HTTP 502. API-SPORTS'-terms withhold publication permission and assign third-party sports rights to-the user; its gate remains `DO_NOT_SHIP`. SportDB.dev requires a paid plan for-production and leaves paid-app data display unclear; its gate remains-`REQUIRES_VENDOR_CONFIRMATION`. SportDevs remains `DO_NOT_SHIP` pending a-successful terms review. No messages were sent and no adapters were added for-these three conditional services.--SportsDataIO and Sportradar are deferred because there is no customer-request or property-specific agreement in this task.--OpenLigaDB's official site states that API data are under ODbL 1.0. The review-recorded the Produced Work attribution requirement, derivative-database-share-alike conditions, 60-requests/minute-per-IP API limit, and separate logo-rights. The optional adapter now shows linked source/license credits and keeps-only bounded, short-lived raw JSON in process memory. It does not persist a-normalized or merged database and ignores team-logo URLs. Offline fixtures-cover connection probe, event window/status, final score selection, standings,-scope limits, release gating, and raw-cache bounds. No live account was used.-See `sports/providers/conditional-and-open-data-review-2026-10-17.md` and-`sports/providers/openligadb.md`.--## Verification added in this continuation--- OpenLigaDB: six offline fixture tests passed for the release gate, connection- probe, season event mapping/date filter, score/status cache reuse, standings,- scope/range bounds, and raw response-cache limits.-- OddsPapi: five offline fixture tests passed, including the quota-free- `/account` connection probe.-- Full unit suites passed for `data` (1,455), `domain` (211), and `feature:live`- (209). Debug compilation of `data`, `feature:live`, and `feature:settings`,- plus production `app:compileReleaseKotlin`, succeeded.-- `feature:settings:testDebugUnitTest` ran 81 tests: 80 passed and the existing- `SettingsLocalizationCoverageTest` failed for `values-ar/settings_redesign.xml`- (67 expected keys missing and eight unexpected plural entries). That- navigation/redesign resource set was not changed here. The Plan 4 provider- keys were separately checked in all 38 advertised locales with matching- positional placeholders.diff --git a/docs/Sports-PLAN-v2.md b/docs/Sports-PLAN-v2.mddeleted file mode 100644index b4f2415c..00000000--- a/docs/Sports-PLAN-v2.md+++ /dev/null@@ -1,2326 +0,0 @@-# StreamVault Sports Hub — Revised Implementation Plan (EPG-First + Resilience Enhancements)--**Status:** Supersedes the previous Sports plan for future work.-**Baseline:** Existing implementation on `codex/sports-integration`, based on the supplied `Sports-PLAN.md` and `Sports-IMPLEMENTATION.md`.-**Core rule:** Keep the Sports Hub EPG-first. Do not introduce ESPN, Apple, scraping, reverse-engineered sports providers, or a new backend.-**Goal of this revision:** Preserve every unfinished requirement from the original plan, keep the work that is already implemented, and add useful event-discovery and resilience improvements.-------# 0. Agent instructions--This is an **incremental continuation plan**, not a greenfield rewrite.--Before changing code:--1. Read the current Sports implementation and the existing integration map.-2. Treat items marked **Implemented** below as existing behavior that should be preserved unless a later section explicitly changes them.-3. Do **not** rebuild already-working features merely to match class/file names suggested in this document.-4. Reuse the existing StreamVault EPG resolution and playback paths.-5. Prefer targeted improvements over architecture churn.-6. Add tests before materially expanding heuristics.-7. Do not add any remote sports-data provider in this plan.-8. Do not add ESPN integration.-9. Do not add Apple Sports integration.-10. Do not add scraping of sports sites.-11. Do not add unauthorized stream discovery/resolution.-12. Do not add a new backend.-13. Do not persist a second Sports database/index unless the EPG refresh architecture later exposes enough change information to make incremental updates reliable.-14. If an implementation detail in this plan conflicts with an existing, better StreamVault abstraction, keep the StreamVault abstraction and satisfy the behavior instead.--The implementation must remain useful with:--```text-User XMLTV / EPG-+-User M3U / Xtream-```--only.-------# 1. Current implementation baseline--The current branch already implements a substantial part of the original plan.--## 1.1 Already implemented — preserve--- [x] Sports top-level navigation and route.-- [x] Active provider / combined-profile awareness.-- [x] Existing resolved EPG-to-channel mapping is reused.-- [x] Hidden/adult/protected channel filtering before Sports playback choices.-- [x] EPG-based sports classification.-- [x] Initial sport classification from title, description, genre/category, and channel metadata.-- [x] Initial league recognition.-- [x] Initial team alias support.-- [x] Event candidate generation.-- [x] Event fingerprinting.-- [x] Duplicate-event grouping with a 15-minute start-time tolerance.-- [x] Multiple playable broadcasts retained on a single event.-- [x] On Now / Today / Upcoming.-- [x] Seven-day Upcoming horizon.-- [x] Sport filtering.-- [x] League filtering.-- [x] Playable-channel counts.-- [x] Sports event details dialog.-- [x] Playback through the existing StreamVault live player.-- [x] Five-minute in-memory Today/Upcoming cache.-- [x] Cache invalidation for EPG/source/profile/visibility changes.-- [x] Optimized normalization pattern reuse.-- [x] Reused event fingerprints during assembly.-- [x] Diagnostic logging behind `SportsHub` DEBUG.-- [x] CPU microbenchmark through 50,000 synthetic programmes.-- [x] Localized Sports UI labels.-- [x] Kotlin compilation and translation-key checks.--These features are not to be reimplemented from scratch.-------# 2. What remains from the original plan--Every unfinished item from the previous plan remains in scope unless explicitly deferred here.--## 2.1 Domain/model depth--- [x] Add richer competitor modeling with display and canonical names.-- [x] Add richer league modeling where useful: recognized leagues now carry a stable canonical ID, display name, sport, and normalized aliases through classification and event assembly.-- [x] Keep status semantics clearly "broadcast schedule status" unless enriched by a future score provider.-- [x] Ensure the model handles team sports and non-team sports without forcing a two-team shape.-- [x] Add direct unit coverage for domain behavior.--## 2.2 Classification--- [x] Broaden classifier fixture coverage.-- [x] Improve international sport/competition recognition from the configured guide.-- [x] Improve negative classification for sports news, previews, replays, highlights, studio shows, documentaries, and post-game programmes.-- [x] Ensure missing category/genre data does not prevent strong title/description detection.-- [x] Ensure generic `Sports` category alone does not incorrectly turn studio programming into competitive events.--## 2.3 Normalization--- [x] Broaden team aliases.-- [x] Broaden league aliases.-- [x] Add better punctuation/Unicode normalization.-- [x] Add Sports-owned normalization/indexing for IPTV channel names, preserving language/region qualifiers while grouping quality decorations for matching.-- [x] Improve non-team sport title cleanup.-- [x] Keep aliases structured/data-driven rather than scattering replacements across code.--## 2.4 Event extraction--- [x] Introduce a dedicated event parser boundary for title and event/session extraction.-- [x] Parse competitors more reliably.-- [x] Parse event type/session for non-team sports.-- [x] Preserve raw EPG programme records for diagnostics/fallback presentation.-- [x] Never invent competitors when evidence is weak.--## 2.5 Deduplication--- [x] Add confidence checks and compatibility signals to event matching.-- [x] Add false-positive tests.-- [x] Handle same teams playing more than once in one day.-- [x] Prevent replay/highlight programmes from merging into a live/upcoming event.-- [x] Handle team aliases across language variants.-- [x] Support wider time tolerance for non-team sports than for team fixtures.--## 2.6 Repository/index architecture--- [x] Keep the current bounded in-memory cache for now.-- [ ] Optionally extract loading/caching behind a feature-owned `SportsRepository` if this materially improves separation/testability.-- [x] Do **not** add a durable duplicate Sports table yet; Sports remains derived from persisted EPG programmes.-- [ ] Revisit incremental indexing only after the EPG refresh layer can expose changed programme IDs and affected source/channel/time ranges.--## 2.7 Runtime/device verification--- [x] Test with a real configured playlist + EPG on the isolated AVD.-- [x] Verify the observed WSL event appears once with its two mapped channel choices.-- [ ] Verify every surfaced playback option actually launches the expected stream; Golf passed its two-minute check, but both WSL choices still fail progression. The 2026-10-16 retest captured 61 frames at two-second intervals for each choice: FHD froze after HLS first-frame success and decoder stalls; HD stayed buffering after a network timeout.-- [ ] Verify switching provider/combined profile refreshes Sports correctly; the isolated AVD currently has only one saved Xtream provider and no combined profile, so switching could not be exercised without changing the user's setup.-- [ ] Exercise Sports invalidation after a provider EPG refresh and a standalone external-guide refresh; this AVD has no external guide source, and its provider sync dialog exposes no EPG-only refresh. No provider/catalog sync was run for this check.-- [x] Verify visibility changes refresh Sports correctly; hiding one channel changed the Sports input from 28,398 to 28,397 visible rows, and unhiding it restored 28,398 on refresh.-- [x] Verify Today/Upcoming cache hits using remote navigation and fresh UI state; confirmed revisits took 6.6 s for Today and 5.5 s for Upcoming. A later same-process Today revisit logged a `window-cache-hit` at 0 ms and retained the expected 564-channel UI.-- [x] Measure actual Room/resolution cost, not only CPU classification cost. Debug-only stage logs measured 28,398 visible channel rows per range; resolved-program loading took 0.57 s On Now, 4.5–9.8 s Today, and 1.02 s Upcoming. This is an aggregate resolution path, not per-statement Room profiling.-- [x] Review D-pad focus and card readability on the 1920x1080 Android TV AVD; physical TV hardware remains unverified.--## 2.8 Test coverage--- [x] Unit tests for classification.-- [x] Unit tests for aliases/normalization.-- [x] Unit tests for competitor extraction.-- [x] Unit tests for league extraction.-- [x] Unit tests for fingerprints.-- [x] Unit tests for deduplication.-- [x] Unit tests for conservative channel fallback matching, date rejection, protected/unplayable filtering, scoring, and direct-mapping precedence.-- [x] Unit tests for broadcast status calculation.-- [x] Fixture-driven XMLTV tests for categorized/minimal guides, exclusions, non-team events, and duplicate broadcasts.-- [x] M3U + XMLTV fixtures for the current resolved path (exact, missing, unresolved, and duplicate-event cases; data-layer persistence/override tests pass). Future event-channel fallback tests belong to Phases E/F.-- [x] Run the adapted `LiveGraphBehaviorTest`.-------# 3. Core architecture — keep EPG-first--The primary architecture remains:--```text-XMLTV / EPG- |- v-resolved EPG programmes for active playable channels- |- v-Sports classification- |- v-event extraction- |- v-normalization- |- v-deduplication- |- v-canonical SportEvent- |- v-playable channel choices already associated with the EPG- |- v-Sports UI- |- v-existing StreamVault live player-```--This is intentionally different from an event-first sports discovery model.--An event-first sports app starts with an external event and searches for the user's matching IPTV channel.--StreamVault starts with an EPG programme that is normally **already associated with a channel**.--Therefore:--> Existing EPG/channel resolution is always the primary and highest-confidence path.--No fallback matcher should replace a working EPG → channel mapping.-------# 4. Revised channel-resolution strategy--The current implementation already resolves EPG programmes to playable StreamVault channels.--Keep that as **Tier 0**.--Add channel-discovery fallbacks only for unresolved or incomplete cases.--## Tier 0 — existing StreamVault resolved mapping--Use the existing resolved-program path.--Conceptually:--```text-EPG programme- |- v-existing StreamVault mapping- |- v-playable channel-```--This is the normal path and should dominate all other signals.--If this succeeds, no channel-name fuzzy search is needed merely because it exists.--## Tier 1 — exact EPG/channel identifiers--Where the underlying mapping exposes identifiers such as:--```text-XMLTV channel id-M3U tvg-id-Xtream channel mapping-persisted user channel mapping-```--keep exact identity as the strongest specific signal.--This may already be encapsulated by the existing resolved-program path.--Do not duplicate that matching logic in Sports.--## Tier 2 — temporary/event-named IPTV channel fallback--**New channel-discovery improvement.**--Use only when a Sports event has no usable direct playback choice, or when the user explicitly opens "Find another channel."--Many IPTV providers expose temporary event channels such as:--```text-EPL | Arsenal vs Liverpool-NHL | Kraken @ Red Wings-UFC 330 | Fighter A vs Fighter B-F1 | Japanese Grand Prix-```--Build a fallback matcher capable of finding these from the user's existing channel list.--The fallback must not introduce any external streams.--### Team-sport matching--Require strong evidence.--For a two-team event, prefer:--```text-one alias from team A-+-one alias from team B-```--in the channel name.--Examples:--```text-"Arsenal vs Liverpool"-"Arsenal - Liverpool"-"Liverpool @ Arsenal"-```--should match.--A channel containing only `Arsenal` should normally not auto-match a single event when multiple Arsenal programmes/channels could exist.--### Fight matching--Use:--```text-fighter A full name or distinctive surname-+-fighter B full name or distinctive surname-```--Avoid short/common surnames as sole evidence.--### Racing/golf/event sports--Use event or series phrases:--```text-Japanese Grand Prix-Formula 1-F1-PGA Tour-The Open-```--Prefer event-specific phrase matches over generic series matches.--### Matching policy--Temporary/event-named channel matching should be:--- deterministic where possible;-- confidence-ranked;-- explainable in diagnostics;-- non-destructive;-- used as fallback, not as replacement for EPG mapping.-------# 5. Date-aware temporary-channel matching--**New event-resolution improvement.**--Temporary event channels can survive after the event or may include future/past dates.--Recognize common date patterns in channel names:--```text-Oct 18-18 Oct-2026-10-18-18/10-10/18-```--Only use ambiguous numeric dates where locale/source context makes them safe enough; otherwise treat them as weak evidence.--If a channel contains a recognizable date:--- require it to be compatible with the event date;-- allow a small timezone tolerance around UTC/local-day boundaries;-- reject an obviously different event date.--Example:--```text-EPL | 18 Oct | Arsenal vs Liverpool-```--must not be auto-selected for the next Arsenal/Liverpool meeting months later.--Date awareness should increase confidence, not become the only required signal.-------# 6. Fallback matcher indexing--**New performance improvement.**--Do not scan every channel with expensive regex/fuzzy logic separately for every event.--If temporary-channel fallback is introduced, build an index once per effective channel list.--Suggested reusable data:--```text-normalized channel name-token -> channel indexes-canonical channel key -> channel indexes-EPG id -> channel indexes-channel id -> index-```--Conceptual structure:--```kotlin-data class SportsChannelIndex(- val channels: List<Channel>,- val normalizedNames: List<String>,- val tokenIndex: Map<String, IntArray>,- val byCanonicalName: Map<String, IntArray>,- val byEpgId: Map<String, IntArray>-)-```--The exact representation should follow existing StreamVault structures.--### Index invalidation--Rebuild only when the effective playable-channel set changes, e.g.:--- active provider changes;-- combined-profile membership changes;-- playlist refresh changes channels;-- visibility rules materially change the available channel set if hidden channels are excluded at index time.--Do not rebuild on every Sports recomposition.-------# 7. Channel fallback scoring--Add a testable, explainable score only for fallback candidates.--Example initial signals:--```text-both competitors present in channel name +100-event title phrase strongly present +90-recognized matching date present +20-series/league phrase present +15-preferred known channel mapping +15-quality/source preference +small bias-language/region preference match +small bias-obviously wrong date reject-only one team with no other evidence weak / do not auto-select-```--Calibrate ranking weights to this app's own data instead of reusing external weights.--Tune against fixtures and real user IPTV data.--Return a reason model:--```kotlin-enum class SportsChannelMatchReason {- RESOLVED_EPG,- EXACT_IDENTIFIER,- EVENT_CHANNEL_NAME,- REMEMBERED_EVENT_PICK,- REMEMBERED_TEAM_PICK,- REMEMBERED_SERIES_PICK,- MANUAL_SELECTION-}-```--If a generic broadcaster/network alias fallback is later added, give it its own reason and keep it lower confidence than event-specific evidence.-------# 8. Manual correction and remembered channel choices--**New sports-hub product improvement.**--Automatic mapping will never be perfect across all IPTV providers.--Give the user a manual correction path.--## 8.1 Event details action--When viewing an event:--```text-Watch on-- beIN Sports 1-- SuperSport LaLiga--Find another channel-```--`Find another channel` searches only the user's configured playable channels.--No external provider data is involved.--## 8.2 Selection modes--After selecting a channel, support these scopes where meaningful:--```text-Use for this event-Always prefer for this team-Always prefer for this league/series-```--Do not force all three options for every sport.--Suggested applicability:--### Team sports--```text-this event-this team-```--Optionally:--```text-this league-```--only if real-world testing shows it is useful and not overbroad.--### Racing--```text-this event-this series-```--Example:--```text-Prefer Sky Sports F1 for Formula 1-```--### Golf--```text-this event-this series-```--### Fighting--Usually:--```text-this event-this promotion/series-```--A persistent fighter-to-channel mapping is unlikely to be useful.--## 8.3 Precedence--Recommended:--```text-event pick- >-team/series preference- >-direct resolved EPG mapping (when user has explicitly overridden)- >-automatic fallback candidate-```--However, be careful:--A remembered preference must not silently route to a channel that is not currently carrying the event.--For persistent team/series preferences, require at least one corroborating signal:--- EPG currently shows the event on the channel; or-- channel name currently identifies the event; or-- user explicitly chooses "play anyway" from manual results.--An old preference is a ranking hint, not proof that the event is airing there today.--## 8.4 Expiry--Event-specific picks should expire automatically after a short period.--Example:--```text-7 days-```--Team/series preferences may persist until removed.--## 8.5 Forget action--Provide:--```text-Forget this choice-```--or equivalent.--Do not trap the user in a bad remembered mapping.-------# 9. Channel-name normalization improvements--Extend existing normalization only as needed for fallback matching.--Common noise:--```text-HD-FHD-UHD-4K-HEVC-H265-H.265-RAW-VIP-Backup-Alt-Feed-```--Examples:--```text-BEIN SPORTS 1 FHD [AR]-beIN Sports 1 HD-BEIN 1 UHD-```--Normalization should separate:--```text-canonical identity-quality-language hint-country/region hint-source/provider decoration-```--Do not discard useful qualifiers too early.--For example:--```text-beIN Sports 1 AR-beIN Sports 1 EN-```--may need to remain distinguishable to the user even if both map to the same broadcaster family.-------# 10. Region/language ranking--Support following teams without hardcoding a US/CA/UK-first region preference.--StreamVault is international.--Use:--1. user's app language where relevant;-2. explicit playlist/channel language metadata where available;-3. provider/group metadata;-4. user channel history/preferences if an existing safe abstraction already exists;-5. otherwise neutral ordering.--Do not globally downgrade Arabic, French, Spanish, German, etc.--A channel should only receive a regional/language preference bonus if it aligns with known user/source context.--This is a ranking refinement, never a reason to hide legitimate alternatives.-------# 11. Duplicate broadcast/channel presentation--Keep all valid playable choices, but reduce UI clutter.--Example raw channels:--```text-beIN Sports 1 HD-beIN Sports 1 FHD-beIN Sports 1 4K-beIN Sports 1 Backup-```--Possible UI:--```text-beIN Sports 1- 4 sources-```--Selecting the group opens the variants.--Alternatively, if StreamVault already has a source-priority abstraction, use it to choose a primary variant while keeping the others accessible.--Do not silently discard alternatives.--Do not incorrectly collapse channels that only look similar but represent different language/region feeds.-------# 12. Optional event zap-list behavior--**Optional team-following enhancement.**--When an event has multiple matched playable channels:--```text-Barcelona vs Real Madrid--beIN Sports 1-SuperSport-Arena Sport-```--consider passing those channels as an event-specific zap list to the existing player if the player architecture supports it cleanly.--Then:--```text-CH+-CH--```--could cycle through only the channels carrying that event.--This is optional and should only be added if:--- it fits the current live-player abstraction;-- it does not complicate the player substantially;-- it preserves normal navigation/back behavior.--Do not create a separate Sports player.-------# 13. Event model refinement--The current model should evolve toward an event shape that supports both team and non-team sports.--Avoid a mandatory:--```text-homeTeam-awayTeam-```--core model.--Prefer:--```kotlin-data class SportEvent(- val id: String,- val sport: SportType,- val league: SportLeague?,- val title: String,- val competitors: List<Competitor>,- val session: String?,- val startTime: Instant,- val endTime: Instant?,- val scheduleStatus: BroadcastScheduleStatus,- val eventType: SportEventType,- val broadcasts: List<BroadcastOption>,- val confidence: Float,- val rawProgrammeRefs: List<String>-)-```--Exact fields may differ from existing implementation.--The important behavior is:--- zero competitors allowed;-- one competitor allowed;-- two competitors allowed;-- many competitors allowed;-- event/session title remains first-class.-------# 14. Non-team sports — make this a first-class remaining task--The existing implementation still needs broader non-team event cleanup.--Treat the following as separate shapes.--## 14.1 Motorsport--Recognize:--```text-Formula 1-F1-NASCAR-IndyCar-MotoGP-```--and sessions:--```text-Practice-FP1-FP2-FP3-Sprint Qualifying-Sprint-Qualifying-Race-```--Example canonical display:--```text-Formula 1-Japanese Grand Prix — Qualifying-Saturday · 09:00-```--Do not attempt to invent competing "teams" from the EPG.--## 14.2 Golf--Recognize tournament + round/session when available:--```text-The Open Championship — Round 3-PGA Tour — Final Round-```--Do not require player lists.--## 14.3 Combat sports--Recognize:--```text-UFC-PFL-boxing-Fight Night-Main Card-Prelims-```--If two fighters are clearly named, store competitors.--If only a card name exists:--```text-UFC 330 — Main Card-```--is still valid.--## 14.4 Tennis--Support both:--```text-Carlos Alcaraz vs Jannik Sinner-```--and generic tournament programming:--```text-ATP Madrid — Quarterfinals-```--## 14.5 Other field/tournament sports--Ensure the fallback model can represent:--```text-cycling-athletics-snooker-darts-multi-team tournaments-```--without forcing a team matchup.-------# 15. Event type classification--Implement/finish:--```kotlin-enum class SportEventType {- LIVE_EVENT,- SCHEDULED_EVENT,- REPLAY,- HIGHLIGHTS,- PREVIEW,- PRE_GAME,- POST_GAME,- SPORTS_NEWS,- SPORTS_SHOW,- UNKNOWN-}-```--Use title/subtitle/description/category signals.--Examples:--```text-Replay-Full Match Replay-Encore-Repeat-Highlights-Match Highlights-Pregame-Pre-Game-Postgame-Post-Match-Preview-Review-Sports News-```--Rules:--- replay must not merge into the original live event merely because competitors match;-- highlights must not appear in the default upcoming/live competition row;-- generic shows may optionally live in a later `More Sports` section;-- do not discard them from the data model if preserving them is cheap.-------# 16. Classification pipeline refinement--Continue reading all useful EPG information:--```text-title-subtitle-description-categories/genres-keywords if available-channel name-channel group-EPG live/repeat flags if available-start/stop-```--Suggested classification output:--```kotlin-data class SportsClassification(- val isSports: Boolean,- val isCompetitiveEvent: Boolean,- val sport: SportType,- val eventType: SportEventType,- val league: SportLeague?,- val confidence: Float,- val reasons: Set<ClassificationReason>-)-```--Keep reasons diagnostic-friendly.-------# 17. Alias registry expansion--Maintain structured alias data.--Required categories:--```text-team aliases-league aliases-sport aliases-event-series aliases-broadcaster/channel aliases where needed-```--Examples:--```text-Manchester United-Manchester Utd-Man Utd-MUFC-```--=>--```text-Manchester United-```--```text-English Premier League-Premier League-EPL-```--=>--```text-Premier League-```--For non-team sports:--```text-Formula One-Formula 1-F1-```--=>--```text-Formula 1-```--Avoid overly aggressive short aliases that create false positives.--For example, a three-letter team abbreviation should generally require sport/league/context support before being treated as definitive.-------# 18. Event identity and deduplication v2--Current identity + 15-minute grouping is useful and should remain.--Strengthen it with an explainable confidence layer.--## 18.1 Team events--Signals:--```text-same sport-same league-same canonical competitor set-start-time proximity-title similarity-```--Do not rely on title similarity alone.--## 18.2 Same teams twice in one day--Do not merge two distinct games if:--- start times are clearly different;-- league/competition differs;-- one is a replay;-- one is a youth/women/reserve variation;-- one title includes a materially different competition/session.--## 18.3 Multi-language broadcasts--These should merge when canonical competitors/league/time strongly agree.--## 18.4 Non-team sports--Fingerprint from:--```text-sport-series/league-canonical event title-session-date/start bucket-```--Example:--```text-motorsport|formula1|japanese-grand-prix|qualifying|2026-10-17-```--Race and qualifying must remain separate.-------# 19. Confidence model--Use configuration/constants that tests can tune.--Illustrative team-event score:--```text-same canonical competitor pair +50-same league +15-same sport +15-start within 5 minutes +20-start within 15 minutes +15-strong normalized title agreement +15-same event type +10-different sport reject-different known competition -30-explicit different competitor reject-replay vs live reject merge-```--Do not hardcode these exact values without fixture validation.--The objective is not "maximum fuzzy merging."--The objective is:--> merge confidently identical broadcasts while avoiding incorrect collapse.-------# 20. Sports repository/index decision--For the current architecture:--## Keep--```text-persisted EPG programmes = source of truth-bounded in-memory Sports snapshots = derived cache-```--## Do not yet add--```text-duplicate persisted Sports event table-```--because the current EPG refresh boundary does not expose reliable changed-program deltas.--## Optional refactor--A feature-owned repository is acceptable if it improves:--- testing;-- ViewModel size;-- cache ownership;-- event query semantics.--Possible interface:--```kotlin-interface SportsRepository {- fun observeOnNow(): Flow<List<SportEvent>>- fun observeToday(): Flow<List<SportEvent>>- fun observeUpcoming(): Flow<List<SportEvent>>- suspend fun refresh(force: Boolean = false)-}-```--But repository extraction is **not** the same thing as a persisted index.--Do not perform it purely for architectural aesthetics.-------# 21. Refresh behavior--Preserve current invalidation behavior.--Sports should refresh when:--```text-provider EPG refresh succeeds-external EPG source refresh succeeds-source assignment changes-combined-profile membership changes-channel/category visibility changes-local day rolls over-selected time window changes-```--On Now may continue to refresh on a short interval because broadcast-state labels change with time.--Avoid reparsing unrelated future windows during every On Now tick.-------# 22. Broadcast-state semantics--Without a score provider:--```text-now < start => UPCOMING-start <= now < end => AIRING / ON NOW-now >= end => ENDED-```--This is **broadcast schedule state**.--Do not imply independently verified match state.--Use UI wording deliberately.--Preferred default:--```text-ON NOW-```--unless StreamVault's existing TV-guide semantics already call a currently airing programme `LIVE`.--If an EPG explicitly marks the programme live, a `LIVE` badge is appropriate.-------# 23. Live scoring — unchanged architectural decision--Do not add a live-score provider in this plan.--Keep scoring optional.--Desired future boundary:--```kotlin-interface LiveScoreProvider {- suspend fun scoreFor(event: SportEvent): LiveScore?-}-```--Potential model:--```kotlin-data class LiveScore(- val competitorScores: Map<String, String>,- val state: GameState?,- val clock: String?,- val period: String?,- val lastUpdated: Instant-)-```--The Sports UI must remain fully functional with:--```text-score == null-```-------# 24. Future user-configured scoring--Keep this as a future investigation, not current implementation.--Potential directions:--```text-user supplies API key for a supported provider-user supplies a compatible endpoint/plugin-commercially licensed provider added later-```--Any future integration must be evaluated separately for:--```text-terms-commercial use-rate limits-client-side secret safety-attribution-redistribution-availability-sport coverage-```--Do not let a score provider become the canonical source of Sports events.--The flow should remain:--```text-EPG SportEvent- +-optional score enrichment-```-------# 25. My Teams — possible EPG-first version, not required now--The sports hub can offer a My Teams feature backed by schedule data.--StreamVault should **not** copy that external dependency.--However, a future EPG-first version is possible:--```text-user follows canonical team alias- |- v-Sports events already detected from EPG- |- v-filter/rank events involving followed team-```--This would require no remote API.--Possible future behavior:--```text-My Teams-- Manchester United-- Real Madrid-- Lakers-```--and show only events found in the user's guide.--This is optional and outside the immediate implementation phases below.--Do not implement standings under the current EPG-only model because EPG does not provide a standardized standings dataset.-------# 26. League manager — EPG-first interpretation--Do not build a static ESPN-slug catalogue.--Instead, if a richer league manager is desired later:--```text-Detected leagues from user's EPG-+-curated StreamVault alias catalogue-```--Users can:--```text-show/hide detected leagues-reorder preferred leagues-```--A league should only appear as active when StreamVault has seen relevant EPG content, unless it is presented as a generic filter preset.--This avoids maintaining a fake catalogue disconnected from the user's guide.-------# 27. Sports hub UX improvements worth adopting--## 27.1 Strong focused-card behavior--Review Sports TV focus behavior on-device.--The focused card must clearly identify:--```text-event-status/time-league/sport-available playback choices-```--without making selected filters visually compete with current focus.--## 27.2 Direct OK behavior--Recommended:--If exactly one high-confidence playable channel exists:--```text-OK -> play-```--If multiple choices exist:--```text-OK -> event details/channel choice-```--If no channel is resolved:--```text-OK -> event details + Find another channel-```--Long-press behavior is optional; only add it if StreamVault already has a stable TV long-press interaction convention.--## 27.3 Manual picker--Search suggestions should prioritize:--```text-event-named channels-recognized team names-league/series names-existing related mapped channels-```--The picker should remain usable by normal text search.--## 27.4 Preserve D-pad stability--When filters/lists reorder, keys/stable item identity should prevent focus-node confusion.--Use stable event IDs and stable filter IDs.--Do not rely on list position as identity.-------# 28. Event card information hierarchy--Recommended:--```text-[SPORT / LEAGUE]--FC Barcelona-vs-Real Madrid--ON NOW / 21:00--2 channels-```--Non-team example:--```text-FORMULA 1--Japanese Grand Prix-Qualifying--Saturday · 09:00--1 channel-```--Fallback generic example:--```text-FOOTBALL--Live Spanish Football--ON NOW--beIN Sports 1-```--Never fabricate teams or event detail.-------# 29. Event details--Keep the current details dialog and extend only as needed.--Display:--```text-canonical event title-sport-league-event/session type-schedule-raw/clean description-playback choices-match reason where useful in diagnostics or picker-```--Optional user-facing source labels:--```text-From guide-Found by channel name-Your saved choice-```--Use plain language, not internal scoring values.-------# 30. Search for another channel--New flow:--```text-Event details- |- +-- existing mapped channels- |- +-- Find another channel- |- v- fallback search- |- +-- event-name candidates- +-- team candidates- +-- series candidates- +-- manual text results-```--Results must be limited to the user's currently playable/allowed channel set.--Respect:--```text-hidden channel rules-adult/protected filtering-active provider / combined profile-source membership-```--Do not let Sports bypass normal StreamVault visibility rules.-------# 31. Testing — mandatory before more heuristic expansion--Testing is the most important unfinished original area.--## 31.1 Classification unit tests--Include:--```text-Barcelona vs Real Madrid-FC Barcelona - Real Madrid CF-Live Premier League Football-LaLiga Football-Formula 1 Japanese GP Qualifying-Japanese Grand Prix - Race-UFC 330-UFC 330 Main Card-NBA Basketball-ATP Madrid: Alcaraz vs Sinner-SportsCenter-Match of the Day-Football Highlights-Premier League Preview-Post Match Show-Sports Documentary-```--Assert:--```text-isSports-isCompetitiveEvent-sport-eventType-league-confidence band-```--where relevant.--## 31.2 Alias tests--Cover:--```text-Manchester United / Man Utd / MUFC-FC Barcelona / Barcelona / Barça-Bayern München / Bayern Munich-Borussia Dortmund / BVB-Premier League / EPL-Champions League / UCL-Formula 1 / Formula One / F1-```--Include false-positive aliases.--## 31.3 Event extraction tests--Test:--```text-two-team matchup-one named competitor-no competitors-fight card-race event-race session-golf tournament-tennis matchup-generic sports programme-```--## 31.4 Deduplication tests--Must merge:--```text-Barcelona vs Real Madrid @ 21:00-FC Barcelona - Real Madrid CF @ 21:00-LaLiga: Barcelona v Real Madrid @ 20:55-```--Must not merge:--```text-live match vs replay-same teams in another competition-same teams much later-race vs qualifying-pre-game show vs match-men's vs women's team when distinguishable-```--## 31.5 Temporary-channel fallback tests--Given channels:--```text-EPL | 18 Oct | Arsenal vs Liverpool-EPL | 17 Oct | Arsenal vs Liverpool-Arsenal TV-Liverpool FC TV-Sky Sports Premier League-```--and event:--```text-Arsenal vs Liverpool-18 Oct-```--expect the dated event channel to rank first.--Do not auto-match:--```text-Arsenal TV-```--solely because one team name matches.--## 31.6 Fight fallback tests--Given:--```text-UFC 330 | Pereira vs Ankalaev-```--ensure both fighters are required for strong event-specific match.--## 31.7 Racing fallback tests--Given:--```text-F1 | Japanese Grand Prix | Qualifying-F1 | Japanese Grand Prix | Race-Sky Sports F1-```--ensure the session-specific channel outranks generic F1 for qualifying.--## 31.8 Manual-pick tests--Test:--```text-event pick precedence-expiry-team preference-series preference-forget action-preference does not bypass channel visibility-```--## 31.9 Fixture-driven XMLTV tests--Create:--```text-good_sports_epg.xml-minimal_sports_epg.xml-messy_sports_epg.xml-multichannel_same_match.xml-multilingual_same_match.xml-replays_and_highlights.xml-non_team_sports.xml-missing_categories.xml-generic_sports_shows.xml-same_teams_twice.xml-```--## 31.10 M3U + XMLTV integration fixtures--Test:--```text-exact tvg-id mapping-existing persisted mapping-missing tvg-id-duplicate channel variants-unresolved EPG channel-temporary event channel fallback-manual selection fallback-```--No internet access in tests.--Phase B covers the current resolved path with exact, missing, unresolved, and-duplicate-event fixtures; existing data-layer tests cover persisted mappings-and EPG manual overrides. Temporary event-channel fallback and Sports-specific-manual channel selection will be tested with Phases E/F.-------# 32. Real-device verification--Run after automated coverage is in place.--## Scenario A — normal resolved EPG--- [x] Load a real playlist + EPG on the isolated AVD.-- [x] Confirm current sports events appear.-- [x] Confirm the Golf event's mapped channel is available.-- [x] Play it; Golf playback remained progressing for roughly two minutes.-- [x] Return to Sports.--## Scenario B — duplicate broadcasts--- [x] One guide event appears with two mapped channel choices.-- [x] Confirm one canonical event card.-- [x] Confirm both mapped playback choices are accessible in the UI; stable playback has not been confirmed for every choice.--## Scenario C — combined profile--- [ ] Same event supplied by channels from multiple profile members.-- [ ] Confirm choices are correct.-- [ ] Switch source membership.-- [ ] Confirm Sports refreshes.--## Scenario D — temporary event channels--- [ ] Use a provider with event-named channels if available.-- [ ] Remove/disable the direct EPG channel mapping for the test.-- [ ] Confirm fallback finds the correct temporary channel.-- [ ] Confirm wrong-date temporary channel is not preferred.--## Scenario E — manual override--- [x] Select a different channel.-- [x] Save event preference.-- [x] Verify the saved channel is promoted and added to the event when absent from direct EPG choices.-- [x] Forget it.-- [x] Verify normal resolution resumes and the added channel is removed.--AVD check on `emulator-5590`: for Burnley vs Wolverhampton Wanderers, selected the-ranked temporary `BR| DISNEY+ 028` channel. The details view showed `SAVED` and-15 choices; forgetting the pick restored the original 14 choices with no saved-badge. No event preference remains. Selecting a manual result also opened the-existing live player as designed by the current UI callback.--## Scenario F — non-team sport--- [x] Golf and surfing examples from the real EPG.-- [x] Verify cards do not fabricate home/away teams.-- [x] Verify event/session titles are readable.--## Scenario G — visibility/security rules--- [x] Hide a channel.-- [x] Ensure it disappears from Sports; the visible-channel input fell from 28,398 to 28,397, then returned to 28,398 after the channel was unhidden.-- [x] Verify protected/adult channel rules remain intact through fallback-index and remembered-pick tests that exclude protected, adult, and unplayable channels.-------# 33. Performance validation--The classifier/assembler has already been CPU-profiled.--Now measure the full Android path.--Record:--```text-guide programme count-visible channel count-active source type-combined-profile member count-cold Today load-warm Today cache load-cold Upcoming load-fallback index construction time-fallback event search time-UI stall/frame issues-device/emulator model-```--## Targets--Do not impose arbitrary hard limits before measuring.--Goals:--- Sports opening should feel immediate after cached data exists.-- Filtering should not re-query EPG.-- Fallback matching should not scan tens of thousands of channels expensively per event.-- Compose recomposition must not trigger EPG reloads.-- On Now refresh should avoid rebuilding unrelated windows.--If fallback indexing adds measurable startup cost, build it lazily only when:--```text-direct mapping failed-or-user opens Find another channel-```--This is likely preferable because normal EPG-first users may never need it.-------# 34. Diagnostics expansion--Keep existing `SportsHub` DEBUG diagnostics.--Add fallback-matcher diagnostics when enabled:--```text-event id-event normalized title-competitor aliases considered-event/session phrases-candidate channel-normalized candidate name-date extracted from channel name-fallback score-match reason-accepted/rejected-remembered-pick source-```--Do not log:--```text-stream URLs-credentials-tokens-playlist URLs-sensitive provider details-```--Production logs should remain quiet by default.-------# 35. Privacy and data boundaries--Keep Sports local.--Do not send:--```text-EPG content-playlist data-channel names-viewing history-credentials-playlist URLs-Xtream credentials-```--to a third-party Sports service.--Manual preferences remain local/profile-scoped using the same storage model as other user preferences where appropriate.-------# 36. Explicitly rejected external-provider patterns--Do **not** implement these external-provider assumptions in this plan:--- ESPN scoreboard API.-- ESPN standings API.-- ESPN team schedule API.-- ESPN logos/CDN as a dependency.-- ESPN broadcaster data as a dependency.-- external fixture source as canonical event source.-- ESPN league slug catalogue.-- A hardcoded US/CA/UK region preference.-- API-first event discovery.--Reason:--StreamVault's core architecture is intentionally:--```text-EPG -> SportEvent-```--not:--```text-external sports API -> event -> search EPG-```-------# 37. Sports hub improvements adopted--The revised plan adopts these ideas:--- [x] event-named temporary IPTV channel fallback;-- [x] date-aware temporary-channel matching;-- [x] efficient channel indexing for fallback search;-- [x] manual channel correction;-- [x] event-scoped remembered channel choice;-- [ ] team/series preference where useful;-- [x] forget/reset mapping;-- [x] distinct handling for team sports, fights, racing, and field/tournament sports;-- [x] stable item identity for TV focus;-- [ ] optional event-specific zap list;-- [x] conservative matching rather than broad fuzzy broadcaster matching;-- [x] explainable candidate ranking;-- [ ] source/language/region preferences that respect the user rather than hardcoded geography.--The fallback is geography-neutral when no explicit language/region preference is-available. Passing explicit source/language/region preferences into ranking is-not implemented yet.-------# 38. Recommended implementation order from current state--This order assumes the existing branch described in the supplied implementation map.--## Phase A — Verify the current implementation before extending it--- [x] Run current branch with a real playlist and populated EPG on the isolated worktree AVD.-- [x] Verify On Now end-to-end, including stable playback on the Golf event. The separate WSL FHD choice stalled after its first frame.-- [x] Verify Today.-- [x] Verify Upcoming.-- [x] Verify sport/league filters.-- [x] Verify duplicate broadcast grouping and playable choices for the observed event.-- [x] Verify details.-- [x] Verify stable playback on a surfaced channel choice; see the WSL channel failure below.-- [x] Record current guide false positives and playback findings before extending heuristics.--**Do this first.**--Do not expand matching logic before observing actual EPG/provider behavior.-------## Phase B — Finish original automated test debt--- [x] Classification unit tests.-- [x] Normalization/alias tests.-- [x] Event extraction tests.-- [x] Fingerprint tests.-- [x] Dedup tests.-- [x] Status tests.-- [x] XMLTV fixtures for categorized/minimal guides, exclusions, non-team events, and duplicate broadcasts.-- [x] M3U/XMLTV fixtures for the current resolved path (exact, missing, unresolved, and duplicate-event cases; data-layer persistence/override tests pass). Future event-channel fallback tests belong to Phases E/F.-- [x] Run `LiveGraphBehaviorTest` on the isolated worktree AVD.--This creates a safety net before changing event identity and parsing.-------## Phase C — Finish event-model and parsing depth--- [x] Refine competitor representation.-- [x] Refine league representation: canonical league identity now drives alias-aware event merging, event IDs, UI grouping, and league filters while preserving the display label.-- [x] Add/complete `SportsEventType`.-- [x] Complete dedicated event extraction boundary.-- [x] Improve competitor extraction.-- [x] Improve non-team event/session extraction.-- [x] Broaden aliases from structured registries.-- [x] Improve non-team title cleanup.-------## Phase D — Strengthen deduplication--- [x] Confidence-aware merge logic.-- [x] Replay/highlight separation.-- [x] Same-teams-twice handling.-- [x] Multilingual match merging.-- [x] Non-team fingerprinting.-- [x] False-positive fixture coverage.-------## Phase E — Add fallback channel discovery--Only after the normal EPG mapping is proven.--- [x] Create a cached normalized channel index for the effective playable channel set; rebuild it when channel, profile, visibility, or guide revision inputs change.-- [x] Add conservative two-competitor channel-name matching with aliases.-- [x] Add fighter-pair matching using full names or distinctive surnames.-- [x] Add event-title and series phrases for non-team sports, with event-specific phrases scoring above generic series-only names.-- [x] Parse ISO, named-month, and unambiguous numeric dates; ignore ambiguous numeric dates and reject incompatible dates, with a two-hour local-midnight boundary allowance.-- [x] Return ranked candidates with score and match reasons.-- [x] Preserve direct EPG choices; only enrich an event when none has a playable stream URL. Phase F adds explicit manual search; runtime playback failure does not yet trigger an automatic search.-- [x] Add fixture-level tests for matching, date rules, quality variants, direct-mapping precedence, and protected/unplayable channels.-------## Phase F — Add manual correction and preferences--- [x] `Find another channel`.-- [x] Manual channel search over the current visible, playable channel index.-- [x] "Use for this event."-- [x] Event-pick expiry (seven days).-- [ ] Optional team preference.-- [ ] Optional series preference.-- [x] "Forget my choice."-- [x] Ensure preferences never bypass hidden/protected or unplayable channel rules.-- [x] Add tests for search ranking, preference policy, expiry, and persistence.--Team and series preferences remain optional and are deferred; event-scoped choices cover the v1 correction flow.-------## Phase G — Channel presentation refinement--- [x] Group quality variants through StreamVault's existing live-channel grouping preference; grouped channels retain their variant and quality-option data, while raw mode keeps each channel separately selectable.-- [x] Preserve all playable alternatives in event details and manual search.-- [x] Keep fallback ordering confidence-ranked and neutral by channel name when no explicit user/source language preference is available; do not favor a fixed region.-- [x] Review direct-OK behavior: selecting a channel choice enters the existing live player, while Program Details remains a separate action.-- [ ] Consider event zap-list if player integration is simple.--The event zap-list remains deferred: `LiveChannelPlaybackRequest` carries one-channel choice, so event-only CH+/CH− cycling would require a wider player-navigation contract rather than a small Sports integration.-------## Phase H — Real-device and large-guide validation--- [x] Android TV device/emulator run on the isolated AVD.-- [x] D-pad/focus review, including first-result focus, navigation back to search, and moving from search to the first result after keyboard dismissal.-- [x] Real EPG false-positive review for the guide-derived news/time-title case.-- [x] Real EPG false-negative review; repaired four configured-guide cases: `Fudbal - Španska liga: Deportivo - Levante`, `Fudbal - Francuska liga: Le Mans - Toulouse`, `Live Bundesliga: Eintracht Frankfurt-Koln Etapa 6`, and `ATP1000 '26: Shanghai Masters QF4`. A follow-up guide-backed check also corrected an EFL Championship entry whose description referenced Premier League.-- [ ] Real fallback-channel matching review.-- [x] End-to-end performance measurement on a configured guide, including cold and cache-hit Today/Upcoming selection with fresh screenshot confirmation.-- [ ] Tune confidence thresholds based on evidence.--The 2026-10-16 guide load logged the four repaired titles as competitive, with team pairs extracted for the football fixtures and `Quarterfinal 4` for ATP QF4. The focused classifier/XMLTV suites pass. The current guide produced zero automatic fallback matches because all assembled events had direct EPG mappings; the manual picker review surfaced the mapped options only. Fallback precision and threshold tuning therefore remain open until a real unresolved event is available.-------## Phase I — Architecture cleanup only if justified--After behavior is stable:--- [ ] Extract a Sports repository if it materially improves testability/ownership.-- [x] Keep current cache; configured-guide measurements recorded a 0 ms warm Today cache hit.-- [x] Do not add a durable Sports index without a changed-program feed; current derived snapshots remain in memory.-- [ ] Document any future EPG refresh API changes that would enable incremental event rebuilding.-------# 39. Acceptance criteria for revised v1--The revised v1 is complete when:--## Core EPG-first path--- [x] A user with a valid playlist and EPG can see current/upcoming sports.-- [x] Events are grouped instead of shown as duplicate channel programmes.-- [x] Direct EPG/channel mappings remain the primary playback path.-- [x] Multiple mapped channels remain accessible.-- [x] Playback uses the existing StreamVault player.--## Classification quality--- [x] Team sports work across common title variants.-- [x] Replays/highlights/previews are not treated as live matches.-- [x] Non-team sports have readable event/session cards.-- [x] Generic low-information EPG entries degrade gracefully.--## Channel-discovery resilience--- [x] If direct EPG mapping fails, temporary event-named channels can be found.-- [x] Wrong-date temporary channels are rejected/down-ranked.-- [x] The user can manually select a channel.-- [x] The user can remember and forget a useful mapping.-- [x] Fallback search remains fast on large channel lists.--## Testing--- [x] Classifier tests exist.-- [x] Dedup false-positive tests exist.-- [x] XMLTV fixtures exist.-- [x] M3U/XMLTV integration fixtures exist.-- [x] Fallback matcher tests exist.-- [x] Manual-pick tests exist.--## Runtime verification--- [x] Tested on a configured Android TV environment.-- [x] Cold/warm load measurements recorded.-- [x] No major D-pad/focus regressions.-- [x] No visibility/security bypass.-- [x] No external sports API required.-------# 40. Future work after revised v1--Not part of the immediate implementation:--```text-live scoring provider-standings provider-team metadata/artwork provider-My Teams based on canonical EPG teams-league preference manager-sports-specific notifications-event zap list if deferred-```--Each remote provider, if ever added, must be reviewed separately.--Do not weaken the EPG-first core to add any of these.-------# 41. Final architecture--```text- USER DATA- +---------------------+- | |- v v- XMLTV M3U/Xtream- | |- v v- existing resolved EPG playable channels- |- v- SportsEpgClassifier- |- v- SportsProgrammeParser- |- v- SportEvent- |- normalize- |- deduplicate- |- +--------+---------+- | |- v v- direct mapped channels no/weak mapping- | |- | v- | fallback channel matcher- | - event channel names- | - date-aware matching- | - team/event/series phrases- | |- | +-------+--------+- | | |- | v v- | auto candidate manual picker- | | |- | +-------+--------+- | |- | remembered preference- | |- +---------+--------+- |- v- BroadcastOption[]- |- +----------------------+- | |- v v- Sports UI Future optional- | LiveScoreProvider- v- Existing StreamVault Player-```--The central rules are:--> **EPG defines the Sports event and normal broadcast mapping.**--> **The user's playlist defines what StreamVault is allowed to play.**--> **Fallback matching exists only to recover from incomplete IPTV/EPG metadata.**--> **Manual correction is preferable to aggressive guessing.**--> **No external sports API is required for the Sports Hub.**--> **Future scoring enriches an EPG-derived event; it never becomes the source of truth for the Sports screen.**-------# 42. Immediate next action for the agent--**Status snapshot, 2026-10-16:** Phase E fallback, Phase F manual correction,-and core Phase G channel presentation are implemented; team/series preferences-and the event zap-list remain deferred. The real-guide false-negative review-found and fixed four classifier/parser misses, with 48 Sports unit tests-passing. Golf remains the stable playback pass. Both WSL choices were retested-for 61 screenshots at two-second intervals and still failed: FHD froze after-HLS first-frame success and decoder stalls; HD stayed buffering after a-network timeout. Provider/combined-profile switching and provider/external-EPG refresh remain unexercised on the configured AVD. Fallback precision-remains unmeasured because every event had direct EPG mappings. See-[Sports-IMPLEMENTATION.md](Sports-IMPLEMENTATION.md) for evidence.--**Progress, 2026-10-17:** Phase C league representation is complete. The-league registry now returns canonical IDs, normalized aliases, sport identity,-and display names. Classification carries this metadata into assembled events;-league aliases merge consistently and canonical IDs back event identity, filters,-and UI row grouping. The configured guide exposed a title/description conflict-on `Burnley vs Wolverhampton Wanderers - EFL - English Football League SkyBet --Championship 2026/2027`; title-first classification now identifies EFL-Championship despite generic Premier League text in the description, and-competitor parsing preserves Burnley and Wolverhampton Wanderers. The EFL-Championship label is localized through the owning module's resources in all-38 advertised locales. Bare `EFL` and `EFL Cup` no longer resolve to-Championship. Focused Sports coverage passes 50 tests across seven suites,-including alias lookup, cross-channel merging of `English Premier League` and-`EPL` entries, and this guide regression. The corrected featured fixture and-selected EFL Championship filter were verified on `emulator-5590`;-see [league-regression.png](../artifacts/sports-ui-review/league-regression.png).--**Progress, 2026-10-16:** Core Phase A guide and playback checks are complete on the isolated-`SportsHub_Worktree_20261016` AVD (`emulator-5590`). The configured guide was-loaded by the user. The installed debug APK was built from this worktree and-its local/device SHA-256 matched. The older AVDs were not used for this pass.--The guide-backed UI checks cover On Now, Today, Upcoming, Basketball and-LNB Pro A filtering, event details, and a mapped event with multiple playable-choices. Earlier cold-load observations were On Now 57 s / 334 available-channels, Today 93 s / 616, and Upcoming 93 s / 585. In the current confirmed-run, On Now loaded in about 50 s / 347 channels, Today in 95.1 s / 580, and-Upcoming in 100.4 s / 585. Remote selection and screenshots confirmed the-Today and Upcoming tabs and their event content. Revisit loads inside the-five-minute window took 6.6 s for Today and 5.5 s for Upcoming. Counts and-timings describe this configured guide and isolated AVD.--The subsequent instrumented build measured cold `window-cold` stages at 18.8 s-for On Now, 40.7 s for Today, and 53.5 s for Upcoming. Each window loaded from-28,398 visible channel rows. Resolved-program loading processed 6,497 rows-(6,497 keys) in 0.57 s for On Now, 198,808 rows (6,546 keys) in 4.5–9.8 s for-Today, and 102,256 rows (6,418 keys) in 1.02 s for Upcoming. Classification-took 2.9 s, 16.3 s, and 38.0 s respectively; assembly took 0.16 s, 0.40 s,-and 0.70 s. First fallback-index construction took 1.47 s; the later windows-reused it in 20–30 ms. A same-process Today revisit logged a 0 ms cache hit.-Channel-normalizer regex caching reduced visible-channel preparation from-about 40 s to about 14 s, and avoiding redundant sport-term checks reduced the-latest Today classification stage from 19.4 s to 16.3 s. Individual Room-statements and fallback-search time are still not isolated. Provider/combined-profile switching remains unmeasured. A visibility refresh check hid-`PT| SPORT TV 6 FHD`, observed 28,397 visible Sports input rows, then unhid it-and observed 28,398 after refresh. Provider data was preserved.--The real guide exposed a false matchup from a local news programme whose title-contained a schedule time. The classifier now rejects news/weather/traffic and-edition-style show titles, and excludes broadcast-time strings such as `5:00p`-from competitor extraction. Fixture coverage now verifies that case. A genuine-French basketball event (`Asvel vs Roanne`) also exposed missing `basket-ball`-and `LNB Pro A` recognition; both are covered by registry/fixture assertions.-Guide classification and assembly now run on `Dispatchers.Default` with-cancellation checks, keeping the large window scan off the UI thread.--Sports JVM coverage was 40 passing tests before Phase F. Focused Phase F tests-now pass for manual search, bounded result ordering, preference policy, expiry,-and event-pick persistence. Phase C/D adds typed canonical competitors, event-type and session parsing, retained raw programme references, and-confidence-aware compatibility grouping. Phase E adds a cached channel index,-conservative team/fight/event matching, date checks, ranked reason-bearing-candidates, and direct-mapping precedence. Phase F adds manual search,-event-scoped seven-day choices, forget behavior, and visible/playable-channel-validation. The Android TV AVD showed the first result focused on picker open,-search remained focused while typing, and the `ESPN` query returned configured-channels. After the keyboard was dismissed, D-pad Down moved focus to the first-result. After logcat was cleared before the query, no OOM, fatal exception, or-ANR appeared. Event choice and forget behavior remain covered by unit tests-rather than a device playback session. `LiveGraphBehaviorTest` also passed on the-isolated AVD.--Playback passed for the Golf event's mapped `EXYU| SPORT KLUB GOLF HD`-channel: 61 screenshots at roughly two-second intervals had 61 unique hashes-across about two minutes, the media session stayed `PLAYING` with `error=null`,-and HLS prepare/first-frame logs were present. Back returned to Sports.--In the earlier playback capture, `PT| SPORT TV 6 FHD` for the World Surf-League event produced an HLS first frame, then stopped progressing: 46-screenshots at two-second intervals had one unique image, the media session-ended in `NONE` with `error=null`, and logs showed no-candidate recovery with-TS fallback disabled. The second WSL choice, `PT| SPORT TV 6 HD`, stayed on-the buffering screen for 61 screenshots over roughly two minutes. Those-screenshots differed because the loading indicator animated; no video first-frame was logged. The media session remained `BUFFERING`, `error=null`, in the-final snapshot, and sanitized logs recorded a network source error followed by-`XTREAM_TS_FALLBACK` selection. `AR | BEIN-SPORTS ENGLISH 1 (Tod) [BK]`-reached `PLAYING` with `error=null` and produced an HLS first frame, but only a-short observation of a static event bumper was made. No stream URLs,-credentials, or provider identifiers are recorded here.--The WSL choices were retested on 2026-10-16 with paced captures. FHD had 61-screenshots at a 2.00-second average interval across 120 seconds, but only 2-unique hashes: a video frame appeared and then froze. The final media session-was `NONE`, `error=null`; sanitized logs showed HLS prepare/first-frame,-decoder stalls, and no-candidate recovery with TS fallback disabled. HD had 61-screenshots at a 2.00-second average interval across 120 seconds and 61 unique-hashes from the animated loading indicator, with no video frame. Its final-session was `BUFFERING`, `error=null`; sanitized logs showed a network timeout,-one retry, HLS prepare, and no first-frame success. No MPEG-TS fallback was-observed in either retest. This confirms the previously reported failures for-these two choices; it is not a general live-channel survey.--Remaining work: provider/combined-profile switching and provider/external EPG-refresh need an AVD with those sources configured; fallback precision needs a-real event without direct mappings; and the WSL failures need a stream/provider-diagnosis or code-level resolution. Visibility refresh is verified: hiding-`PT| SPORT TV 6 FHD` changed the visible Sports input from 28,398 to 28,397-rows, and unhiding it restored 28,398. Aggregate resolved-program timing is-measured, but individual Room statements and fallback-search time are not-isolated. Keep the fallback matcher behind the direct EPG path.diff --git a/docs/Sports-UI-REVIEW.md b/docs/Sports-UI-REVIEW.mddeleted file mode 100644index cd9e503e..00000000--- a/docs/Sports-UI-REVIEW.md+++ /dev/null@@ -1,37 +0,0 @@-# Sports UI refinement � 2026-10-17--Worktree: `D:/antigravity-scratch/iptv-player/.worktrees/sports-integration`-Branch: `codex/sports-integration`-Device: `emulator-5590`, configured guide retained.--## Scope--Presentation correction during Plan v2; no later Sports plan or remote sports-data provider was implemented. Existing navigation, EPG loading, classification, event grouping, channel preferences, manual search, and playback request contracts remain in place.--- Replaced the vertically scrolling eager column with a lazy list of league rows.-- Moved time-window controls alongside the title; reduced sport/league controls to 30 dp.-- Replaced the 270 dp minimum trophy hero with a 140 dp split fixture/broadcast panel.-- Ordered recognized league rows by event count, followed by generic guide categories. Featured a two-competitor fixture from the leading row when available.-- Added compact 244 x 140 dp event cards with competitor monograms, schedule, status and source-channel logo. Monograms are derived from guide names, not official team artwork.-- Made each event card one focus target that opens details. Direct playback remains available in the featured channel action; all broadcast choices and manual correction remain in details.-- Removed nested horizontal channel-button lists from event cards.-- Bounded the details dialog to 640 x 440 dp with fixed header/actions and an independently scrolling broadcast list.-- Added a localized EFL Championship label; no other UI copy changed.--## Validation--- `:app:assembleDebug`: passed; APK installed on emulator-5590.-- Sports JVM suite: 50 tests across seven suites, zero failures/errors.-- The configured EFL Championship filter selected Burnley vs Wolverhampton Wanderers correctly, even though the guide description referenced Premier League. Screenshot: [league-regression.png](../artifacts/sports-ui-review/league-regression.png).-- Resource audit: 29 referenced UI keys present and nonempty across all 38 advertised locales, including the EFL Championship label.-- Screenshot review caught and corrected a clipped first event row and details-header scrolling.-- Final overview screenshot confirms the entire 140 dp featured panel and first league row fit together at 1920 x 1080.-- D-pad Down entered league cards; horizontal movement scrolled the row while keeping the focused card visible. OK opened Liverpool vs Manchester City with both mapped channel choices.-- Opened Burnley details with 14 channel choices and moved seven choices down; the title, description, channel count and footer stayed fixed while only the channel list scrolled.-- No app fatal exception or ANR was found in the inspected recent logcat window.-- Device screenshots and remote-navigation evidence are under `artifacts/sports-ui-review/`.-- This is UI validation, not a new live-playback stability certification. Existing WSL playback failures in Sports-IMPLEMENTATION.md remain unresolved.--## Known data limitations--Scores, standings, official team artwork and video preview require separate planned work/data. The guide still surfaces weakly parsed entries such as `Upcoming vs MLB Network Strike Zone`; classifier changes were not included in this presentation pass.diff --git a/docs/StreamVault_Trakt_Integration_Plan.md b/docs/StreamVault_Trakt_Integration_Plan.mddeleted file mode 100644index 5c403cf8..00000000--- a/docs/StreamVault_Trakt_Integration_Plan.md+++ /dev/null@@ -1,1578 +0,0 @@-# StreamVault — Trakt Integration Plan--> **Status:** Implementation plan based on the current Trakt developer documentation as of **October 11, 2026**.-> **Target:** StreamVault Android / self-hosted open-source media player.-> **Primary use case:** Let users connect their own Trakt account, automatically track playback, and optionally synchronize Trakt data such as history and watchlists.--## Implementation progress — October 12, 2026--Phase 1 account code is implemented in the Trakt integration worktree: PKCE/state,-dedicated HTTPS callback activity, encrypted atomic persistence, serialized rotating-refresh tokens, profile/status, connect/cancel/disconnect, API headers, and rate-limit-cooldown. Build and deployment instructions are in [TRAKT_SETUP.md](TRAKT_SETUP.md).--The supplied public Client ID and HTTPS callback URL are configured locally. The-existing StreamVault Trakt registration now uses the exact callback below. The-callback site is deployed and Android verifies its domain for the installed debug-APK. Real browser sign-in and callback delivery are **validated**. Firefox-157.0.1 from Mozilla's official archive is installed on the Codex_Trakt Android 16-AVD. The user completed login/consent, and StreamVault displayed-Connected with the account username. Profile refresh completed without an error.-After force-stopping the app (PID 2256) and relaunching (PID 3115), Connected and the-same username returned. No tokens or authorization codes were collected in evidence.--Phase 2's domain identity foundation has started: `TraktMediaIdentity` and its-resolver accept attached positive movie/show TMDB IDs, with exact episode numbers-and matching local series/provider ownership. Missing IDs, unknown episode numbers,-and inconsistent ownership return no identity; no title guessing is performed.-Season-zero specials are supported. Six domain tests and the debug build passed;-output is in `build/trakt-identity-validation.log`.--Phase 2 now includes exact episode resolution (show TMDB lookup followed by season/-episode lookup), a bounded successful-ID cache, start/pause/stop payloads, serialized-authenticated requests, and player wiring. The player reports identified VOD only;-live TV, catch-up, recordings, trailers, and unknown external media are excluded.-Duplicate ticks and buffering produce no extra requests. Session switches preserve-the old item's last observed progress, and stale starts/pauses are suppressed. A-bounded transition queue avoids accumulating position ticks while network calls run.-Completion and cleanup submit a final stop; transient engine recovery preserves the-session. Tracking failures do not crash playback or trigger ambiguous write retries.-An explicit 401 can refresh once and retry; duplicate-stop 409 responses are terminal.-Opening playback loads the saved account without requiring a visit to Trakt settings.--Domain, transport/authentication, and player-coordinator tests cover these behaviors.-Build, playback boundary verification, and app/data lint passed against existing-baselines. Output is in `build/trakt-scrobble-final-validation.log`; the final-exception-isolation follow-up is in `build/trakt-scrobble-safety-validation.log`.-The earlier targeted suites contained 11 domain, 25 data, and 6 player tests, all passing.-Real-account episode start/pause reporting was exercised on the signed-in-Codex_Trakt emulator for the exact-matched S.W.A.T. Exiles S1E1. Trakt returned-successful HTTP responses for start and pause, and the player showed “Tracking with-Trakt” then “Trakt tracking paused”; playback reached a decoded first frame. The-test paused at about 2:11 of 44:35 (about 5%), so it did not test watched-history-completion. Trakt's scrobble API saves a pause as playback progress; a stop above-80% is needed to create a watched-history entry. StreamVault does not yet read the-saved `/sync/playback` item back, so its badge confirms request acceptance, not the-persisted server-side progress row. No watchlist, favorites, personal-list, or-history-add request was part of this test. A non-focusable player badge now fades-in for three seconds when tracking status changes and stays available while player-controls are open. It also explains when the account needs connecting, content-cannot be tracked, no exact Trakt match exists, or a request fails. The duration--late start case and status transitions have player unit coverage. Real movie-scrobbling, Cast/external-player tracking, and variant episode ownership mapping-remain unvalidated or unsupported.-Phase 3's read/match foundation is described below.-Phase 4 watchlist support is implemented; real-account UI acceptance remains open.-Phase 5 now includes movie/show Favorites write-through, movie/show user ratings,-personal custom-list management, and public discovery categories for trending-and popular movies/shows. Settings can independently hide each Movies/Series-Trending/Popular category. Settings also show the connected account's expanded text-profile and provide independent playback-scrobbling and history-sync controls.--Phase 5 custom lists (October 16): Settings loads the connected account's personal-lists and lets the user create private lists, inspect movie/show/season/episode-items, remove items, reorder entries, reorder lists, and delete a list after an-explicit confirmation. Movie, show, season, and episode detail actions can add or-remove the exact supported item in a selected list. The Trakt Lists dialog also-offers Create new list and creates a private list before returning to the picker.-List metadata and item pages use a five-minute account-scoped cache; item pages are-fetched only when a list is opened and are staged before replacing the cached list.-Incognito mode blocks reads and writes, account changes invalidate the operation,-explicit 401 responses refresh once, and uncertain list writes are not retried.-Episodes and seasons are matched through their parent show's TMDB identity and-resolved to exact Trakt IDs before writes. People entries and reordering remain-unsupported when Trakt does not return stable list-entry IDs. Focused catalog,-settings, and data unit tests pass; debug APK assembly and emulator UI acceptance-remain to be completed. Real-account list mutations remain unvalidated.--Phase 2 validation follow-up (October 12): the coordinator now sends pause/stop only-for an identity whose start succeeded. This prevents skipped intermediate sessions-or failed starts from creating watched history through a later high-progress stop.-A Robolectric integration test drives the production player coordinator, account-service, HTTP client, and encrypted disk store through movie start/pause/resume,-movie-to-episode switching, exact episode resolution, and completion. It uses a-synthetic account and MockWebServer, never real Trakt writes. It passed with the-debug build; output is in `build/trakt-playback-integration-validation.log`.-The failed/skipped-start regressions are covered by the player tests; follow-up-test/boundary/lint output is in `build/trakt-playback-regression-validation.log`.-At the time of this synthetic follow-up, the isolated emulator was closed and real-VOD scrobbling acceptance had not yet been run; the later signed-in episode check-is recorded above.--Phase 3 read/match foundation (October 12): `TraktHistorySource` fetches one-authenticated page of mixed movie/episode history at a time (100 records per-request), sharing the same token lock and rotating refresh handling as playback.-Pagination uses Trakt's response header, with raw row-count fallback. Invalid dates,-missing IDs, fractional identifiers, and unknown types are skipped with a count;-IDs retain 64-bit precision. `TraktHistoryIndex` deduplicates repeated history IDs-and refuses conflicting media identities. Its merge policy produces explicit import-candidates, preserving newer local rewatch progress, manual completion, and larger-local play counts. A completion import advances older progress to its known duration-so existing catalog queries reflect the watched state. Remote absence never removes-local history.--Phase 3 now has a manual Settings → Trakt → Sync Now action. It stages up to 50-pages before writing; a failed read or exceeded limit imports nothing. Cached movie/-series rows are matched in bounded TMDB batches, and episodes require exact numbers-and provider/series ownership. Import candidates are rechecked under the playback-repository lock and inside a Room transaction before history and catalog projections-are updated together. Repeated imports do not increment plays or rewrite the watch-time. Incognito mode prevents imports, and account changes abort the run. The UI-reports imported, uploaded, unchanged, unmatched, and skipped counts, or partial-counts after a failure. Sync Now also uploads up to 100 newest completed local events-per run, resolved only by exact TMDB and episode ownership. It compares all staged-history first, uses stable UTC minute timestamps, and stops on a failed write; the-next manual run reconciles again before posting. Incognito mode blocks both sync-directions. The local catalog stores each item's latest watch time, so earlier-rewatches cannot be reconstructed as separate events. There is no automatic polling.-Real-account sync/device UI acceptance remains open. Test/build/lint output is in-`build/trakt-history-import-final-validation.log`, including Room persistence and-unwatched-count checks.-See [TRAKT_HISTORY_SYNC.md](TRAKT_HISTORY_SYNC.md).--Outbound synchronization now has focused MockWebServer and service-level coverage-for request payloads, exact episode lookup, UTC minute timestamps, accepted and-unmatched response counts, same-minute reconciliation, account ownership, one-time-401 refresh, ambiguous-write retry suppression, incognito blocking, and the 100-event-per-run cap. The full Trakt domain and data test packages pass (18 domain and 52 data-tests); all use local mocks, with no real-account history writes. Real-account-Sync Now also completed on the isolated Codex_Trakt emulator using the saved connected-account. The UI reported 0 imported, 0 uploaded, 0 unchanged, 0 unmatched, and 0-skipped. That emulator has no provider/catalog, so this confirms the authenticated-empty-history read and result UI without changing Trakt history; item matching,-non-empty import, and outbound upload still need acceptance against a real library.-Trakt's current API-normalizes `watched_at` to the minute and its API team says equal item/timestamp pairs-deduplicate, although the current contract still contains an older warning. StreamVault-preflights the complete staged history and canonicalizes timestamps before uploads.--Phase 4 watchlist implementation (October 12): authenticated movie/show list reads-and explicit add/remove actions share the account service's rotating-token lock.-Movie and show detail pages show Trakt bookmark actions only for positive TMDB IDs;-titles are never used as a fallback. Reads are staged before the account-scoped-five-minute cache is replaced, with a 50-page (100 items per page) bound per media-type. Incomplete reads do not expose a partial list, and Incognito mode blocks reads-and writes. Explicit 401 responses refresh once; uncertain write failures are not-retried. The Trakt domain/data/catalog test suites pass (18/65/46 tests), and-`:app:assembleDebug` succeeds. No real-account watchlist item was changed. Display,-add/remove, failure feedback, and reconnect behavior still need device acceptance-with a configured movie/show catalog.-The five watchlist action/status strings are translated across the catalog's supported locales; :feature:catalog:lintDebug and :data:lintDebug pass (18 existing data lint baseline findings remain filtered).--Local validation passed: 16 Trakt tests, 17 related Settings tests, app Kotlin-compilation, settings dependency boundary verification, and app/data debug lint-against the existing baselines. The configured debug APK built and installed, and-`pm get-app-links` reports `davidona.github.io: verified`. At that checkpoint,-emulator OAuth login and session persistence passed; playback had not yet been tested.-Detailed local command output is in-`build/trakt-final-validation.log` and `build/trakt-configured-build.log`.--Phase 1 follow-up adds an actionable missing-browser message with pending-login-cancellation and retry, plus HTTP/encrypted-storage integration coverage for login-after recreation, saved profile/session, token rotation, disconnect, denial and late-callbacks. These local tests pass. Real login, callback, profile, and session-persistence also passed. The opt-in device test rotated a real token pair once,-verified encrypted persistence, and reloaded the same profile without another-refresh. Output is in `build/trakt-live-refresh-validation.log`. Disconnect showed-Disconnected on the real device. Real deny/cancel, process death during pending-login, and stale callbacks remain browser acceptance checks. An isolated Android-device test with production encrypted storage and synthetic OAuth responses passed-pending-login service/store recreation, denial, cancellation, disconnect, and late-callback rejection. It leaves the real account session untouched; this establishes-device storage/service behavior, not end-to-end browser consent. Output is in-`build/trakt-device-recovery-validation.log`.-Follow-up build/test/lint output is in `build/trakt-phase1-followup-validation.log`.--Device validation found and fixed unreadable status text and a search-result focus-target that prevented the Connect button from receiving focus. The corrected screen-is readable, opens with Connect focused, and launches Firefox. The updated APK build,-17 related Settings tests, and app lint passed; output is in-`build/trakt-device-ui-validation.log`.--The Trakt worktree now uses Room schema 81. Codex_Trakt was upgraded in place from-schema 78; its provider and catalog rows were preserved. The separate default-checkout has advanced to schema 82, so reconcile its newer database changes before-merging or release validation. Code remains uncommitted and unpushed in this-worktree; do not push until requested.--A GitHub Pages hosting package is saved in `docs/trakt-pages/` with release,-beta, and debug App Link associations. The release fingerprint was verified against-the existing signed release APK. The intended callback is-`https://davidona.github.io/oauth/trakt/callback/index.html`; both this page and the-domain-root verification JSON return HTTP 200 without redirects. The hosting site-was published before the user's instruction to keep further code local. Integration-code remains uncommitted and unpushed in this worktree; do not push until requested.-See [TRAKT_PAGES_DEPLOYMENT.md](TRAKT_PAGES_DEPLOYMENT.md).-------## 1. Executive decision--StreamVault should integrate Trakt as **one registered Trakt application** with a single StreamVault **Client ID**.--Users should **not** enter their Trakt username/password into StreamVault and should **not** create their own Trakt developer application.--For Android, StreamVault should use:--**OAuth 2.0 Authorization Code Flow + PKCE (`S256`) + HTTPS Verified App Link**--This is Trakt's current recommended authentication method for mobile apps.--### Architecture--```text- Trakt- │- StreamVault App- Client ID- │- ┌────────────────┼────────────────┐- │ │ │- User A User B User C- │ │ │- OAuth OAuth OAuth- │ │ │- Access/Refresh Access/Refresh Access/Refresh- tokens tokens tokens- │ │ │- Personal Trakt Personal Trakt Personal Trakt- account account account-```--The **Client ID identifies StreamVault**.--Each user's **OAuth access token identifies and authorizes that individual user**.-------# 2. Important 2026 Trakt changes--Trakt's authentication guidance has changed significantly.--## PKCE is now the recommended sign-in mechanism--Trakt explicitly recommends PKCE for the Authorization Code Flow.--A mobile application no longer needs to ship a Trakt `client_secret`.--Trakt states that the Client Secret is **deprecated for user sign-in** and should only be used in situations where it can remain on a trusted server.--For StreamVault:--```text-Use:-client_id-OAuth Authorization Code Flow-PKCE S256-HTTPS redirect URI-Android Verified App Link--Do NOT ship:-client_secret-```--This is especially suitable for StreamVault because the project is open source and distributed as an Android application.-------## Client ID is public--Trakt explicitly describes the `client_id` as public.--It appears in OAuth authorization requests and therefore cannot be treated as a secret.--It is fine to keep the Client ID in a GitHub Actions secret for repository/configuration hygiene, but this does **not** provide real secrecy.--For example:--```text-GitHub Actions Secret-TRAKT_CLIENT_ID=...-- ↓ build--BuildConfig.TRAKT_CLIENT_ID-- ↓--StreamVault APK-```--Anyone sufficiently motivated can obtain the Client ID from the application or OAuth traffic.--That is expected.--### Recommendation--Use a GitHub secret if convenient, but document internally that:--> `TRAKT_CLIENT_ID` is configuration, not a credential that must remain secret.--Never place a Trakt `client_secret` in the APK.-------# 3. Trakt application registration--Create **one Trakt API application for StreamVault**.--Current Trakt documentation says creating an application requires a **verified GitHub account** connected through the developer panel.--Developer applications are managed here:--https://developer.trakt.tv/apps--Suggested application identity:--```text-Name: StreamVault-Description: Open-source IPTV and media player with optional Trakt account integration.-```--Use StreamVault's real project/site information where Trakt requests it.--Trakt also requires developers to follow its branding requirements and developer announcements.-------# 4. Self-hosted / open-source status--Trakt's current API Use Policy explicitly lists these as permitted examples:--- media player integrations that scrobble playback into a connected user's account;-- personal tools;-- self-hosted tools that synchronize a user's own media activity;-- applications that manage a user's watch history, ratings, or lists.--The policy also states that an application's popularity, where it runs, or whether it has a backend does not by itself determine whether the integration is permitted.--This makes StreamVault's architecture a direct fit for Trakt's permitted use cases.--## Important restrictions--StreamVault must not:--- scrape the Trakt website;-- mirror or bulk-harvest Trakt's database;-- sell or redistribute Trakt API data as a dataset/feed;-- provide another service access through StreamVault's Trakt credentials;-- create replacement API apps to evade limits or restrictions;-- use Trakt data in an application that promotes copyright infringement or piracy.--StreamVault should continue to present itself as a **media/IPTV player for user-provided sources**, not as a provider of unauthorized media.-------# 5. User experience--The user-facing flow should be simple.--## Settings--```text-Settings-└── Trakt- └── Connect Trakt-```--When the user presses **Connect Trakt**:--```text-StreamVault- │- │ Generate PKCE verifier + challenge- ▼-Open Trakt authorization page in browser- │- ▼-User signs into Trakt- │- ▼-User approves StreamVault- │- ▼-Trakt redirects to StreamVault HTTPS callback- │- ▼-Android Verified App Link opens StreamVault- │- ▼-StreamVault exchanges authorization code + PKCE verifier- │- ▼-Access token + refresh token stored securely-```--After connection:--```text-Trakt--✓ Connected--Automatically track playback ON-Sync watch history ON-Sync watchlist ON--[ Sync Now ]-[ Disconnect ]-```--If desired, StreamVault can fetch the user's Trakt profile after authentication and display their username.-------# 6. OAuth protocol--## 6.1 Generate a PKCE verifier--For every sign-in attempt, generate a new random `code_verifier`.--Trakt currently specifies:--- length: **43–128 characters**-- allowed characters:- - `A-Z`- - `a-z`- - `0-9`- - `-._~`--The verifier exists only for the current authentication attempt.--Do not reuse it.-------## 6.2 Generate the PKCE challenge--Hash the verifier using SHA-256:--```text-SHA256(code_verifier)-```--Then Base64URL encode the result **without padding**.--```text-code_challenge = BASE64URL_NO_PADDING(SHA256(code_verifier))-```--Trakt currently supports:--```text-code_challenge_method=S256-```--Use `S256`.-------## 6.3 Open Trakt authorization--Open Trakt's authorization endpoint in the user's browser:--```text-https://auth.trakt.tv/oauth/authorize-```--Include the required OAuth parameters plus:--```text-client_id-redirect_uri-response_type=code-state-code_challenge-code_challenge_method=S256-```--`state` should be a cryptographically random value associated with the pending login attempt.--When the callback returns, StreamVault must verify that the returned `state` matches the original value.--If it does not match, abort the login.-------# 7. Android redirect handling--Trakt's current PKCE documentation specifically recommends **HTTPS redirect URIs**.--For Android, use a **Verified App Link**.--Example conceptual redirect:--```text-https://streamvault.example.com/oauth/trakt/callback-```--That HTTPS URL is registered with Trakt.--Android is configured so that the verified domain opens StreamVault for that callback.--Do **not** use:--```text-streamvault://callback-localhost-urn:ietf:wg:oauth:2.0:oob-```--Trakt now advises against custom schemes and localhost-style callbacks because another application may be able to claim/intercept them.--### Requirement--The `redirect_uri` is case-sensitive and must match exactly:--1. the URI registered in the Trakt developer application;-2. the URI sent in `/oauth/authorize`;-3. the URI sent during token exchange.-------# 8. Authorization code exchange--After authorization, Trakt redirects back with:--```text-?code=...-&state=...-```--Verify `state`.--Then exchange the temporary authorization code using:--```text-POST /oauth/token-```--Send the authorization code and the original `code_verifier`.--With PKCE:--```text-DO NOT send client_secret-```--The result includes an OAuth access token and refresh token.-------# 9. Token lifecycle--## Access token--Current Trakt documentation states that access tokens are valid for:--**7 days**--Store the access token securely on the device.--Use it for authenticated Trakt calls:--```http-Authorization: Bearer <access_token>-```-------## Refresh token--Use the refresh token to obtain a new access token without forcing the user to log in again.--Important 2026 behavior:--**Refresh tokens are single-use.**--Every successful refresh returns:--```text-new access_token-new refresh_token-```--The refresh token that was just used becomes invalid immediately.--Therefore token persistence must behave atomically:--```text-1. Send old refresh token-2. Receive new access token + new refresh token-3. Replace BOTH stored tokens-4. Never use the old refresh token again-```--### Avoid concurrent refreshes--Do not let several API requests independently refresh an expired token.--Use a synchronization mechanism such as a mutex/single-flight token refresh.--Otherwise:--```text-Request A uses refresh_token X → succeeds → X invalidated-Request B uses refresh_token X → fails-```-------## Legacy token migration--Trakt notes that refresh tokens issued before its recent authentication migration may no longer be exchangeable.--If token refresh returns something equivalent to:--```json-{- "error": "invalid_grant",- "error_description": "session not found"-}-```--StreamVault should:--1. clear the invalid local Trakt session;-2. show that Trakt needs to be reconnected;-3. let the user perform OAuth again.--This should be treated as a one-time migration/re-authentication case rather than endlessly retrying the same refresh token.-------# 10. API request authentication--Trakt says all applications should send the required Trakt API headers, including the app's API key / Client ID.--Authenticated calls additionally use the user's Bearer token.--Conceptually:--```http-trakt-api-key: <STREAMVAULT_CLIENT_ID>-Authorization: Bearer <USER_ACCESS_TOKEN>-```--Implement the remaining version/content headers according to the current endpoint documentation when building the HTTP client.--Centralize these headers in the Trakt API client rather than manually adding them in individual features.-------# 11. Public vs authenticated requests--Some Trakt endpoints are public and need only the StreamVault Client ID.--Other endpoints require an authenticated user's OAuth token.--Some public endpoints optionally accept OAuth and return personalized information.--Architecture:--```text-Public Trakt request- ↓-Client ID- ↓-Trakt---User-specific request- ↓-Client ID-+ Bearer access token- ↓-Trakt-```--If a signed-in user's token can validly be supplied to an endpoint, doing so also affects which rate-limit bucket is used.-------# 12. Current rate limits--As of the current Trakt documentation:--| Scope | Operations | Limit |-|---|---|---:|-| Authenticated user | GET | 500 requests / 5 minutes |-| Authenticated user | POST / PUT / DELETE | 1 request / second |-| Unauthenticated | GET | 500 requests / 5 minutes |--Unauthenticated GET requests are currently scoped by:--```text-Client ID + public IP-```--So devices behind the same public IP can share the unauthenticated allowance.--Authenticated GET requests use the individual user's authenticated bucket.-------## 429 handling--On:--```http-429 Too Many Requests-```--StreamVault should:--1. inspect `Retry-After`;-2. wait at least that duration when present;-3. otherwise use bounded exponential backoff with jitter;-4. avoid immediate retry loops;-5. cache and de-duplicate requests where appropriate.--Trakt may also return an `X-Ratelimit` header containing diagnostic information.--Log:--```text-HTTP status-endpoint-HTTP method-authenticated vs unauthenticated-Retry-After-X-Ratelimit-```--Do not log OAuth tokens.-------# 13. What "scrobbling" means--Trakt defines **scrobbling** as automatically tracking playback by reporting when a movie or episode:--```text-starts-pauses-stops-```--This is the correct Trakt feature for StreamVault's playback integration.--Conceptually:--```text-Player starts movie- ↓-Trakt scrobble: start--Player pauses- ↓-Trakt scrobble: pause--Player resumes- ↓-Trakt scrobble: start/resume as required by endpoint semantics--Player stops / completes- ↓-Trakt scrobble: stop-```--Implementation should follow the exact current scrobble endpoint payload requirements rather than inventing a custom watched-state protocol.-------# 14. Media identification--Scrobbling is only reliable when StreamVault knows exactly what title the user is playing.--Do not rely only on the filename/title string if stronger metadata exists.--Prefer IDs already attached to StreamVault content.--Useful identifiers in Trakt media objects include IDs such as:--```text-Trakt-TMDB-IMDB-TVDB (where applicable)-```--For a TV episode, the local media model should ideally identify:--```text-Show ID-Season-Episode-```--Example:--```text-StreamVault item-TMDB show ID: 1396-Season: 2-Episode: 3-- ↓--Resolve/match Trakt episode- ↓--Scrobble exact episode-```--If StreamVault cannot confidently identify the movie/episode, do not silently scrobble the wrong title.--A future fallback may allow the user to manually match an unidentified item.-------# 15. Recommended StreamVault Trakt features--## Phase 1 — Authentication foundation--Implement:--- Trakt Client ID configuration;-- OAuth Authorization Code Flow;-- PKCE S256;-- random OAuth `state`;-- HTTPS redirect;-- Android Verified App Link;-- access-token storage;-- refresh-token storage;-- single-use refresh rotation;-- disconnect/revoke-local-session behavior;-- user profile/status display.--Deliverable:--```text-Settings → Trakt → Connect-```--works reliably.-------## Phase 2 — Scrobbling--Implement playback tracking for:--- movie start;-- episode start;-- pause;-- resume;-- stop;-- completion.--Build scrobbling around the central media identity model, not directly around raw IPTV/file names.--Include protection against:--- duplicate start events;-- pause-event spam;-- retry loops;-- scrobbling the wrong episode;-- stale events after the player changes media.-------## Phase 3 — Watch history synchronization--Add:--- fetch user's Trakt history;-- mark local items as watched based on Trakt state;-- send explicitly watched local items to Trakt where appropriate;-- "Sync Now" action.--Define conflict behavior before implementing two-way sync.--Recommended principle:--```text-Do not erase either side automatically unless the user explicitly performs-an action whose meaning is unambiguous.-```-------## Phase 4 — Watchlist--**Implementation status:** code complete; real-account device acceptance remains open.--Add optional support for:--- reading the user's Trakt watchlist;-- showing whether a StreamVault movie/show is on the watchlist;-- add/remove watchlist actions.--The home dashboard also offers optional **Trakt Watchlist Movies** and **Trakt-Watchlist Series** shelves. They preserve Trakt's list order, resolve only against-the active provider by TMDB ID, and omit titles without a playable catalog match.-The shelves are separate from StreamVault's local Favorites. The Movies and-Series sections also expose a Trakt Watchlist action in shelf mode and a-watchlist category in the category picker; Classic mode shows it as another-clickable category. These views use targeted provider/TMDB lookups, preserve-Trakt order, and explain when no watchlisted titles match the current provider-or filters.--Keep this separate from playback history.-------## Phase 5 — Additional Trakt functionality--**Implementation status:** the first Phase 5 slice is implemented in code: the-existing movie/show heart continues to save to StreamVault Favorites and, when-Trakt is connected, adds or removes that TMDB-matched movie/show in Trakt-Favorites. A failed remote write leaves the local change intact and reports the-sync failure. This applies to detail, search, and saved-item heart actions;-group-only changes and live-channel favorites remain local. Items without a-TMDB ID remain local-only. Existing local favorites are not bulk-uploaded, and-an explicit provider-scoped import action adds existing Trakt Favorites when an-exact TMDB match is present in the active provider's catalog.--The ratings slice is also implemented. Movie and show detail pages read the-connected account's ratings from Trakt, stage each read before replacing its-account-scoped cache, and keep the cache for five minutes. Reads are bounded to-50 pages of 100 items per media type; missing or invalid TMDB IDs and malformed-ratings are skipped. The current Trakt rating appears in the rating dialog, where-the user can submit a value from 1 to 10, and on the detail page beside the title-metadata when a rating exists. Writes use the exact TMDB ID, share the-account service's serialized token refresh, retry once only after an explicit 401,-and are never retried after an ambiguous transport failure. Incognito mode blocks-rating reads and writes. Ratings do not replace provider ratings or external rating-metadata, and episodes are not included. Local unit/API tests cover read pagination,-staging, cache behavior, write payloads, account changes, incognito, and detail-page-identity mapping. Real-account rating UI acceptance remains open; no live rating was-submitted during implementation.--Discovery/trending (October 16): Movies and Series expose **Trending on Trakt** and-**Popular on Trakt** in modern shelf browsing and classic category browsing. These-public endpoints do not require a Trakt sign-in. StreamVault caches each first page-for 30 minutes, preserves Trakt order, and shows only exact TMDB matches from the-active provider, so discovery never imports a remote catalog into the app. Failed-refreshes retain the last good page and surface an error state. API parsing, cache,-and catalog-order projection have focused tests. On October 16, debug version-1.0.19 was installed on the Codex_Trakt Android 16 emulator; Trending on Trakt-and Popular on Trakt each loaded provider-matched results in both Movies and-Series. The Classic-mode category rail still needs device acceptance.--Discovery visibility settings (October 16): Settings → Movies & Series → Library-browsing now has four independent switches for Trending and Popular in Movies and-Series. All four default to visible and persist with the rest of user preferences.-Turning one off removes it from the modern browse actions, category picker, and-Classic category rail; if that category was selected, the view returns to the full-library. The preferences are included in portable backup classification. The-switches are visible on the Codex_Trakt emulator. Hiding and restoring Trending-movies was verified in modern browsing: the action disappears and returns while-Popular remains. Classic-mode rail acceptance remains open.--Emulator compatibility (October 16): The Trakt AVD's database was at schema 78,-with an older schema-80 layout also present on a second development AVD. A-data-preserving 80→81 repair migration aligns the episode index and Xtream-onboarding receipt columns. The historical Room migration suite passed on-Codex_Trakt, and the app opened after upgrade with the existing provider and catalog-rows preserved. No app data was cleared.--Phase 5 account controls and import (October 16): Settings exposes persistent-switches for playback scrobbling and manual history import/upload. Disabling-scrobbling pauses an already active Trakt playback session so it cannot create a-watched-history stop, hides the player tracking status, and suppresses queued new-starts. Disabling history sync prevents the manual sync action from running. An-explicit **Import Trakt favorites to this provider** action reads Trakt movie/show-favorites in bounded pages, stages the complete read before local writes, and adds-only exact TMDB matches from the active provider to StreamVault Favorites. The-result reports added, already present, unmatched, and skipped titles; it never-uploads existing local favorites. The profile now displays available name,-location, joined date, gender, age, VIP status, and about text, with a refresh-action. It does not hotlink Trakt-hosted avatars. Favorite import, settings,-profile parsing, and scrobbling preference behavior have focused unit coverage;-the debug APK assembles successfully. Version 1.0.19-debug was installed in place-and launched on the Codex_Trakt Android 16 emulator; provider, catalog, and account-data were retained. Real-account import and toggle acceptance remain open.--Still deferred or unvalidated:--- Cast/external-player playback scrobbling and manual matching for unknown media.-- Custom-list people items and real-account acceptance for deletion/reordering and- season/episode add/remove operations.-- Real-account acceptance for history sync, watchlist, Favorites import, ratings,- and custom-list operations.--Authentication, matching, scrobbling, history sync, watchlist, personal lists with-movie/show/season/episode support, list deletion and ordering, movie/show Favorites,-movie/show ratings, and public trending/popular-categories, Favorites import, and expanded text profile are implemented;-real-account acceptance remains open for the operations listed above.-------# 16. Suggested internal module design--```text-Trakt/-├── TraktApiClient-├── TraktAuthService-├── TraktTokenStore-├── TraktTokenRefreshCoordinator-├── TraktScrobbleService-├── TraktSyncService-├── TraktMediaMatcher-└── Models/-```--## TraktApiClient--Responsibilities:--- base URL;-- required headers;-- Client ID;-- Bearer token injection;-- JSON serialization;-- HTTP response handling;-- rate-limit metadata.--Do not place OAuth UI logic here.-------## TraktAuthService--Responsibilities:--- generate PKCE verifier/challenge;-- generate and validate `state`;-- construct authorization URL;-- process callback;-- exchange authorization code;-- refresh token;-- disconnect.-------## TraktTokenStore--Responsibilities:--- securely persist:- - access token;- - refresh token;- - token expiry information;-- atomically replace tokens after refresh;-- clear tokens on disconnect/re-authentication requirement.-------## TraktTokenRefreshCoordinator--Responsibilities:--- ensure only one token refresh occurs at a time;-- let waiting requests reuse the newly refreshed token;-- prevent reuse of an invalidated single-use refresh token.-------## TraktMediaMatcher--Responsibilities:--Resolve the currently playing StreamVault item to an exact Trakt movie/episode using authoritative media IDs whenever possible.--This module is deliberately independent from the player.-------## TraktScrobbleService--Responsibilities:--Translate player lifecycle events into Trakt scrobble requests.--It should not be responsible for identifying media.--Input should already be something like:--```text-ResolvedTraktMovie-or-ResolvedTraktEpisode-```-------# 17. GitHub / build configuration--Recommended:--```text-GitHub repository- │- ├── no Trakt client secret- │- └── workflow reads TRAKT_CLIENT_ID- │- ▼- Android build- │- ▼- BuildConfig.TRAKT_CLIENT_ID-```--Keeping the Client ID in GitHub Actions Secrets is acceptable for convenience.--However:--**Do not build security assumptions around hiding the Client ID.**--PKCE is what protects OAuth sign-in when the client itself cannot keep a secret.-------# 18. Local token security--The following are real user credentials and must be protected:--```text-access_token-refresh_token-```--Do not:--- commit them to Git;-- include them in crash reports;-- write them to normal application logs;-- put them into analytics payloads;-- expose them in UI/debug screens in release builds.--Use Android secure storage appropriate to StreamVault's architecture.--The Client ID does not require this secrecy.-------# 19. Trakt image handling--If StreamVault later uses images returned directly by Trakt:--Trakt currently requires applications to **cache the images** rather than hotlink them from Trakt's CDN.--Its current image guidance says image data can be included with:--```text-?extended=full-```--and images are returned in WebP form.--Do not add Trakt image support by simply pointing permanent UI image URLs at Trakt's CDN.--If StreamVault already uses TMDB or another media metadata provider for artwork, keeping artwork responsibility with that provider may be cleaner.-------# 20. Pagination and API efficiency--For paginated Trakt endpoints:--```text-?page=...-&limit=...-```--Trakt recommends explicitly sending pagination parameters when supported.--Do not assume a universal page size.--Use response headers such as:--```text-X-Pagination-Page-X-Pagination-Limit-X-Pagination-Page-Count-X-Pagination-Item-Count-```--Use these values instead of calculating page count from the requested limit.--Cache API data where appropriate and avoid repeatedly requesting data StreamVault already has.-------# 21. API application lifecycle--A noteworthy current policy:--Trakt says API application registrations may be automatically deleted after **30 consecutive days with no usage**.--Registrations used only for testing during their first 30 days may also be removed.--Therefore:--- create the real StreamVault integration when implementation work is active;-- keep developer account/contact information current;-- do not create unnecessary duplicate apps.-------# 22. Failure handling--StreamVault should explicitly handle:--## Authentication cancelled--User closes browser or denies access:--```text-Keep Trakt disconnected.-Do not show an application error.-```--## OAuth state mismatch--```text-Abort login immediately.-Discard pending PKCE transaction.-```--## Expired access token--```text-Refresh once through TraktTokenRefreshCoordinator.-Retry original operation after successful refresh.-```--## Refresh `invalid_grant`--Especially:--```text-session not found-```--Treat as requiring reconnection.--Do not repeatedly retry.--## 401 after refresh--Clear invalid session and request reconnection.--## 429--Respect `Retry-After`.--## Offline--Queue only operations where delayed execution has clear semantics.--Do not create an unbounded playback-event queue.--## Unknown media identity--Do not scrobble until a reliable match exists.-------# 23. Recommended implementation order--```text-1. Register StreamVault Trakt app- ↓-2. Configure Client ID- ↓-3. Configure HTTPS redirect + Android App Link- ↓-4. Implement PKCE + OAuth state- ↓-5. Implement callback + token exchange- ↓-6. Secure token persistence- ↓-7. Single-flight token refresh- ↓-8. Connected-account settings UI- ↓-9. Media ID matching- ↓-10. Playback scrobbling- ↓-11. History synchronization- ↓-12. Watchlist support- ↓-13. Optional ratings/lists/discovery-```--Do not start history/watchlist synchronization before authentication and media matching are reliable.-------# 24. Acceptance checklist--## Registration--- [ ] StreamVault Trakt developer application created.-- [ ] Developer GitHub account verified/connected if required by Trakt.-- [ ] Client ID configured.-- [ ] No Client Secret included in StreamVault.--## OAuth--- [ ] Authorization Code Flow implemented.-- [ ] PKCE verifier generated per login.-- [ ] PKCE uses SHA-256 / `S256`.-- [ ] OAuth `state` generated and validated.-- [ ] HTTPS callback registered.-- [ ] Android Verified App Link configured.-- [ ] Redirect URI matches exactly in all OAuth stages.-- [ ] Browser-based Trakt login works.--## Tokens--- [ ] Access token securely stored.-- [ ] Refresh token securely stored.-- [ ] 7-day access-token expiry handled.-- [ ] Refresh token rotation replaces both tokens.-- [ ] Concurrent refresh is prevented.-- [ ] `invalid_grant` migration case prompts reconnect.-- [ ] Tokens are never logged.--## API--- [ ] Client ID header centrally added.-- [ ] Bearer token centrally added for authenticated calls.-- [ ] 401 handling implemented.-- [ ] 429 handling respects `Retry-After`.-- [ ] Request caching/de-duplication implemented where useful.-- [ ] Pagination response headers handled correctly.--## Playback--- [ ] Movie matching works.-- [ ] Show/season/episode matching works.-- [ ] Start scrobble works.-- [ ] Pause scrobble works.-- [ ] Stop/completion scrobble works.-- [ ] Duplicate playback events suppressed.-- [ ] Unknown media does not get incorrectly scrobbled.--## User experience--- [ ] Connect Trakt button.-- [ ] Browser authentication.-- [ ] Return to StreamVault automatically.-- [ ] Connected state visible.-- [ ] Disconnect option.-- [ ] Scrobbling toggle.-- [ ] History-sync toggle.-- [ ] Watchlist-sync toggle if implemented.-- [x] Read and set Trakt movie/show ratings from detail pages.-------# 25. Things StreamVault should explicitly NOT do--```text-✗ Ask for the user's Trakt password-✗ Store a Trakt password-✗ Embed a client_secret in Android-✗ Require every StreamVault user to create a developer application-✗ Use replacement API keys to bypass restrictions-✗ Scrape trakt.tv-✗ Mirror the Trakt catalog-✗ Redistribute Trakt's dataset-✗ Hotlink Trakt-hosted artwork-✗ Treat the Client ID as a true secret-✗ Reuse old refresh tokens after a successful refresh-✗ Use custom-scheme OAuth callbacks when the recommended verified HTTPS App Link can be used-```-------# 26. Sources--All core decisions in this plan are based on Trakt's official developer documentation.--## Trakt API introduction--https://developer.trakt.tv/--Covers Trakt terminology including scrobble, history, watchlist, lists and favorites.-------## Authentication / OAuth--https://developer.trakt.tv/docs/authentication-oauth--Key findings:--- OAuth 2.0 is used for account authorization.-- Authorization Code Flow is intended for apps with browser/callback support.-- Device Code Flow is intended for TVs/media centers/limited-input devices.-- PKCE is recommended.-- Access tokens are currently valid for 7 days.-- Refresh tokens are single-use.-- Older refresh tokens affected by the authentication migration may require users to reconnect.-------## PKCE--https://developer.trakt.tv/docs/pkce--Key findings:--- PKCE is recommended for apps that sign users in.-- Trakt only supports `S256`.-- `client_id` is public.-- A `client_secret` is not required for PKCE login.-- Client Secret is deprecated for user sign-in.-- Android should use HTTPS Verified App Links.-- Custom schemes, localhost and out-of-band callbacks are discouraged.-------## Create a Trakt application--https://developer.trakt.tv/docs/create-an-app--Key findings:--- New apps use a Client ID.-- PKCE does not require a Client Secret.-- A verified GitHub account is currently required to create an API app.-- Developers must follow Trakt's API/branding rules.-- Trakt data must not be used in applications promoting copyright infringement or piracy.--App management:--https://developer.trakt.tv/apps-------## API use policy--https://developer.trakt.tv/docs/api-use-policy--Key findings:--- media-player scrobbling is explicitly permitted;-- personal/self-hosted tools are explicitly permitted;-- app popularity/location/backend does not itself decide permission;-- bulk harvesting, resale and dataset redistribution are prohibited;-- rate-limit circumvention is prohibited;-- API app registrations can be removed after 30 consecutive days without usage;-- applications should provide clear privacy information for their own handling of user data.--Policy page was updated by Trakt in September 2026.-------## Rate limits--https://developer.trakt.tv/docs/rate-limiting--Current documented limits:--```text-Authenticated GET:-500 / 5 minutes / user--Authenticated POST/PUT/DELETE:-1 / second / user--Unauthenticated GET:-500 / 5 minutes / Client ID + public IP-```--Also documents:--```text-429 Too Many Requests-Retry-After-X-Ratelimit-```-------## Pagination--https://developer.trakt.tv/docs/pagination--Documents:--```text-page-limit-X-Pagination-Page-X-Pagination-Limit-X-Pagination-Page-Count-X-Pagination-Item-Count-```--Page sizes vary by endpoint and should not be assumed globally.-------## Extended information--https://developer.trakt.tv/docs/extended-info--Trakt returns minimal media information by default and supports extended data where required.--Prefer requesting only the amount of data StreamVault actually needs.-------## Images--https://developer.trakt.tv/docs/images--Important:--- Trakt-hosted images must be cached;-- hotlinking is not allowed;-- `extended=full` is the current preferred way to request image information where supported;-- images are currently returned as WebP URLs.-------# 27. Final StreamVault decision--For StreamVault Android:--```text-ONE StreamVault Trakt application-ONE public Client ID-NO client secret in the app--OAuth 2.0 Authorization Code-+ PKCE S256-+ HTTPS callback-+ Android Verified App Link--Each user:- own access token- own rotating refresh token- own Trakt account- own authenticated rate-limit bucket--Playback:- resolve exact movie/episode- → scrobble start/pause/stop--Later:- history- watchlist- ratings/lists if useful-```--This should be treated as the baseline Trakt architecture unless Trakt changes its developer documentation again.diff --git a/docs/THIRD-PARTY-LICENSES.md b/docs/THIRD-PARTY-LICENSES.mdnew file mode 100644index 00000000..90019422--- /dev/null+++ b/docs/THIRD-PARTY-LICENSES.md@@ -0,0 +1,48 @@+# Third-party licenses and source++StreamVault includes third-party software. The licenses below apply to those components; they are separate from the StreamVault project license. The corresponding license texts are also packaged under `app/src/main/assets/licenses/`.++## Components++| Component | Version / source revision | License | Packaged notice |+| --- | --- | --- | --- |+| jcifs-ng (SMB recording) | 2.1.10 | GNU LGPL 2.1 or later | [`jcifs-ng-LGPL-2.1.txt`](../app/src/main/assets/licenses/jcifs-ng-LGPL-2.1.txt), [`GPL-2.0.txt`](../app/src/main/assets/licenses/GPL-2.0.txt) |+| Bouncy Castle Provider (`bcprov-jdk18on`, jcifs-ng dependency) | 1.76 | Bouncy Castle License | [`BouncyCastle-LICENSE.html`](../app/src/main/assets/licenses/BouncyCastle-LICENSE.html) |+| SLF4J API (jcifs-ng dependency) | 1.7.36 | MIT | [`SLF4J-MIT.txt`](../app/src/main/assets/licenses/SLF4J-MIT.txt) |+| AndroidX Media3 libraries, including the FFmpeg decoder wrapper | Media3 1.11.0; source commit `2bc207851df311340767e913931ca7b28cab1794`; Copyright (C) 2016 The Android Open Source Project | Apache License 2.0 | [`Apache-2.0.txt`](../app/src/main/assets/licenses/Apache-2.0.txt) |+| Other packaged app libraries (non-Media3 AndroidX, Kotlin/Kotlinx, Dagger/Hilt, OkHttp/Retrofit, Gson, Coil, ZXing and core-library desugaring) | Versions in the app's Gradle catalog/module declarations | Apache License 2.0 | [`Apache-2.0.txt`](../app/src/main/assets/licenses/Apache-2.0.txt) |+| FFmpeg decoder libraries in the Media3 AAR | FFmpeg source commit `ba69be84a1ceabfb39127831ad8da0fd7cb471f3` (release/6.0) | GNU LGPL 2.1 or later, subject to the enabled configuration | [`FFmpeg-LGPL-2.1.txt`](../app/src/main/assets/licenses/FFmpeg-LGPL-2.1.txt), [`GPL-2.0.txt`](../app/src/main/assets/licenses/GPL-2.0.txt) |+| libtorrent4j | 2.0.6-26 | MIT | [`libtorrent4j-MIT.txt`](../app/src/main/assets/licenses/libtorrent4j-MIT.txt) |+| libtorrent native library | Source commit `ed88357b4cdf7ae9d4b35aa77e654afbe2b7b11c` pinned by libtorrent4j 2.0.6-26 | BSD-3-Clause | [`libtorrent-BSD-3-Clause.txt`](../app/src/main/assets/licenses/libtorrent-BSD-3-Clause.txt) |+| Apple `route.h` notice included in the libtorrent notice bundle | Upstream libtorrent source notice | Apple Public Source License 2.0 | [`APSL-2.0.txt`](../app/src/main/assets/licenses/APSL-2.0.txt) |++The libtorrent notice file also preserves notices for its other bundled source components, including Boost-licensed and public-domain code.++## Google SDK developer terms++The app also declares Google Play services Auth and Cast SDKs. These are separate from the open-source licenses above. Google Sign-In/API use is subject to the [Google APIs Terms of Service](https://developers.google.com/terms/) and the [Google API Services User Data Policy](https://developers.google.com/terms/api-services-user-data-policy). Cast use is also subject to the [Google Cast SDK Additional Developer Terms of Service](https://developers.google.com/cast/docs/terms/).++## Corresponding source++The source for the application is published at [github.com/Davidona/StreamVault-IPTV](https://github.com/Davidona/StreamVault-IPTV). For a particular app release, use the matching source revision and the dependency revisions recorded in that release's `player/libs/media3-decoder-ffmpeg-1.11.0.properties` file.++* jcifs-ng 2.1.10 source: [tag `jcifs-ng-2.1.10`](https://github.com/AgNO3/jcifs-ng/tree/jcifs-ng-2.1.10).+* Bouncy Castle 1.76 source: [tag `r1rv76`](https://github.com/bcgit/bc-java/tree/r1rv76).+* SLF4J 1.7.36 source: [tag `v_1.7.36`](https://github.com/qos-ch/slf4j/tree/v_1.7.36).+* libtorrent4j 2.0.6-26 source: [tag `v2.0.6-26`](https://github.com/aldenml/libtorrent4j/tree/v2.0.6-26). That tag pins its native libtorrent source to commit [`ed88357b4cdf7ae9d4b35aa77e654afbe2b7b11c`](https://github.com/arvidn/libtorrent/tree/ed88357b4cdf7ae9d4b35aa77e654afbe2b7b11c).+* AndroidX Media3 decoder wrapper source: [pinned decoder module](https://github.com/androidx/media/tree/2bc207851df311340767e913931ca7b28cab1794/libraries/decoder_ffmpeg). Its [pinned README](https://github.com/androidx/media/blob/2bc207851df311340767e913931ca7b28cab1794/libraries/decoder_ffmpeg/README.md) documents the FFmpeg build and AAR assembly steps.+* FFmpeg source: [pinned FFmpeg revision](https://github.com/FFmpeg/FFmpeg/tree/ba69be84a1ceabfb39127831ad8da0fd7cb471f3).++For the bundled FFmpeg AAR, the project records the enabled decoders, supported ABIs, source commits, NDK versions and AAR hash in [`media3-decoder-ffmpeg-1.11.0.properties`](../player/libs/media3-decoder-ffmpeg-1.11.0.properties). The project-specific rebuild notes are in [`FFMPEG.md`](FFMPEG.md) and [`FFMPEG-LGPL-NOTICE.md`](FFMPEG-LGPL-NOTICE.md). If a release uses modified third-party source or different build options, publish the corresponding modified source and update those records for that release.++## License texts++* [Apache License 2.0](../app/src/main/assets/licenses/Apache-2.0.txt)+* [GNU LGPL 2.1 for jcifs-ng](../app/src/main/assets/licenses/jcifs-ng-LGPL-2.1.txt)+* [GNU LGPL 2.1 for FFmpeg](../app/src/main/assets/licenses/FFmpeg-LGPL-2.1.txt)+* [GNU GPL 2.0 text referenced by LGPL 2.1](../app/src/main/assets/licenses/GPL-2.0.txt)+* [Bouncy Castle License](../app/src/main/assets/licenses/BouncyCastle-LICENSE.html)+* [MIT License for SLF4J](../app/src/main/assets/licenses/SLF4J-MIT.txt)+* [MIT License for libtorrent4j](../app/src/main/assets/licenses/libtorrent4j-MIT.txt)+* [BSD-3-Clause and component notices for libtorrent](../app/src/main/assets/licenses/libtorrent-BSD-3-Clause.txt)+* [Apple Public Source License 2.0](../app/src/main/assets/licenses/APSL-2.0.txt)diff --git a/docs/TRAKT_HISTORY_SYNC.md b/docs/TRAKT_HISTORY_SYNC.mddeleted file mode 100644index 7c9b0324..00000000--- a/docs/TRAKT_HISTORY_SYNC.md+++ /dev/null@@ -1,86 +0,0 @@-# Trakt history synchronization--## Current implementation — October 12, 2026--The authenticated read API fetches one mixed history page at a time, with a limit of-100 rows. It shares the account mutex and single-use token rotation with playback-and profile requests. A 401 can trigger one refresh; a second 401 requires reconnect.-Rate-limited reads return a status without retrying. Missing pagination headers use-the raw row count, so skipped malformed rows do not prematurely end pagination.--Movie entries require a positive TMDB movie ID. Episode entries require a positive-parent-show TMDB ID and exact season/episode numbers. Unsupported or malformed rows-are counted and skipped. History IDs retain 64-bit integer precision. The endpoint-and response format were checked against the-[official Trakt sync contract](https://github.com/trakt/trakt-api/blob/master/projects/api/src/contracts/sync/index.ts).--The matching index deduplicates repeated history IDs across pages. Conflicting-identities for the same history ID match neither item. It reports the latest watch-and distinct play count for each exact media identity.--## Merge policy--- Import candidates must match a catalog-resolved media identity and content kind;- episodes must also match the local season and episode numbers.-- Newer local rewatch progress and explicit manual completion are preserved.-- Imported completion is automatic completion, with the newer watch timestamp and- the larger play count. Older progress advances to the known duration so existing- library queries reflect completion. Newer local rewatch progress, metadata, and- provider identity remain intact.-- Applying the same match twice produces no second candidate.-- An item absent from remote history produces no change. Nothing is deleted or- marked unwatched automatically.--The policy returns candidates. A dedicated repository operation rechecks current-persisted/pending history under its lock and in a Room transaction before applying-one candidate and updating catalog projections. It assigns automatic completion,-preserves the remote watch timestamp, and never increments the play count merely-because a sync was repeated. Current incognito preferences suppress writes.-Completed episodes are excluded from unwatched counts even with unknown duration.-No real account history was fetched or changed by automated validation.--## Manual Sync Now--Settings → Trakt → Sync Now stages the entire bounded remote read first (up to 50-pages / 5,000 records). A failed page or exceeded limit produces no writes. Movie/show-catalog lookup uses bounded TMDB batches; episode matching uses cached exact-provider/series ownership and season/episode numbers. It does not fetch provider-catalogs or guess titles.--Account changes stop the run. Local import failure may leave earlier successful-imports; the UI reports that count, and retrying is idempotent. The result includes-imported, uploaded, unchanged, unmatched, and skipped counts. Outbound sync uses the-newest completed local event per exact media identity, skips events already present-in Trakt, and sends batches of at most 100. Repeated Sync Now runs reconcile against-Trakt history before another POST; uploads are never automatic. Incognito mode blocks-the operation. Ambiguous write failures stop the run, and the next manual run reads-history before deciding what remains. There is no automatic polling or history-deletion. Local history stores only each item's latest watch time, so older local-rewatches cannot be reconstructed as separate dated events.--## Remaining work--The authenticated empty-history Sync Now path passed on the isolated Codex_Trakt-emulator. The connected account returned a successful result with zero imported,-uploaded, unchanged, unmatched, or skipped items. The emulator had no provider/catalog,-so this did not exercise media matching or outbound upload and changed no Trakt history.-Still verify a non-empty account and library, including rewatch/manual completion-conflicts, repeated sync, and interruption. Larger histories need a bounded-continuation design before expanding the current read limit.--Trakt now normalizes `watched_at` to minute precision and its API team says the same-item plus minute timestamp deduplicates naturally, though the current history contract-still has an older warning assigning duplicate prevention to clients. StreamVault-therefore canonicalizes uploads to UTC minute timestamps and preflights all staged-history before writing. A capped or failed read still blocks every upload.--Local test/build/lint output: `build/trakt-history-import-final-validation.log`. Tests cover-mixed pages, pagination, malformed rows, duplicate/conflicting IDs, merge conflicts,-401/rate-limit handling, history/playback sharing one token rotation, staged-read-failures/limits, account switches, incognito, idempotent transactional persistence,-catalog progress, episode counts, and the manual settings action. The outbound follow-up-adds MockWebServer payload/response tests and service coverage for exact movie/episode-resolution, minute-precision reconciliation, the 100-event cap, incognito and account-changes, refresh retry, and ambiguous failure handling. All 52 Trakt data tests and 18-Trakt domain tests pass locally; these tests do not write to a real Trakt account.-Real-account sync/device acceptance remains open.diff --git a/docs/TRAKT_PAGES_DEPLOYMENT.md b/docs/TRAKT_PAGES_DEPLOYMENT.mddeleted file mode 100644index f56ea90e..00000000--- a/docs/TRAKT_PAGES_DEPLOYMENT.md+++ /dev/null@@ -1,87 +0,0 @@-# Deploy the Trakt callback with GitHub Pages--The files in `docs/trakt-pages/` were published at the root of the GitHub user site-repository `Davidona/davidona.github.io` on October 11, 2026, before the user's-instruction to keep further code local. The integration worktree has not been-pushed. Do not publish further code until the user requests it.--Deployment commit: `17d72f1f9ece8b9b907ad299ed9da481dc6da50c`.-Both public URLs below returned HTTP 200 without redirects and with the expected-content types. Trakt's existing StreamVault app has the exact callback registered;-local debug configuration matches it. The configured APK built and installed, and-Android reports `davidona.github.io: verified` for `com.streamvault.app.debug`.-Real OAuth login/consent and callback delivery passed on the isolated Codex_Trakt-emulator (5558) using Firefox 157.0.1. Connected state and username survived an app-process restart. Remaining account acceptance cases are tracked in TRAKT_SETUP.md.-GitHub Actions callback-variable configuration and integration workflow-changes remain pending publication approval.--## Publish--1. Check whether `Davidona/davidona.github.io` already exists. If it does, preserve- its existing site and merge only the needed callback and verification files.-2. Otherwise, create a public repository named `davidona.github.io` under Davidona.-3. Copy the **contents** of `docs/trakt-pages/` into the repository root, including- `.nojekyll` and `.well-known/assetlinks.json`. Commit them on `main`.-4. In repository Settings → Pages, select Deploy from a branch, `main`, and `/ (root)`.-5. Wait for deployment and verify these two addresses return HTTP 200 directly,- without a redirect:- - `https://davidona.github.io/.well-known/assetlinks.json` (application/json)- - `https://davidona.github.io/oauth/trakt/callback/index.html` (text/html)--Use the explicit `index.html` callback URL because directory paths on static hosts-may redirect to add a trailing slash. Register the exact explicit URL everywhere.--## Configure Trakt and builds after deployment--Keep `https://github.com/Davidona/StreamVault-IPTV` in Trakt's **Website** field.-Set Trakt's **Redirect URI** to:--```text-https://davidona.github.io/oauth/trakt/callback/index.html-```--Set the same value in local.properties as `trakt.redirect.uri`, and in GitHub-repository variable `TRAKT_REDIRECT_URI` for the StreamVault build workflows.-Set repository secret `TRAKT_CLIENT_ID` to the supplied public app ID. No client-secret is needed. Local callback configuration is complete. The public Client ID-was also saved as an Actions secret before publication was paused; no client secret-was configured. Add the callback variable when preparing CI for publication.--## Certificates included--The verification file authorizes only these application/certificate combinations:--| Package | Certificate |-| --- | --- |-| `com.streamvault.app` | Existing release APK signing certificate |-| `com.streamvault.app.beta` | Same official certificate used by the beta build configuration |-| `com.streamvault.app.debug` | This machine's debug signing certificate |--The release certificate was confirmed using Android apksigner against the existing-release APK on October 11, 2026. The debug certificate was confirmed with this-worktree's Gradle signingReport. Certificates are public; no keystore/private key,-password, OAuth code, or user token is included. New signing keys require updating-this file. A debug build from another machine may use a different certificate.--## Validate--Install the new debug APK with the configured callback. On Android 12+:--```text-adb shell pm verify-app-links --re-verify com.streamvault.app.debug-adb shell pm get-app-links com.streamvault.app.debug-```--Confirm `davidona.github.io` is verified. A 200 response alone does not prove-Android verification. Complete browser consent from Settings → Trakt and confirm-the app returns with the connected username. Keep one matching StreamVault build-installed during routing tests. Then validate restart, cancellation, disconnect,-and refresh behavior from `TRAKT_SETUP.md`.--The fallback page removes the OAuth query from browser history and neither reads-nor exchanges OAuth codes. Domain verification causes Android to route the link-to the app before the page is loaded. GitHub still receives a normal web request-if the browser loads the fallback page; this static page cannot control hosting-provider logs.diff --git a/docs/TRAKT_SETUP.md b/docs/TRAKT_SETUP.mddeleted file mode 100644index b291990f..00000000--- a/docs/TRAKT_SETUP.md+++ /dev/null@@ -1,193 +0,0 @@-# Trakt setup and validation--Settings → Trakt supports browser sign-in, profile refresh, disconnect, VOD-scrobbling, and manual two-way history sync. Movie/show detail pages support Trakt-watchlist actions and 1–10 user ratings.-The client ID and HTTPS callback configuration below apply to all variants.--## Build configuration--Register one StreamVault application at https://developer.trakt.tv/apps. Set the-public Client ID and an HTTPS callback URI owned by the project using either:--```properties-# local.properties (gitignored)-trakt.client.id=YOUR_PUBLIC_CLIENT_ID-trakt.redirect.uri=https://YOUR_DOMAIN/oauth/trakt/callback-```--Or environment variables `TRAKT_CLIENT_ID` and `TRAKT_REDIRECT_URI`, which take-precedence. These apply to all variants. CI beta/release workflows read repository-secret `TRAKT_CLIENT_ID` and repository variable `TRAKT_REDIRECT_URI`. The Client ID-is public configuration. Do not configure a client secret.--Unconfigured builds show a disabled Connect button. No production domain or Client-ID is invented. The callback must match the registered URI exactly. The manifest-host and path are generated from the same build value as the OAuth requests.-Use a normal HTTPS URI without a port, query, fragment, or embedded user info.--## Verified App Link deployment--Host `https://YOUR_DOMAIN/.well-known/assetlinks.json` over HTTPS, without redirects:--```json-[- {- "relation": ["delegate_permission/common.handle_all_urls"],- "target": {- "namespace": "android_app",- "package_name": "com.streamvault.app",- "sha256_cert_fingerprints": ["YOUR_RELEASE_SIGNING_CERTIFICATE_SHA256"]- }- }-]-```--For development/beta testing, add separate entries for `com.streamvault.app.debug`-and `com.streamvault.app.beta` with the corresponding signing certificates. Publish-only variants/certificates you control. Keep only the intended app variant installed-while checking callback routing. Obtain fingerprints with Gradle `:app:signingReport`.--On Android 12+ use `adb shell pm verify-app-links --re-verify PACKAGE`, then-`adb shell pm get-app-links PACKAGE` to confirm the domain is verified. On older-Android versions, inspect domain verification with `adb shell dumpsys package PACKAGE`.-The manifest alone does not establish domain ownership; deployment is required.--### GitHub Website field versus callback--`https://github.com/Davidona/StreamVault-IPTV` is a suitable project Website value-in the Trakt registration form. It is not an Android OAuth callback: StreamVault-cannot publish domain verification files on `github.com`.--A GitHub Pages user site is deployed from the repository `davidona.github.io`. It-serves `https://davidona.github.io/oauth/trakt/callback/index.html`, with verification-at `https://davidona.github.io/.well-known/assetlinks.json`. Both addresses returned-HTTP 200 without redirects on October 11, 2026. A project Pages site under `/StreamVault-IPTV/` does-not provide control of the domain-root `/.well-known/` path required by Android.-Include `.nojekyll` when serving the static verification directory from a branch.--The complete static hosting package is prepared in `docs/trakt-pages/`, including-the verified release signing certificate and this machine's debug certificate.-See [TRAKT_PAGES_DEPLOYMENT.md](TRAKT_PAGES_DEPLOYMENT.md) for deployment status.-The explicit `index.html` callback avoids a directory-slash redirect on static hosts.--References: [GitHub Pages setup](https://docs.github.com/en/pages/getting-started-with-github-pages/creating-a-github-pages-site)-and [Android website associations](https://developer.android.com/training/app-links/configure-assetlinks).--## Token and failure behavior--Access/refresh tokens and pending PKCE state are encrypted with the existing-CredentialCrypto implementation and saved as one AtomicFile record in no-backup-storage. Neither tokens nor callback URLs are logged. The existing crypto layer-uses Android Keystore and has an app-private software fallback on broken TV devices.--Login transactions expire after ten minutes and are consumed once, including state-mismatch, duplicate query parameters, denial, or a bad callback path. Valid pending-transactions survive process death while the browser is open.--A mutex serializes account operations and refreshes. Both tokens are replaced-together. Before a refresh, the old session is cleared durably so a crash, network-timeout, or persistence failure cannot reuse a possibly consumed single-use token.-Such failures require reconnecting. This deliberately favors credential safety over-silently retrying an ambiguous refresh. Disconnect clears local tokens and pending-sign-in; it does not revoke the application grant on Trakt's website.-An explicit 429 rejection preserves the old session for retry after cooldown because-the server issued no replacement tokens.--The dedicated HTTP client has no body logger/cache, redirects, or transport retries.-Writes are spaced at least one second apart. A 429 establishes a cooldown from-Retry-After (seconds or HTTP date), or exponential backoff with jitter. Further-requests fail locally during that cooldown; the client does not loop or queue events.--## End-to-end acceptance still required--### Playback tracking implementation (October 12, 2026)--Identified movies and episodes are wired to start, pause/resume, completion, content-switch, and cleanup reporting. Episodes resolve a show TMDB ID and exact numbers to-a Trakt episode ID before posting. Live TV, catch-up, recordings, trailers, unknown-external URLs, cast, and external-player tracking are excluded. Mismatched local-episode ownership is skipped rather than guessed. Tracking sends only for a connected-account, shares token rotation with profile requests, and never retries ambiguous-writes. No real watched-history writes were performed during automated validation.--The current Trakt contract was checked against its official source:-- [Scrobble endpoints](https://github.com/trakt/trakt-api/blob/master/projects/api/src/contracts/scrobble/index.ts)-- [Episode scrobble IDs](https://github.com/trakt/trakt-api/blob/master/projects/api/src/contracts/scrobble/schema/request/episodeScrobbleRequestSchema.ts)-- [External ID lookup](https://github.com/trakt/trakt-api/blob/master/projects/api/src/contracts/search/index.ts)--Real acceptance still needs an identified movie and episode: verify start on Trakt,-pause/resume, completion, switching titles, and disconnect during playback. This is-separate from the successful real account sign-in and token-rotation checks below.--`TraktPlaybackIntegrationTest` covers the production coordinator → account → HTTP-client → encrypted-store path with a synthetic account and local MockWebServer.-It verifies authenticated movie and resolved-episode requests through pause/resume,-switching, and completion. It passed alongside the debug build. Failed/skipped starts-also cannot submit a later stop and accidentally create watched history. These local-checks do not establish real-device VOD playback or backend history acceptance.--The existing StreamVault app registration and local configuration now match the-deployed callback. Android verifies the domain for the installed debug APK. Real-login and consent completed in Firefox 157.0.1 on the isolated Codex_Trakt AVD-(emulator-5558). The callback returned to StreamVault, which displayed Connected-and the account username. Profile refresh completed without an error. Force-stop-and relaunch restored Connected and the same username (old PID 2256, new PID 3115).-No tokens or authorization codes were collected in the validation evidence.--Firefox's login page is difficult to navigate with a TV D-pad. Codex_Trakt uses-`hw.screen=multi-touch` so the host mouse can provide touch input for browser login.-This is an emulator configuration change, not a change to StreamVault's TV input.--The original Television_4K_2 device has database version 81; this worktree uses 78.-Its newer original-checkout APK was restored without clearing data. Use Codex_Trakt-for these checks and reconcile the newer app/database changes before release.-On a device with a real browser:--1. **Passed:** Connect from Settings → Trakt and confirm browser consent returns to StreamVault.-2. **Passed:** Confirm username and connected state, including after app process restart.-3. Deny/cancel consent and confirm the account stays disconnected without an error.-4. Restart the app process while the browser is open and complete the same login.-5. Disconnect and confirm a stale callback cannot reconnect the account.-6. **Passed:** Rotate a real token pair, persist it encrypted, and reload the same- profile without another refresh. The opt-in device test passed on Codex_Trakt;- output is in `build/trakt-live-refresh-validation.log`.--The real-device Disconnect action also displayed Disconnected. A new login was-started and the app process stopped while Firefox was open; completing that login-is pending. Browser denial/cancel and stale-callback end-to-end checks remain pending.--`TraktAccountRecoveryInstrumentationTest` passed on Codex_Trakt with production-Android encrypted storage in a separate test directory and synthetic OAuth API-responses. It verifies pending-login recreation, denial, cancellation, disconnect,-and late callback rejection without changing the real account. Output is in-`build/trakt-device-recovery-validation.log`. This does not replace browser handoff-acceptance. The app and Android test APK both built successfully.--`TraktLiveAccountInstrumentationTest` is skipped unless `live_trakt=true` is-explicitly supplied. It uses the isolated device's existing signed-in session and-rotates its real tokens; run it only with the app stopped. A test clock expires the-old pair in memory, and the production service performs the refresh and persistence.-It does not log or export token values. Run the specific test with:--```powershell-adb -s emulator-5558 shell am instrument -w -e class com.streamvault.app.trakt.TraktLiveAccountInstrumentationTest -e live_trakt true com.streamvault.app.debug.test/androidx.test.runner.AndroidJUnitRunner-```--Use the installed Firefox browser on Codex_Trakt for these checks. A-package that only resolves web intents to Android's framework browser stub cannot-complete consent. If there is no handler at all, Settings shows an install-browser-message and clears the pending login so Connect can be tried again.--Unit tests cover PKCE, callback rejection, single-use refresh concurrency/failure,-request headers/payloads, rate-limit cooldown, and encrypted atomic persistence.-Local integration tests also combine the production HTTP client, CredentialCrypto,-and disk store against MockWebServer: complete login after service/store recreation,-reload the username, rotate and persist the token pair, disconnect, and reject late-callbacks after cancellation. Robolectric uses the crypto layer's software fallback;-this does not verify a device's hardware Keystore or browser/App Link handoff.-They do not establish real Trakt sign-in. Domain verification was checked separately-with Android's package manager.--Official protocol references: https://developer.trakt.tv/docs/pkce and-https://developer.trakt.tv/docs/authentication-oauth.diff --git a/docs/XTREAM_LIVE_IMPORT_COMPARISON.md b/docs/XTREAM_LIVE_IMPORT_COMPARISON.mddeleted file mode 100644index e50662e8..00000000--- a/docs/XTREAM_LIVE_IMPORT_COMPARISON.md+++ /dev/null@@ -1,132 +0,0 @@-# Initial Xtream Live TV import comparison--Inspected 2026-10-09. StreamVault source: `540ec30c`. Reference implementation-revision: `b5271300b74eb6706293ceb8f3e70b62589e03ad`, inspected in a separate checkout.-No application code was changed and no runtime speed comparison was performed.--The user's priority is the initial live import on Add Provider. Work queued-afterward, including EPG and movie/series indexing, is outside that slow phase.-The earlier broad review remains useful for later work, but scheduling EPG-after indexing cannot fix the time spent importing live channels first.--## What the reference implementation actually does--- `MainActivity.fetchXtreamChannels` authenticates, then launches live category- and full live stream requests concurrently. It calls getLiveStreams without- a category ID. When movies/series are enabled, their bulk lists and category- requests launch alongside these too.-- XtreamClient.streamBulkArray uses Android JsonReader on the response stream.- It reads scalar fields into a small per-row map and immediately builds a- Channel. It does not turn every row into JSON text and decode that text again.-- The reader accepts a root array and selected object-wrapped arrays. It maps- IDs represented as numbers or strings, handles category_ids fallback and- catch-up flags, and skips nested structures it does not consume.-- Parsed Channels accumulate in an ArrayList proportional to catalog size.- Input JSON is streamed, but the entire output catalog is retained in memory.- Its OOM handling explicitly acknowledges that this list can still be too large.-- The Xtream fetch returns the full enabled live/movie/series result. It does- not deliver a capped live preview or incremental live row callbacks to the UI.- The separate early live callback in this file belongs to Stalker.-- On a successful provider fetch, loadAllConfiguredProviders merges the result- and calls renderLivePartial. That starts the live derivation/render path before- the final persistCatalog call. The catalog cache is a delimited text file,- written with a temporary file followed by rename; channel rows are not being- staged and indexed in Room during the download.-- It still performs live filtering and grouping in deriveLiveHalf and caches- derived results. The absence of import-time Room writes does not mean it- performs no classification or caching work at all.--Reference implementation inspected at the revision above; relevant components are the Xtream request orchestrator, direct streaming parser, catalog cache, and live rendering path.--## Where StreamVault spends extra initial-live work--| Stage | Reference implementation | StreamVault |-| --- | --- | --- |-| Live requests | One full stream-list request, categories overlap | AUTO chooses category requests on LOW and MID onboarding; categories precede stream loading |-| Category path | Normal loader uses full list | Globally spaced request starts, 250 ms on healthy server; limited window concurrency |-| Parsing | JsonReader fields → Channel | Gson tree → JSON text → kotlinx DTO → Channel |-| Download/write overlap | Builds an in-memory output list | Mapping/staging callbacks suspend further reading |-| Persistence before availability | Starts live rendering before final flat-file persistence | Stages the lineup and commits Room catalog plus FTS before provider setup finishes |-| Import-time CPU | Basic row mapping; grouping performed in live derivation | Field cleanup, internal URL creation, full grouping classification, stage fingerprints |--The largest structural distinction is the request topology. For 200 categories,-our 250 ms request-start spacing alone implies about 49.75 seconds before the-last request starts, even with a fast provider. LOW devices run one category-request at a time; MID devices permit at most two. Grouped awaitAll windows-prevent free slots from picking up more work while a slow request finishes.-These are policy-derived costs, not an observed timing for the user's account.--Our existing STREAM_ALL route already uses a thin live DTO and bounded staging.-It is the foundation to improve; a new live sync engine from scratch is not-required to adopt the useful ideas in the reference implementation.--Our per-row getLogicalGroupId calls ChannelNormalizer.classify, calculating-language, resolution, codec, transport, source tags and variant attributes in-addition to the canonical group key. The import only retains the group ID.-Consider a canonical/group-key-only method after checking equivalence with the-existing classifier. Measure its CPU cost before deciding its priority.--Staging batches are 100/300/500 by device tier. Each batch runs a transaction,-checks workflow ownership, counts staged rows, deduplicates/fingerprints and-writes them. Full live promotion rebuilds global channels_fts inside its-transaction, although generated Room code has maintenance triggers. Avoiding-the rebuild needs search-correctness validation; it is not safe to delete this-call merely because it looks redundant.--## Revised implementation proposal, live first--1. Establish a live-only baseline: authentication → live categories → first- stream headers/row → completed transfer/staging → commit → live screen- ready. Compare AUTO and explicit STREAM_ALL on the same full channel lineup.- This separates request topology from parsing, mapping and persistence.-2. Implement direct streaming field decoding into thin live rows. Preserve- StreamVault's current field semantics, lenient IDs/flags, provider headers,- category_ids, EPG IDs, channel numbers, catch-up and playback URL behavior.- Consume supported response shapes explicitly; report truncated/malformed- responses so they cannot be mistaken for complete deletion snapshots.-3. Use a small bounded batch queue between the reader and a single DB writer.- Keep row/admission budgets and commit ownership. Tune batch sizes by measured- transaction duration and memory headroom; reduce growing COUNT queries with- safe incremental accounting and reconciliation on resume.-4. Validate bulk ingestion under constrained heaps, then make AUTO prefer the- proven bulk path for healthy providers on LOW/MID too. Actual pressure and- observed bulk failures still trigger fallback. Keep explicit user modes.- Hidden categories can be filtered during bulk mapping, but that trades- network bytes against request count and must preserve required hidden rows.-5. Reduce commit cost, including proving whether FTS trigger maintenance makes- the global rebuild unnecessary. Retain atomic promotion, stable local IDs,- favorites/protection and partial-import preservation.-6. Improve category fallback with continuously filled slots and pacing driven- by server stress rather than a universal delay. Compare a new-provider fast- path and changed-row refresh path separately; neither should discard the- workflow/generation guarantees.--Keep the initial live catalog persistent and queryable through existing Room-interfaces. Adopting the reference implementation's all-in-memory catalog and file storage would change-too many browse/search/state contracts and increase peak memory. Borrow its-bulk request and single-parse approach while keeping bounded ingestion.--A full-catalog-ready milestone should remain distinct from any future small-preview milestone. Improving real complete-live throughput is the requested-goal; changing the completion label is insufficient.--## Evidence needed before calling a fix faster--Use identical provider data, device, network and channel coverage. Record-request count/bytes, end-to-end ingest, parse/map CPU, writer wait, stage totals,-commit/FTS time, first live-screen readiness and peak heap/GC. Current full-path-logs already report total ingest, mapping and staging time; commit logs report-category staging/commit, channel apply and FTS rebuild. Add missing parser,-request/header and readiness measurements. Current ingest elapsed includes-callback DB work, so it is not pure network time.--Test small/large lineups, many tiny categories, slow/throttled/bulk-rejecting-providers, malformed rows, process-death/cancellation, and hidden categories.-Verify complete channel counts, EPG IDs/numbers/catch-up flags, search,-stable favorites/protection and playback URLs. No speed ratio is established-by this source comparison. Playback bug validation, if a change affects it,-must follow the repository's sustained screenshot/log instructions.--The the reference implementation checkout was reviewed as a reference. No source was copied into-StreamVault; the proposed changes are implementation ideas for our existing-pipeline.diff --git a/docs/XTREAM_SYNC_BENCHMARK.md b/docs/XTREAM_SYNC_BENCHMARK.mddeleted file mode 100644index d75fbdb0..00000000--- a/docs/XTREAM_SYNC_BENCHMARK.md+++ /dev/null@@ -1,199 +0,0 @@-# Xtream sync benchmark--This guide documents the benchmark harness for the-[Xtream sync improvement plan](XTREAM_SYNC_IMPROVEMENT_PLAN.md). Initial runs-captured the pre-change engine; the current branch's ordinary app now uses-bulk-first AUTO, while the isolated benchmark build keeps a policy override for-repeatable comparisons.--## Run on the connected emulator--From the repository root in PowerShell:--```powershell-.\gradlew.bat :app:assembleDebug :app:assembleDebugAndroidTest -PxtreamSyncBenchmark=true -PcompatAbi=x86_64 --console=plain-adb -s emulator-5554 install -r app/build/outputs/apk/debug/app-debug.apk-adb -s emulator-5554 install -r app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk-python tools/xtream_sync_benchmark.py --channels 10000 --categories 100 --iterations 5 --warmups 1 --refresh-```--The build property creates `com.streamvault.app.syncbenchmark` with its own-storage and disables developer account seeding. Ordinary debug builds keep-their usual application ID and seeds. The instrumentation refuses to run-against another application ID or a benchmark database containing providers.-It creates synthetic accounts and removes only the exact account from each run.-It never clears app data or removes the existing debug app. For an interrupted-run, use `--cleanup-run <exact run token from report.json>`. The instrumentation-checks that token, normalized benchmark name and local endpoint before removing-that one provider; otherwise resolve it in the benchmark app before rerunning.--On this branch, ordinary `com.streamvault.app.debug` builds use bulk-first-`AUTO` by default; the isolated benchmark package retains its explicit policy-override for comparisons. To build the ordinary x86_64-compatible APK for-manual provider testing, use `:app:assembleDebug -PcompatAbi=x86_64` and install-it without clearing data. The exact saved APK, package verification, and-emulator install/launch record are in the-[P6 tuning report](XTREAM_SYNC_P6_TUNING_REPORT.md).--The Python runner starts a fixture bound to loopback, temporarily reverses its-port through adb, and removes that mapping when done. It refuses to reuse an-existing reverse mapping; choose another `--port` if necessary. APK installation-is explicit; the runner does not install, uninstall, or wipe an app.--Results go to an ignored, unique `build/xtream-sync-performance/<timestamp>/`-directory: `report.json`, structured `benchmark-log.txt`, and `requests.jsonl`.-The report requires both successful instrumentation and a completion marker.-An incomplete or failed run does not become a successful timing result.--## What is measured--The instrumentation invokes `ValidateAndAddProvider.loginXtream` using the-production dependency graph. Optional `--refresh` invokes `retrySection(LIVE)`,-the Settings live repair entry point. Runs cover AUTO, STREAM_ALL and-CATEGORY_BY_CATEGORY unless `--modes` limits the selection. The stored choice-is recorded alongside observed bulk/category request counts: STREAM_ALL can-still be overridden by existing safety policy, and AUTO may behave differently-for initial setup versus refresh.--Optional `--first-browsable-screen` launches the isolated app on the empty-Welcome screen, routes its startup landing destination to Live TV, and times-from the production setup use case starting until the first synthetic channel-row is accessible in the real Live screen. For a deterministic real-row target,-it temporarily hides the empty virtual Favorites and Recent categories, then-restores those preferences and the prior landing destination. The report-includes median and max for measured samples. It covers app navigation and row-readiness, but drives the production use case directly instead of interacting-with the provider form; it is emulator evidence, not a release-device-comparison. The option still deletes only its synthetic provider.--Optional `--verify-channel-fields` pages through the persisted live rows after-each setup and, with `--refresh`, after each Settings-style Live refresh. It-checks every row against the deterministic fixture: source order,-stream identity, name, category ID, the row's expected fallback category name,-EPG ID, archive fields, adult/protection state, logical group ID, fingerprint-presence, and the internal live URL token. Because fixture live rows omit-`category_name`, it separately checks the persisted category table against the-category-list names. The check uses 1,024-row pages and skips fixture rows-intentionally marked malformed. It runs after the relevant sync timer stops, so-its elapsed time is reported separately and is not included in import or-refresh latency.--Optional `--background-worker` marks the synthetic provider's last successful-Live timestamp stale, then queues a one-time no-ID `ProviderSyncWorker` through-WorkManager. It waits for terminal state and verifies the worker succeeded,-updated live-success metadata, and retained the exact channel count. This runs-the same provider-enumeration stale-refresh branch used by periodic and-launch-stale work; it does not wait for the periodic interval or validate its-network/battery scheduling constraints.--Each sample verifies the expected channel count after commit. Setup milestones-record live download start, save start, and the transition to movie category-shells after live commit. When synthetic movie/series summaries are configured,-the harness also waits for both durable index jobs to finish and checks Room-summary and active-index counts. The total setup time includes authentication,-initial workflow work, live import and existing category-shell completion;-summary indexing is reported separately. Refresh time ends when the existing-live repair command returns. Warmups are excluded from medians and maxima.-Request counts belong to the synthetic account's full lifecycle and include-both phases when refresh is enabled.--Optional `--repeat-vod-refresh` invokes the existing forced summary-index command-once for movies and then once for series after the initial jobs succeed. The-fixture and local rows are unchanged. It records per-section and combined-sequential elapsed time plus Java heap/ART GC samples for those direct refresh-calls, then verifies both Room and active-index counts again. This isolates an-unchanged summary refresh from setup and live import. It does not measure UI-readiness, playback, native RSS, or release-device performance. The P7 report-uses this option for its pre/post comparison.--When both movie and series fixtures are non-empty and at least one warmup is-configured, the first warmup seeds hydrated details, movie watch history,-protection flags and local playback metadata, then forces summary reindexing.-It checks that remote titles refresh while local IDs, hydrated fields, watch-state, protection, playback metadata and hydrated index timestamps survive.-The check is reported as `room_preservation_verified` and stays outside measured-samples when the configured warmup count is nonzero.--`XtreamSyncTiming` reports each streamed live response's wall duration, callback-duration, emitted row count and normal completion. Callback duration includes-downstream mapping and staging; remaining wall time includes network waits,-decode and request overhead. It is not parser CPU. Existing catalog timing-records capture stage batches, category commit, channel promotion and FTS-rebuild, now using a monotonic clock. The runner retains only structured-benchmark data and explicitly recognized numeric timing lines. It never-exports general provider logs, request URLs, response previews or passwords.--The P3 bulk pipeline adds numeric `live-pipeline` records for batch counts,-reader duration, final writer drain, send/backpressure time and estimated-outstanding raw batch bytes. See the-[pipeline report](XTREAM_SYNC_PIPELINE_IMPLEMENTATION.md) for resource accounting-and overlap semantics. These durations overlap and are not CPU measurements.--Java heap is sampled every 50 ms, with ART GC count deltas where available.-These are debug-emulator measurements, not release-device performance, native-RSS or an allocation profile. A short heap peak may fall between samples.-Production background jobs remain enabled and can contend with later samples.-Record environment, payload checksum and scenario with every comparison.--## Fixture scenarios--The fixture generates deterministic live, movie and series rows. Live JSON is-streamed without retaining the live list, and each catalog type can be-partitioned across categories. Metadata records seed, payload checksums, byte-sizes and expected counts. `--bulk-vod-status` and `--bulk-series-status` can-reject full responses while category requests succeed, exercising summary-fallback. EPG remains outside the benchmark. The fixture supplies no playable-media.--Examples (add normal iteration/mode options as needed):--```powershell-python tools/xtream_sync_benchmark.py --channels 50000 --categories 200 --header-delay-ms 100-python tools/xtream_sync_benchmark.py --channels 10000 --categories 100 --category-delay-ms 1500-python tools/xtream_sync_benchmark.py --channels 10000 --categories 100 --bytes-per-second 2000000-python tools/xtream_sync_benchmark.py --bulk-status 503 --modes STREAM_ALL-python tools/xtream_sync_benchmark.py --disconnect-after-rows 500 --modes STREAM_ALL-python tools/xtream_sync_benchmark.py --channels 1000 --categories 20 --disconnect-after-rows 500 --modes AUTO --experimental-auto-bulk --iterations 1 --warmups 0 --verify-channel-fields --settle-seconds 30-python tools/xtream_sync_benchmark.py --channels 1000 --categories 10 --movies 2000 --movie-categories 20 --series-items 1000 --series-categories 10 --bulk-vod-status 503 --bulk-series-status 503 --runtime-tier LOW --stage-batch-size 256 --modes STREAM_ALL --iterations 5 --warmups 1-python tools/xtream_sync_benchmark.py --channels 1000 --categories 10 --movies 2000 --movie-categories 20 --series-items 1000 --series-categories 10 --runtime-tier LOW --modes STREAM_ALL --iterations 5 --warmups 1 --repeat-vod-refresh-python tools/xtream_sync_benchmark.py --channels 1000 --categories 10 --movies 2000 --movie-categories 20 --series-items 1000 --series-categories 10 --bulk-vod-status 503 --bulk-series-status 503 --runtime-tier LOW --modes STREAM_ALL --iterations 5 --warmups 1 --repeat-vod-refresh-python tools/xtream_sync_benchmark.py --channels 1000 --categories 10 --movies 8000 --movie-categories 80 --series-items 4000 --series-categories 40 --runtime-tier DEVICE --stage-batch-size 256 --modes STREAM_ALL --iterations 3 --warmups 1-python tools/xtream_sync_benchmark.py --channels 1000 --categories 10 --movies 8000 --movie-categories 80 --series-items 4000 --series-categories 40 --bulk-vod-status 503 --bulk-series-status 503 --runtime-tier LOW --stage-batch-size 256 --modes STREAM_ALL --iterations 2 --warmups 1-python tools/xtream_sync_benchmark.py --channels 1000 --categories 10 --modes STREAM_ALL --iterations 1 --warmups 0 --first-browsable-screen-python tools/xtream_sync_benchmark.py --channels 10000 --categories 100 --modes STREAM_ALL --iterations 1 --warmups 1 --background-worker-```--These examples exercise synthetic category fallback and larger catalog sizes.-They are emulator evidence only; they do not measure playback, native RSS,-real-provider behavior, or physical-device performance. The P7 report records-the completed tier and route comparison matrix plus the unchanged VOD-pre-change comparison. That route-specific emulator comparison does not replace-the P0 release-device baseline or physical-device acceptance gate.--Also available: `--malformed-every`, `--throttle-every`, and `--seed`. Fault-scenarios are diagnostic checks: current retry/fallback behavior may prevent-completion, in which case the runner intentionally fails. A completed server-response alone never proves a complete client catalog.--Fixture/report tests:--```powershell-python -m unittest tools.tests.test_xtream_sync_perf_fixture tools.tests.test_xtream_sync_benchmark tools.tests.test_catalog_xtream_fixture-```--## Remaining measurement work--This package is an initial backend baseline, not the full P0 gate. Follow-up-work still needs precise headers/first-row and workflow-wait timings, attempt-and generation identifiers, row identity/field equivalence beyond counts,-skipped/duplicate/hidden coverage, parser CPU/allocation profiling, auxiliary-index readiness, release-build/device first-screen comparison, and full-WorkManager scheduling-constraint validation. Synthetic first-browsable and-no-ID background-worker measurements are available now. Pipeline byte high-water-and writer-drain timings now exist; actual heap/allocation attribution and queue-occupancy over time remain open. Run the full-five-sample scenario matrix and representative release-device measurements-before freezing production live-sync tuning. The P7 unchanged-summary result is-route-specific and stays separate from the release-device gate. Playback-validation is separate and follows AGENTS.md's sustained capture/log-requirements.diff --git a/docs/XTREAM_SYNC_CATEGORY_IMPLEMENTATION.md b/docs/XTREAM_SYNC_CATEGORY_IMPLEMENTATION.mddeleted file mode 100644index 1e36e65e..00000000--- a/docs/XTREAM_SYNC_CATEGORY_IMPLEMENTATION.md+++ /dev/null@@ -1,88 +0,0 @@-# Xtream live category scheduling--P5 on `codex/xtream-live-sync-performance`.--Live category requests use a bounded refilled coordinator: completion frees a-slot immediately instead of waiting for the slowest category in a fixed window.-Outcomes retain provider category order, while progress reports completion order.-Runtime profile caps and the remembered sequential preference remain. Completed-attempts merge under the P1 fence; failed or cancelled attempts are discarded.--Stress downgrade stops refilling until already running attempts drain, then-admits one at a time. Repeated sequential stress stops further admissions.-Authentication failures stop admissions and block provider continuation, including-when authentication fails during a sequential continuation request. The coordinator-returns a structured authentication/stress stop reason so continuation cannot undo-a terminal stop. Completed outcomes remain available for partial promotion.--Local staging and attempt-reset exceptions bypass transport retries and provider-health accounting, then escape the fetcher with their original failure type and-message. This also applies to legacy decoder fallback. Unexpected worker failure-cancels siblings; worker-CancellationException explicitly cancels the coordinator too, including workflow-supersession. Scope exit joins workers before staging cleanup.--Regression tests use the real HTTP fetcher, mapper, staging writer, coordinator-and Room store to verify local-failure propagation, sibling cancellation,-discarded staging and preservation of the active catalog. Strategy tests also-verify that stress/authentication stops suppress continuation, and continuation-tests preserve completed and unattempted outcomes when a later request loses-authentication.--Healthy live-category requests no longer have the mandatory 250 ms start gap.-Remembered stress retains pacing and backoff. Movie/series category requests-retain their existing pacing and fixed-window behavior.--HTTP 429 and server failures retain their status and Retry-After in the existing-network exception type. Both regular and streamed responses preserve these-fields instead of wrapping the exception again. Retry-After accepts seconds or-an HTTP date. Provider-wide Retry-After deadlines survive successful concurrent-requests and stress recovery; the next request waits for the later of that-deadline and adaptive backoff. Authentication is not classified as throttling.-Waiting requests recheck the deadline after waking, including when another-response extends Retry-After while they are asleep; a deterministic test covers-that extension.--## Evidence--After the failure-handling review fixes, 314 sync/HTTP Kotlin unit tests passed-with zero failures or errors. Nine new regression tests cover local writer and-attempt-reset failures, real-fetcher sibling cancellation and staging cleanup,-legacy fallback, authentication before/during continuation, and terminal stress-on both an intermediate and the final category. Existing shared-helper and-other-protocol sync tests remain in that passing set.--42 focused Kotlin tests passed, including refilled slots with a slow category,-bounded concurrency, stable result order, stress downgrade/abort, authentication,-sibling cancellation, real attempt supersession, failed-scope isolation, HTTP-status/header propagation and deterministic Retry-After waiting.--The isolated API 36 emulator retained all expected channels and passed cleanup:--| Fixture | Measured pairs | Add Provider median | Live refresh median |-| --- | ---: | ---: | ---: |-| 2,000 rows / 10 categories | 5 plus 1 warmup | 1,277 ms | 1,199 ms |-| 10,000 rows / 100 categories | 2 plus 1 warmup | 8,059 ms | 7,766 ms |--Reports:-- `build/xtream-sync-performance/20261010T080155937054Z/report.json`-- `build/xtream-sync-performance/20261010T080311051489Z/report.json`--Earlier 2,000-row category checks took roughly 2.5–2.8 seconds. Their sample-counts and device states differ, so this comparison establishes removal of the-observed pacing cost rather than a controlled release-device speedup ratio.-This emulator uses LOW profile category concurrency one: parallel refill itself-is verified by deterministic tests, not a device concurrency measurement.--At the time of this P5 report, production AUTO selection was unchanged. P6 later-enabled bulk-first AUTO in normal app profiles on this branch for direct testing.-The release gate remains open because tier overrides ran on one emulator and did-not measure physical devices or first-screen readiness. See the-[P6 tuning report](XTREAM_SYNC_P6_TUNING_REPORT.md).-The synthetic fixtures contain no playable media and do not validate playback.--The bulk-HTTP-503 fallback fixture also passed both operations at 2,000 rows:-`build/xtream-sync-performance/20261010T080443490570Z/report.json`.-Initial completion took 10,102 ms and refresh 7,587 ms. Existing bulk retries-and stressed-provider backoff remain costly; faster healthy category pacing-does not bypass those failure safeguards.diff --git a/docs/XTREAM_SYNC_DATABASE_IMPLEMENTATION.md b/docs/XTREAM_SYNC_DATABASE_IMPLEMENTATION.mddeleted file mode 100644index ba1b5d3f..00000000--- a/docs/XTREAM_SYNC_DATABASE_IMPLEMENTATION.md+++ /dev/null@@ -1,98 +0,0 @@-# Xtream live database write improvements--P4 on `codex/xtream-live-sync-performance`, following the-[improvement plan](XTREAM_SYNC_IMPROVEMENT_PLAN.md).--## Changes and invariants--The isolated Xtream live writer uses its unique-ID admission count for the-per-provider staging limit. The first batch checks that its private session is-empty. Later batches avoid a growing-table COUNT query. The writer advances its-successful accepted count only after insertion returns; a failed write ends and-discards the attempt under P1 rules. Completed-category merges, completion seals-and recovery still reconcile actual database counts. General M3U/Stalker writers-keep database accounting. The optimized entry point must not be used to append-to a recovered session or with a duplicate/nonexclusive admission set.--Stage entities and fingerprints are prepared before entering the fenced write-transaction. SHA-256 inputs, delimiters and lowercase hexadecimal output remain-compatible with existing persisted fingerprints. Hex encoding uses a lookup-table, and text normalization reuses its whitespace expression. Unchanged-row-promotion continues to compare fingerprints and preserves local channel IDs.--Fallback categories classify repeated names once and still allow later adult-flags or alternate adult names to strengthen classification. Only placeholders-can be renamed. The live writer materializes the category snapshot at completion-instead of copying the accumulated category list after every batch.--Live index backfill uses a provider-scoped transactional DELETE plus INSERT-SELECT from channels, under the workflow commit fence. It preserves the previous-field mapping and defaults without allocating two full Kotlin lineup lists.-An empty lineup clears obsolete live index rows; other providers and content-types are untouched.--Full and partial staged live promotion rely on Room's FTS content-sync triggers-instead of rebuilding the global channel search index. Explicit rebuild paths-and other content-type rebuilds remain. No schema migration is required.--## Validation--- 151 focused Kotlin unit tests passed, including attempt retry isolation,- supersession/recovery, fresh-session checks, size limits, fingerprint encoding,- adult category promotion and existing sync regression tests.-- 14 Python fixture/benchmark tests passed.-- Real emulator Room tests passed: SQL projection fields, provider isolation,- empty-lineup cleanup and full/section M3U catalog equivalence.-- FTS tests passed on fresh Room and actual databases migrated from v9 and v78.- They exercise initial insert, unchanged refresh, rename, partial insertion,- stale deletion, another provider, transaction rollback, stable local IDs,- favorite linkage and user protection through production staged promotion.- Before removing rebuilds, the same search matrix also passed through the- production promotion DAO calls without a rebuild.-- Data instrumentation now targets API 36. Its previously unspecified target- caused Android's old-app installation block. This affects the library test APK.-- The existing M3U equivalence assertion was corrected to normalize generated- identities across providers; provider IDs intentionally affect those hashes.- Stale-row assertions still inspect real persisted remote IDs.--## Measured results and limits--The 10,000-row/100-category synthetic fixture has the same payload SHA-256 as P3:-`4dfbcaf7e39ce168eb4cd58e34b5d8c78dddf4592d6638cb46c76b0fb31d63a3`.-On the API 36 emulator with the isolated debug app, five measured initial/refresh-pairs plus one warmup pair produced these medians:--| Operation | P3 | P4 before FTS removal | Change |-| --- | ---: | ---: | ---: |-| Add Provider backend | 4,245.5 ms | 3,883.6 ms | 8.5% lower |-| Settings Live refresh | 4,305.8 ms | 3,809.0 ms | 11.5% lower |--Report: `build/xtream-sync-performance/20261010T074712205202Z/report.json`.-All 12 samples retained exactly 10,000 channels and cleanup/count assertions-passed. Thirteen complete bulk responses occurred: one account had a redundant-third import, with a 7,831 ms refresh tail. This scheduling issue remains open.-Aggregate staging time across those 13 imports decreased from 21,982 to 20,043-ms. Peak sampled Java heap among measured pairs was 9,958,416 bytes; sampling-does not capture exact peak RSS or all native SQLite memory.--After FTS removal, all three modes passed initial and refresh coverage at 2,000-rows/10 categories, with no routine `channel-fts-rebuild` timing event. Report:-`build/xtream-sync-performance/20261010T075202281663Z/report.json`.-Category mode still incurs its old pacing floor; one refresh had an extra import.-These single samples are coverage checks, not comparable performance medians.--The final 50,000-row/200-category coverage run also passed both paths:-`build/xtream-sync-performance/20261010T075233892541Z/report.json`.-Initial import took 24,672 ms and refresh took 49,078 ms, versus P3's single-21,090/40,451 ms samples. Both runs performed three complete bulk imports for-two requested operations. This larger case does not show a latency improvement;-it retains the duplicate-refresh problem and requires more investigation.-The final run contained no global channel FTS rebuild timing events.--This is backend debug-emulator evidence. The emulator was restarted to resolve-the test installation investigation, and repeated runs can differ in device-state. Release-device end-to-end readiness, LOW/MID/HIGH acceptance and sustained-real-channel playback remain open. At the time of this P4 report, AUTO had not-yet changed; P6 later enabled bulk-first AUTO in normal app profiles on this-branch for direct testing. These results do not establish a tenfold overall-improvement.diff --git a/docs/XTREAM_SYNC_FAILURE_HARDENING.md b/docs/XTREAM_SYNC_FAILURE_HARDENING.mddeleted file mode 100644index 58f3da04..00000000--- a/docs/XTREAM_SYNC_FAILURE_HARDENING.md+++ /dev/null@@ -1,104 +0,0 @@-# Xtream failure handling and continuation queues--Date: 2026-10-10. Branch: `codex/xtream-live-sync-performance`.--## Changes--- A rejected bulk Live TV request no longer starts category-stream fallback for- authentication failures. An already-started category metadata request may finish.- Action-specific HTTP 403 remains eligible for category fallback: denying a full- catalog request does not by itself prove that the credentials were rejected.- HTTP 403 no longer spends three transient retries repeating the denied catalog- request before switching topology; transport/throttle retries retain backoff.-- Full sync preserves the previous Live success timestamp after failed or partial- coverage. Keeping the old channel library does not prove a fresh complete import.- A complete category fallback still counts as success despite bulk-path warnings.-- Retryable movie/series category discovery failures now produce durable index- continuations immediately. The worker retries category discovery before summaries.- Rejected credentials produce permanent job status and no automatic continuation.-- Authentication failures in full summary streams or category slices terminate- the section without scheduling more categories. A permanent rejection replaces- an older PARTIAL job, so recovery cannot repeatedly reuse that partial status.-- Launch/periodic summary admission does not restart FAILED_PERMANENT jobs merely- because they have no successful timestamp. Explicit forced operations can retry.-- Provider-specific index workers complete their WorkManager node after a recorded- permanent section failure, allowing already-appended sections to execute. The- durable index job and workflow retain the failure. Transient failures still use- WorkManager retry/backoff; standalone periodic batch failures still report failure.--## VOD and EPG ordering--Continue using durable queues. Add Provider commits Live TV first, then fetches-movie and series category shells before returning. Summary payloads and hydrated-details are outside initial Live ingestion; details remain on demand.-The category shells also identify VOD-only providers when Live TV is empty, so-this pass retains their existing setup/activation behavior.--The provider catalog continuation chain runs Live auxiliary index backfill, movie-summaries, and series summaries. Category slices checkpoint completed work and-enqueue continuation nodes. This is serialized provider work, not simultaneous-full Live/VOD/guide downloads. Category-shell failure now has an immediate durable-recovery path rather than depending on a later periodic check.--EPG is scheduled only when enabled, in a separate unique chain with the existing-30-second initial delay. It checks queued/running catalog jobs and defers with-backoff while they remain. Guide retries therefore do not occupy the catalog chain.-Transient catalog failures can delay subsequent catalog jobs; permanent failures-release the chain and remain visible in durable section state. This change does-not introduce parallel full VOD downloads or alter slice/batch budgets.--## Verification--Focused tests cover rejected Live bulk requests, rejected summary/category-requests, permanent-state admission, transient discovery continuations, previous-PARTIAL status replacement, recovery coalescing and failed-live freshness.--The benchmark's optional `--settle-seconds 30` observes terminal setup state and-channel counts every second after completion, before synthetic-provider cleanup.-Its request report rejects bulk requests occurring after category fallback begins.-Use setup-only runs; explicit refresh/background probes intentionally issue requests-and cannot be combined with this assertion. The observation window is bounded and-does not establish indefinite quiescence or playback health.--Two setup-only fault scenarios passed on the API 36 Android TV emulator, using-the isolated benchmark package with bulk-first AUTO explicitly enabled:--| Scenario | Live requests | Result | Observation |-| --- | --- | --- | --- |-| 1,000 channels / 20 categories, bulk disconnected after 500 rows | 4 incomplete bulk attempts, then 20 categories | Partial; all 1,000 rows and 20 category records matched fixture fields | 30 seconds of stable terminal state/count; zero bulk requests after fallback |-| Same Live catalog, bulk HTTP 503; 200 movies / 100 series with full summary HTTP 503 | 3 rejected Live bulk attempts, then 20 categories | Partial; exact Live fields; movie/series jobs SUCCESS with exact Room/index counts | 30 seconds of stable terminal state/count; zero bulk requests after fallback |--Reports are retained locally under ignored build directories:--- `build/xtream-sync-performance/hardening-truncated-bulk-1k/report.json`-- `build/xtream-sync-performance/hardening-503-bulk-vod-1k/report.json`--The earlier `hardening-truncated-1k` and `hardening-503-vod-1k` runs used the-benchmark's historical AUTO policy opt-out and made no bulk Live requests. They-passed category-route checks but are not evidence of bulk failure recovery.-Both corrected runs completed instrumentation successfully and recorded complete-request traces. Synthetic providers and reverse mappings were cleaned afterward.-EPG was SKIP in these fixtures; no guide download or playable media was tested.--Fixture/report/catalog-fixture Python tests passed (17 tests). The final Gradle-run passed 196 JVM tests: 181 focused sync tests and 15 backup manager tests-included by the test-name filter. This includes the HTTP 401/403 distinction,-attempt isolation, category scheduling, provider recovery and continuation tests.-Both isolated app and instrumentation APKs assembled successfully; their package-IDs were checked before installation. `git diff --check` passed.--Queue completion/admission policy has focused unit coverage. The emulator VOD-run exercises successful continuation after transient bulk rejection; it does-not exercise a permanent-failure WorkManager dependency chain or EPG fetching.-Real-provider sync, guide acceptance, sustained playback and other fault profiles-remain separate release gates.--## Manual testing default follow-up--The isolated benchmark package formerly defaulted to the historical AUTO policy-whenever its override preferences were absent. After instrumentation cleaned the-preferences, a manual Add Provider run in that same app therefore selected-category mode on LOW devices. The emulator log and foreground package identified-this mismatch. Its ordinary UI now defaults to bulk-first like normal packages.-The instrumentation harness writes an explicit true/false override for route-comparisons and clears it afterward; historical opt-out comparisons remain available.diff --git a/docs/XTREAM_SYNC_IMPROVEMENT_PLAN.md b/docs/XTREAM_SYNC_IMPROVEMENT_PLAN.mddeleted file mode 100644index d5f871dd..00000000--- a/docs/XTREAM_SYNC_IMPROVEMENT_PLAN.md+++ /dev/null@@ -1,542 +0,0 @@-# Xtream sync improvement plan--Status: implementation in progress on `codex/xtream-live-sync-performance`.-Prepared 2026-10-09 against source revision `540ec30c`.--Supporting evidence:--- [Initial live import comparison](XTREAM_LIVE_IMPORT_COMPARISON.md)-- [Current sync engine review](XTREAM_SYNC_PERFORMANCE_REVIEW.md)-- [Initial backend baseline](XTREAM_SYNC_INITIAL_BASELINE.md)-- [Attempt isolation and recovery implementation](XTREAM_SYNC_RECOVERY_IMPLEMENTATION.md)-- [Live parsing and group identity implementation](XTREAM_SYNC_PARSING_IMPLEMENTATION.md)-- [Bounded live pipeline implementation](XTREAM_SYNC_PIPELINE_IMPLEMENTATION.md)-- [Database write and search implementation](XTREAM_SYNC_DATABASE_IMPLEMENTATION.md)-- [Live category scheduling implementation](XTREAM_SYNC_CATEGORY_IMPLEMENTATION.md)-- [Completed primary resume coalescing](XTREAM_SYNC_RESUME_IMPLEMENTATION.md)-- [P6 live strategy and tuning report](XTREAM_SYNC_P6_TUNING_REPORT.md)-- [P7 summary and background implementation](XTREAM_SYNC_P7_IMPLEMENTATION.md)-- [P0 50k scale and batch sweep](XTREAM_SYNC_P0_SCALE_REPORT.md)-- [Failure handling and continuation queues](XTREAM_SYNC_FAILURE_HARDENING.md)--## Current status (2026-10-10)--| Work item | Status | Done | Remaining |-| --- | --- | --- | --- |-| P0 baseline | In progress | Synthetic backend fixture, initial baseline, synthetic first-browsable-row probe, controlled 50k-row scale/batch sweep, repeated/randomized 10k route comparisons across simulated LOW/MID/HIGH policies, field equivalence after both routes, hidden-scope refresh and fallback, and a verified 503 fallback terminal-state/retry-quiescence fix | Other fixture/provider profiles, terminal-state and retry-quiescence behavior for truncated-body and other failure paths, broader refresh cases, attributable allocation/CPU profile, release-build/device comparison and frozen acceptance gates |-| P0 50k scale and batch sweep | Done | Six API 36 emulator batch profiles plus a matched 50k route comparison; 50,000/50,000 rows committed; same fixture hash | Exploratory only; no repeatable batch-size gain; see linked report |-| P0 10k route comparisons | Done | Three alternating-order LOW/100 pairs plus three seeded randomized pairs per simulated LOW/MID/HIGH policy; complete samples and request logs; see the P0 report | One synthetic fixture and emulator only; other provider distributions remain open; this sweep did not change stage-batch defaults |-| P0 persisted row/field equivalence | Done | All 50,000 rows and 200 category records checked after both routes; malformed rows, hidden-category refresh on both routes, and exact fields after HTTP 503/truncated-body category fallback checked; 10k HTTP 503 fallback now settles at Partial without post-fallback bulk retries | Synthetic emulator only; other failure paths and provider distributions remain open; see linked report |-| P1–P5 | Done | Implementation and focused correctness/performance evidence are recorded in the linked reports | P6/P8 release acceptance still depends on these components passing the full matrix |-| Failure handling and continuation queues | Done | Live/VOD authentication termination, durable category-discovery retries, failed-live freshness correction, permanent section queue handling, and 30-second truncated/503 fallback checks | Other fault/provider profiles, longer retry observation and real EPG/playback acceptance remain open; see linked report |-| P6 implementation and emulator exploration | Done | Bulk-first AUTO is active in normal app profiles on this branch; hidden-scope behavior, progress labels, and synthetic 10k-row tuning matrix are implemented | Physical-device/provider acceptance remains open; stage batch defaults are unchanged |-| P6 emulator follow-up | Done | Fresh benchmark APK exercised 10k-channel AUTO bulk success and HTTP 503 category fallback; prior Settings refresh, Welcome-to-Live first-row, and no-ID stale-worker checks also passed on API 36 emulator | Physical LOW/MID/HIGH, real-provider and sustained-playback validation remain deferred |-| P6 physical-device/provider validation | Deferred | No physical devices are available; the branch debug APK is installed and launched for user-side provider testing | Run and record the real-provider sync/playback check; physical LOW/MID/HIGH validation stays deferred |-| P7 implementation | Done | Summary diffing/fingerprints, checkpointed row/time slices, catalog-before-guide scheduling, focused unit coverage, and fingerprint allocation reduction | Bulk-refresh gain is route-specific; physical tuning remains open |-| P7 emulator summary matrix | Done | 2k/1k category fallback under LOW/MID/HIGH/DEVICE; bulk-success comparison; 8k/4k bulk-success and LOW fallback; Room counts and warmup preservation checks passed | Physical tuning is tracked separately |-| P7 before/after unchanged VOD refresh comparison | Done | Pre-P7 commit compared with P7 working tree on the same API 36 emulator, fixture, LOW policy and 100-row stage batch; ten measured bulk-success samples and five fallback samples per build | Bulk success was 59.69% faster; fallback was effectively unchanged; sampled heap increased, so no blanket speedup claim |-| P7 fingerprint allocation follow-up | Done | Removed per-field length-buffer and per-byte formatter allocations while preserving persisted SHA-256 encoding; repeated emulator runs passed for bulk success and category fallback | Sampled refresh peak fell 32.4% on bulk success and 25.5% on fallback versus P7; physical tuning is still required |-| P7 physical-device tuning | Deferred | Not run; no physical devices are available | Resume if target hardware becomes available |-| P8 end-to-end release validation | Pending | — | Real-provider two-channel sustained playback and rollout/rollback evidence |--The reference implementation provides hypotheses to investigate, not a design-authority or proof of correctness. Choose behavior for this app's measured-performance, provider compatibility, persistent library and recovery guarantees.-Keep, change or reject each reference idea independently. No performance claim-from another app substitutes for our validation.--## Outcome and scope--Make the complete Xtream live lineup available substantially sooner when adding-a provider. Apply the same ingestion improvements to Settings Live TV sync and-automatic refresh. Then improve movie/series summary ingestion and background-work using the proven components.--Priority order:--1. Initial Add Provider live import: request topology, parsing, mapping, staging- and promotion through the first usable live screen.-2. Settings/manual/background live refresh, including unchanged catalogs.-3. Movie/series summaries and index persistence.-4. Background scheduling, EPG handoff and progress clarity.--EPG scheduling does not explain the initial live import delay. Keep it outside-the first performance milestone. Keep movie/series payloads and EPG out of the-initial live bandwidth budget; retain their durable follow-up behavior.--The milestone means the complete accepted live catalog is committed and-browsable. A preview or earlier completion label does not count as faster full-ingestion. Retain Room storage, provider configuration workflows and existing-repository contracts. Other provider protocols receive regression coverage when-shared helpers change; redesigning their ingestion is outside this plan.--## Performance contract--Capture baseline before changing behavior. Record both the entire Add Provider-journey and its live segment: authentication, ingest, promotion and first live-screen. Also report the time from live promotion to setup completion, so category-shell or navigation costs cannot be silently attributed to live ingestion.--Initial engineering targets, to calibrate against baseline measurements:--| Scenario | Target |-| --- | --- |-| Many-category initial import on a healthy bulk-capable provider | At least 80% lower median complete-live time than current AUTO, a 5x improvement; 10x is a stretch target |-| Parsing on identical bulk payload | At least 50% lower parser CPU time without changing accepted row semantics |-| Existing healthy bulk route | Improve the dominant measured costs; no repeatable median or tail regression above 10% |-| Unchanged live refresh | Skip unchanged catalog writes and eliminate unnecessary full index passes |-| Memory | Bounded transient parse/map/write batches, no OOM on agreed LOW/MID/HIGH device scenarios |-| Correctness | Same complete channel coverage and required fields; preserve stable IDs and user state |--These are targets, not established results. Network-limited and bulk-rejecting-providers need separate expectations. Freeze scenario-specific release gates-after baseline; document a revised target if measurements show a different-constraint. Count reduction alone is insufficient to establish a speedup.--Use one warm-up and at least five measured runs for each main baseline/final-comparison, report median and maximum; use a larger sample before claiming p95.-Use the same fixture seed/provider snapshot, device, build type, network policy-and hidden-category settings. Clean provider state for initial-import runs;-preserve state for refresh runs. Separate emulator diagnostics from measurements-on a physical TV-class device. Report setup/account validation latency separately-from catalog speed when the server varies it.--## Architecture decisions--### Bulk first, provider-aware fallback--AUTO should prefer the validated bounded bulk path for a healthy provider.-Device tier controls resource budgets; LOW/MID alone should no longer force-hundreds of requests once the new path passes constrained-device validation.-Explicit CATEGORY_BY_CATEGORY remains a supported choice. Explicit STREAM_ALL-continues to express a bulk preference, with failures surfaced or recovered-according to a documented contract; do not silently label fallback as bulk.--Persist observed bulk support/failure state with a cooldown and eventual probe.-Existing liveAvoidFullUntil and health fields may be reused when their meaning-matches. Do not conflate category throttling with proof that bulk is unsupported.-Separate authentication failures, HTTP throttling, interrupted transfers,-malformed shapes, size admission failures and actual memory pressure.--For hidden categories, support early row filtering plus preservation of existing-hidden content and required hidden rows. Full bulk still downloads hidden rows,-so a provider with most categories hidden may benefit from selected categories.-Use measured/known catalog coverage for that decision; a newly added provider-has no reliable category size estimates. Keep destructive pruning confined to-confirmed complete scopes.--### Two concurrent live requests and a bounded pipeline--After authentication and workflow acquisition, start live category retrieval-and one bulk live-stream request concurrently. The same provider request budget-governs both. Do not split one live array into arbitrary parallel downloads.--The intended AUTO default is one complete live-list HTTP response, decoded-incrementally as it arrives. Parallelism comes from fetching category metadata-alongside it and overlapping decode with mapping/database staging. The current-bulk request interface does not provide independently addressable row ranges;-starting the same full request multiple times repeats data rather than divides-work. Parallel category requests remain the fallback/selected-category strategy.--Do not fetch movies/series in parallel with initial live ingestion by default:-they compete for provider connections, bandwidth, CPU and memory while the-priority is live readiness. Their later concurrency should be measured within-the shared resource budget. Benchmark bounded concurrent category loading as-an alternative to bulk too; if a provider handles categories substantially-better, the provider-aware planner should use that evidence.--```mermaid-flowchart TD- A[Acquire provider workflow and resource budget] --> C[Fetch live categories]- A --> R[Fetch and decode full live array]- C --> M[Resolve immutable category context]- R --> Q[Bounded queue of thin row batches]- M --> W[One mapper and staging writer]- Q --> W- W --> V[Validate completed snapshot]- V --> P[Atomically promote catalog and required indexes]- P --> U[Publish live readiness]- U --> B[Durable catalog and guide follow-up work]-```--The reader produces thin rows. The consumer waits for category context before-classification and staging; the queue may fill while categories are pending,-but stays bounded. Category retrieval returns either authoritative context or-an explicit failure result with existing fallback-category semantics. Resolve-that result once; mapping must not trigger repeated category network fetches.--Use structured coroutines: reader failure cancels/drains the consumer safely;-writer failure cancels the HTTP call; parent cancellation closes response bodies-and queues. Close normally only after valid end-of-document. Promotion waits-for reader completion, queue drain and all durable writes.--One writer owns counters, duplicate admission and session state. This avoids-concurrent mutation and category-stage mutex contention. Bound queued batches,-row field sizes according to existing admission rules, retained metadata and-any producer concurrency. A bounded queue alone does not make an unbounded-HashSet of all stream IDs or category cache bounded: account for these explicitly-and evaluate stage-table uniqueness as an alternative deduplication mechanism.--Initial tuning candidates, evaluated against current 100/300/500 batches:--| Tier | Candidate row batch size | Maximum queued batches |-| --- | --- | --- |-| LOW | 128–256 | 1 |-| MID | 512 | 1–2 |-| HIGH | 1,024 | 2 |--These are benchmark candidates, not production defaults. Count the producer's-current batch and writer's current batch too. Select production values using-allocation/heap headroom, row width, cancellation latency and transaction-duration. Retain global size caps and bounded SQL parameter chunks. Parallel-provider imports need an app-wide resource budget, not only per-provider limits.--### Direct decoding and minimal mapping--Introduce a live-specific direct token decoder, initially alongside the current-path. The existing JsonReader infrastructure can be reused; avoid per-row Gson-trees, JSON reserialization and second decoding. Return thin typed live rows,-not a generic map retaining every scalar field. Skip irrelevant nested payloads.--Support current numeric/string/null field variants, singular/plural category-IDs, archive flags and provider text compatibility. Add deliberately supported-root-array/wrapper shapes with explicit recognition. Authentication/error-objects must never become successful empty catalogs. Distinguish a malformed-row with valid structural boundaries from an invalid/truncated JSON document.-Track skipped rows and prevent degraded coverage from being labeled complete.--Preserve server ordering/num, EPG IDs, catch-up fields, adult/protection behavior,-logo cleanup and internal stream URL semantics. Keep provider credentials out-of logs. Retain custom headers and User-Agent on every request.--Extract a group-key-only path from ChannelNormalizer after proving it produces-the same logicalGroupId as classify. Avoid calculating unused resolution,-language, codec and other variant attributes during import. Keep canonical key-semantics stable, because changing grouping identity can affect the library.-Compute row fingerprints once from normalized fields where practical.--### Attempt isolation and durable snapshot rules--Audit retry/fallback before introducing concurrency. Current full streaming-keeps staging session, seen IDs and counters outside the retry block. New code-must make ownership and reset behavior explicit; this observation is a risk to-test, not a claim of a reproduced data-loss bug.--Each bulk attempt owns a fresh session, counters and buffered batches. On a-failed attempt, cancel/drain work and discard its session before retry. If a-future resumable protocol is implemented, it needs explicit coverage/checkpoint-semantics; concatenating two full responses is not a resume protocol.--For category fallback, isolate category attempts too. Only successful category-attempts contribute confirmed coverage; promote them into the import session-without letting failed retries leave stale membership. Keep successful category-results while retrying failed categories. This requires category-scoped attempt-staging or equivalent provenance, not a shared dedup set alone.--Persist complete-response status separately from staged row count. Recover and-fully promote only a snapshot durably marked complete after writer drain. The-current onboarding recovery must be checked because non-empty staged rows alone-cannot prove the remote response finished. Incomplete bulk sessions restart or-remain explicitly partial; they must never trigger full stale-row deletion.--Retain configuration generation, workflow lease and commit fences in the same-transaction as promotion. Recheck ownership for staging/commit under the existing-contract; optimize query frequency only with equivalent supersession protection.-If extra fields/tables are necessary, include Room migration and older-state-recovery tests. Temporary failures leave the previous active catalog intact.--### Efficient persistence and indexes--Track accepted stage count in the session writer after successful writes;-reconcile from the database when recovering. Enforce limits using admitted-unique rows, and do not count duplicates as additional catalog coverage.-Investigate bounded category SQL summaries instead of repeatedly materializing-all fallback categories each batch. Keep transaction duration controlled.--For first import, use staged bulk insertion and SQL promotion without loading-the entire live lineup into Kotlin. For refresh, use fingerprints/changed-row-diffs to avoid rewriting unchanged channels. Preserve local IDs, favorites,-user protection, overrides and history. Optimize correlated changed-column-lookups only after separating first-import and refresh measurements.--Verify Room FTS maintenance triggers on fresh and upgraded databases. Remove-the global rebuild from routine promotion only if integration tests prove search-correctness for inserts, renames, removals, unchanged refresh and multiple-providers. Retain an explicit repair/rebuild operation. Do not suppress triggers-without a transactionally correct replacement.--Replace the later whole-list Xtream live index backfill with SQL projection or-bounded updates. Decide whether the auxiliary index is required for initial-browsing/search; required indexes complete before their readiness milestone.-Every index must use the same complete generation, including safe stale cleanup.-Do not advertise search readiness while a required index remains queued.--### Category fallback that stays busy--Replace grouped awaitAll windows with a continuously filled bounded worker pool.-Start conservatively and adapt request concurrency and spacing using measured-provider stress. Retain a device/resource ceiling, honor usable Retry-After,-back off on throttle/reset/timeout and stop pointless authentication retries.-Healthy providers should not inherit a universal 250 ms request-start delay.--Use one writer for all successful category producers. Persist category coverage-and retry failed categories only. Avoid sharing unsafe modifications with other-protocols. Keep non-retryable errors, valid emptiness and partial success distinct.-Test the effect of UI priority requests without interrupting a coherent commit.--## Implementation work packages--Each package is a separately reviewable change with its own evidence. Run-focused checks after each; run the complete relevant set at integration/release.-Measurements can change tuning choices, but must not silently change coverage-or completion semantics.--| Package | Work and primary files | Depends on | Exit criteria |-| --- | --- | --- | --- |-| P0 | Baseline and scalable fixture; timing in OkHttpXtreamApiService, live strategy, SyncCatalogStore, setup/readiness; tools and benchmark harness | Inspection | Reproducible initial/refresh report with counts, strategy and stage/memory costs |-| P1 | Attempt isolation, durable completion/coverage, cancellation; live strategy, catalog stager/store, onboarding state/DAO, commit fence | P0 | Truncation/retry/process-death cannot promote an incomplete full snapshot or lose active data |-| P2 | Direct live token decoder and compatible thin rows; HTTP service, XtreamDtos, XtreamProvider, ChannelNormalizer | P1 | Field-equivalent output, correct errors and lower measured parse/map CPU |-| P3 | Concurrent category/bulk retrieval and bounded reader/writer pipeline; live strategy/support, stager, runtime profile | P2 | Observable overlap, enforced queue/resource bounds, no extra category fetches, complete cancellation |-| P4 | Stage accounting, promotion/FTS/index cost; catalog store/DAO, index DAO, live backfill | P3 | Lower stage/commit cost, unchanged rows avoided, verified search and stable user state |-| P5 | Refilled category workers and adaptive pacing; XtreamFetcher, XtreamSupport, adaptive policy | P1 and P3 | Idle slots reused; isolated failed categories; reliable throttled/bulk-rejecting fallback |-| P6 | AUTO strategy and unified live behavior; live policy/profile, metadata, full/section routing, setup and Settings progress | P4 and P5 | Bulk default passes LOW/MID/HIGH scenarios; explicit modes and hidden scopes work across entry points |-| P7 | Movie/series summaries reuse and background priority; incremental executor, worker, continuation scheduler, summary DB writes | P6 | Faster summaries, preserved hydrated details, catalog-before-guide scheduling, bounded completion jobs |-| P8 | End-to-end acceptance, sustained playback, rollout and report | P6; P7 for full Xtream release | Gates met, evidence archived, rollback path proven |--P6 is the first live performance release milestone; P7 follows it. Normal app-builds on this branch now use bulk-first AUTO so the changed sync can be tested-directly. Keep the measured stage-batch defaults until physical-device evidence-supports a retune. The isolated benchmark package can still compare the prior-AUTO policy with the bulk-first policy using identical data coverage.--Implementation progress on 2026-10-10: P0 has an initial backend baseline,-isolated fixture, synthetic first-browsable-row probe, controlled 50k-row-scale/batch sweep, matched bulk/category comparison, all-row field equivalence-for both initial-import routes, malformed-row handling, a hidden-scope live-refresh check on both routes, 503 and truncated-body category fallback field-checks, and repeated/randomized 10k route comparisons across simulated-LOW/MID/HIGH policies. Larger batch profiles did not show a repeatable-elapsed-time gain, so production batch defaults remain unchanged. The original-503 run exposed `Syncing` plus three later bulk retries after full category-coverage. After updating queued onboarding recovery coalescing, a repeat 10k-HTTP 503 run verified 10,000 fields and 100 categories, settled at `Partial`,-made only the three initial bulk attempts and zero post-fallback bulk requests;-the log confirmed the queued recovery was coalesced after onboarding completed.-The truncated-body run showed `Partial` after full row coverage but has not been-rerun after this change. Other fixture/provider comparisons, lifecycle checks-for other failure paths, broader refresh cases, attributable allocation/CPU-profiling, release-build/device comparison and frozen acceptance gates remain-open; see the-[P0 scale report](XTREAM_SYNC_P0_SCALE_REPORT.md). P1 attempt isolation and conservative receipt-based-recovery are implemented and validated. P2 direct live decoding and cheaper-group identity are implemented with field-equivalence checks and measured-component CPU reductions. P3 retrieval overlap and a bounded reader/writer-pipeline are implemented with cancellation, resource-bound and real-graph-setup/refresh evidence. P4 stage accounting, fingerprint costs, SQL live-index-projection and trigger-maintained search are implemented with fresh/migrated-Room checks and measured backend improvements. P5 refilled live-category-workers and adaptive pacing are implemented with cancellation, authentication-and Retry-After coverage. Targeted primary recovery now rechecks completion-under the provider lock and coalesces already successful foreground imports.--Bulk loading progress follow-up (2026-10-10): the Add Provider callback now-reports the accepted channel count after successful staging writes, for example-`Loading Live TV channels...` followed by `3,200 channels processed`. Updates-are throttled to 250 ms, with the final drained count always published. A new-attempt clears the discarded count. The bar remains indeterminate because-the bulk endpoint supplies no reliable total; Saving and Ready remain tied to-catalog promotion. Focused reporter, strategy callback and progress-parser-tests cover these behaviors; no real-provider UI acceptance is claimed here.--P6 bulk-first AUTO behavior, hidden-category routing and user-facing progress-are implemented. Normal app profiles now enable bulk-first AUTO; the isolated-benchmark package retains an explicit policy override for comparisons. Batch-and policy measurements cover one synthetic API 36 emulator, 10,000 rows and-five measured runs, but tier values were simulated. A fresh build was reinstalled-and rerun on the emulator: AUTO retained and field-verified all 10,000 channels-with one bulk request; a second AUTO run with three HTTP 503 bulk rejections-completed all 100 category requests, retained and field-verified all 10,000-channels, and emitted no post-fallback bulk retries. The synthetic setup-to-first-row-measurement exercises the real Welcome-to-Live UI with a synthetic channel, and the no-ID-ProviderSyncWorker stale-refresh branch succeeds through WorkManager with-preserved 10k catalog coverage. These are emulator evidence, not physical-device-or release-build comparisons; WorkManager interval/constraint scheduling,-real-provider behavior and sustained playback remain open. The P6 release gate-therefore remains open even though bulk-first AUTO is now active on this branch.-Production stage-batch defaults remain unchanged. P7 summary deduplication,-bounded category slices,-catalog-before-guide scheduling and separate guide work are implemented with-focused tests. The API 36 emulator completed the synthetic VOD/series matrix:-2k/1k category fallback under LOW/MID/HIGH/DEVICE, a bulk-success comparison,-and 8k/4k bulk-success and LOW fallback runs. Counts, index jobs, and warmup-Room preservation checks passed. A separate unchanged-summary refresh-comparison against pre-P7 commit-`2af03f5149e888d25307457d4cce82fab3de74d9` used ten measured bulk-success-samples and five fallback samples per build. Median time was 59.69% lower on-the bulk-success route, while category fallback was effectively unchanged-(0.89% lower). Maximum sampled Java heap rose from 10.09 to 17.19 MiB on bulk-success and from 9.01 to 10.83 MiB on fallback. The full bulk sample set is-reported because baseline timings settled during measurement; no samples were-trimmed. The result supports only a bulk-success refresh gain; fallback and-memory observations remain open for physical-device tuning. A follow-up removed-per-field length-buffer and per-byte formatter allocations while retaining the-same fingerprint encoding. Repeated unchanged-refresh runs reduced the sampled-peak by 32.4% on bulk success and 25.5% on category fallback versus P7; fallback-timing remained effectively unchanged. The bulk peak remains 1.52 MiB above-the pre-P7 maximum, and all results are from one emulator. Physical tuning is-deferred because no physical devices are available. P8 is pending because-real-provider sustained playback and rollout/rollback validation have not been-performed. The status table above marks completed work separately from open-acceptance. Reports linked above record the evidence and limits.--## P0 measurement and fixture deliverables--Add a dedicated configurable Xtream performance fixture; do not inflate the-existing one-channel catalog correctness fixture or change its stable entries.-Suggested artifacts: tools/xtream_sync_perf_fixture.py, fixture tests, and a-connected benchmark driver writing ignored build/xtream-sync-performance files.-Keep payload generation streaming too, so fixture memory/server generation does-not dominate or mimic client performance. Record server request starts/ends,-bytes and fixture seed. Use synthetic credentials only.--Provide configurable channel/category counts, deterministic metadata, category-distribution, bandwidth/header delay, category latency, throttling, bulk rejection,-malformed rows and mid-response disconnects. Record the dataset checksum.--Timing records use a monotonic clock, run ID, provider ID, configuration-generation, section, attempt and strategy. Include:--- Authentication, workflow wait and request start/header/first-row timestamps.-- Categories ready, reader complete, writer drained, commit complete, setup- complete and first browsable live-screen timestamps.-- Accepted/duplicate/skipped/hidden counts, confirmed category coverage, bytes,- requests, retries/fallback reasons and maximum active request count.-- Parse/map/stage CPU or attributable duration, queue blocked time/high-water,- transaction/FTS/auxiliary-index durations, peak heap and GC activity.--Overlapping stage durations cannot be summed to derive wall time. Reader-completion includes backpressure; distinguish it from parser CPU and network-waiting. Avoid claiming pure transfer time from the current full ingest timer.-Log aggregate/batch summaries with throttling, never per channel. Export-sanitized JSON and a compact Markdown comparison; no credential URLs or body-previews in benchmark artifacts.--## P6 behavior across entry points--Add Provider uses the new pipeline and finishes after a coherent live catalog-and existing required setup work. Publish live readiness immediately at the-proper milestone; movie/series summaries and EPG remain durable follow-ups.-Preserve provider activation and saved-with-warning behavior for empty or-unavailable live-only/VOD-only providers. Navigation must not depend on an-auxiliary background job that the live screen does not require.--Settings TV, full refresh and background stale refresh share the same live-planner and importer. Reason affects priority/refresh policy, rather than forcing-category loading for every manual/background request. Explicitly map full and-section requests so FOREGROUND does not hide a manual/background reason.-Respect force versus freshness and cancellation. Unchanged refresh should keep-the current catalog visible throughout.--Progress phases: connecting, loading live channels, saving channels, live ready.-Use item counts when the provider has no trustworthy total; do not manufacture-a percentage. Category fallback may show confirmed categories/total. Progress-and completion must represent committed rows, not only decoded or queued rows.-Expose strategy/fallback details in diagnostics, with plain user-facing labels.--## P7 remaining Xtream work--Reuse direct-decoding and bounded-write components for movie/series summary-streams after their live validation. Keep rich details and episodes on demand.-Preserve existing hydrated fields, TMDB identities and watch progress during-summary refresh. Skip unchanged rows, avoid read-after-write where stable ID-mapping can be obtained cheaply, and maintain required indexes in bounded work.--Replace the universal two-category worker slice with a measured time/row budget-and durable per-category checkpoints. Guarantee forward progress under repeated-failures and requested-category priority. Prune stale items only after confirmed-complete section coverage, preserving hidden scopes and partial results.--Schedule required catalog work ahead of delayed guide work in the existing-provider workflow chain. Coalesce redundant pending work where possible. Do not-create competing queues without addressing leases, locks and commit ownership.-Guide retry/delay should not starve movie/series availability. Settings must-distinguish category shells queued, summary catalog complete and guide complete.--## Validation matrix--| Area | Required scenarios and assertions |-| --- | --- |-| Dataset | Small 1k, typical 10k, large 50k/100k live rows within existing admission limits; 1/20/200/500 categories; uneven and empty categories; duplicate IDs |-| Provider | Healthy bulk, slow headers/body, category-only, throttle with/without Retry-After, resets, authentication/error-object response, unsupported wrapper, oversized response |-| Parser | String/number/null IDs and flags, category_ids, order/num, EPG IDs, catch-up, Unicode/text compatibility, unknown/nested fields, valid empty, semantic bad row, truncated JSON after staged batches |-| Refresh | Zero/1%/30% changed rows, additions/removals/renames, multiple providers, hidden/protected/required categories, existing favorites and local overrides |-| Lifecycle | Cancel during categories/reader/write/commit, writer failure, process death before/after completion receipt, retry after partial body, provider edit/delete/supersession, app restart |-| Memory/concurrency | LOW/MID/HIGH, actual pressure, long/wide rows, full queue, slow writer, duplicate tracker growth, simultaneous provider work, cancellation while backpressured |-| Entry points | Add Provider, Settings TV, full refresh/rebuild, automatic refresh, explicit AUTO/STREAM_ALL/CATEGORY_BY_CATEGORY, live-empty provider with other content |-| Search/index | Insert/update/delete/unchanged results, old DB migration, global multiple-provider FTS correctness, incomplete/complete auxiliary index states |--Extend existing focused tests: OkHttpXtreamApiServiceTest, XtreamDtoParsingTest,-XtreamProviderTest, SyncManagerXtreamLiveStrategyTest, SyncManagerXtreamSupportTest,-XtreamLiveSyncPolicyTest, SyncCatalogStoreTest, commit-fence/workflow tests and-ChannelNormalizer tests. Add genuine backpressure/cancellation/attempt isolation-tests with controllable producer/writer barriers. Do not use timing sleeps as-the primary unit-test assertion for concurrency.--Use Room instrumentation for actual FTS trigger/migration/promotion behavior,-stable IDs and process-death recovery, extending CatalogSyncEquivalenceIntegrationTest-and ProviderWorkflowIntegrationTest where appropriate. Extend setup/Settings-tests for actual completion/warning/cancel semantics. Benchmark generated Room-code on-device; mocked DAO timings are not persistence performance evidence.--Run focused data/domain/feature Gradle test tasks as affected, followed by data-connected instrumentation and the app/benchmark journey for the changed routes.-Resolve exact test variants from the project at implementation time. No build,-launch or single screenshot is sufficient evidence of an improved sync.--After the final live change, select at least two representative live channels-and validate actual playback in the emulator using repository instructions:-61 screenshots per channel at 2-second intervals, unique hashes demonstrating-continued progression, media-session PLAYING with error=null, and sanitized-HLS/recovery logs with no fatal/stuck error or unintended MPEG-TS fallback.-Report channel names, count/interval, unique hashes, media session and log findings.-This verifies playable imported rows; fixture-only channel counts cannot replace-it. Retain screenshot sequences and logs under ignored validation artifacts.--## Rollout, rollback and completion--Keep implementation changes separable from strategy selection. Use internal-debug configuration for controlled comparisons; avoid exposing experimental-parser/batch toggles to users. Ship the validated live path before expanding-to other sections. Preserve explicit category mode as a compatibility escape-route; actual rollback can revert AUTO selection independently of the parser.-Prove migrations and session receipts remain readable by the supported rollback-version, or document a version boundary before shipping schema changes.--Completion checklist:--- [ ] P0 baseline archived, bottleneck ranking and gates frozen.-- [ ] P1–P5 correctness and performance evidence reviewed.-- [ ] P6 live-only release meets agreed latency/memory/coverage gates.-- [ ] Settings/background refresh passes the shared-path matrix.-- [ ] Required browse/search indexes and user state remain correct.-- [ ] Retry/cancel/death/edit/delete preserve coherent catalog ownership.-- [ ] Two-channel sustained playback report recorded.-- [x] P7 catalog/guide follow-up improvements verified independently.-- [x] Before/after report includes build revisions, device/runtime, data seed,- counts, requests, medians/spread, heap/GC, fallback behavior and limitations.-- [x] Branch AUTO activation/default behavior, direct-test APK and current- validation limits documented.-- [ ] Release rollout/rollback and supported schema migration compatibility- proven.--No package is marked complete until its evidence exists. The first P0 backend-harness, timing hooks and measurements are implemented on-`codex/xtream-live-sync-performance`. See the-[benchmark guide](XTREAM_SYNC_BENCHMARK.md) and-[initial baseline](XTREAM_SYNC_INITIAL_BASELINE.md) for the initial redirected-category-only runs and remaining P0 gates. Later P6 candidate runs exercised-the synthetic bulk route; they do not replace physical-device, provider, or-first-screen measurements. Follow-up work also showed requests continuing-after workflow supersession; prompt termination and joined cleanup are covered-by P1. Measured bottlenecks guide tuning while the correctness and complete-live-outcome above remain fixed.diff --git a/docs/XTREAM_SYNC_INITIAL_BASELINE.md b/docs/XTREAM_SYNC_INITIAL_BASELINE.mddeleted file mode 100644index 20c31683..00000000--- a/docs/XTREAM_SYNC_INITIAL_BASELINE.md+++ /dev/null@@ -1,98 +0,0 @@-# Initial Xtream live backend baseline--Measured on 2026-10-09 using the first P0 implementation on-`codex/xtream-live-sync-performance`, based on `develop` at `540ec30c`.-This is the current importer with timing hooks, not an optimized implementation.-Reproduction and limitations: [benchmark guide](XTREAM_SYNC_BENCHMARK.md).--## Environment and dataset--- Debug APK, Android TV x86_64 emulator, API 36,- model `sdk_google_atv64_x86_64`, memory class 192 MB, low-RAM flag false.-- Maximum Java heap 201,326,592 bytes. Android's live low-memory signal can- change independently of heap occupancy or the low-RAM device flag.-- 10,000 live rows, 100 categories, seed 1, no artificial network delay,- bandwidth cap, throttling, malformed rows or disconnects.-- Live payload SHA-256:- `4dfbcaf7e39ce168eb4cd58e34b5d8c78dddf4592d6638cb46c76b0fb31d63a3`.-- EPG skipped; movie/series shells empty. Production background jobs enabled.-- One warmup and five measured initial imports per requested mode.--```powershell-python tools/xtream_sync_benchmark.py --channels 10000 --categories 100 --iterations 5 --warmups 1-```--## Results--| Requested mode | Setup median | Setup max | Live-committed median | Saved channels | Observed measured live requests |-| --- | ---: | ---: | ---: | ---: | --- |-| AUTO | 25.300 s | 25.334 s | 25.240 s | 10,000 | 100 categories/import; zero bulk |-| STREAM_ALL | 25.286 s | 25.293 s | 25.228 s | 10,000 | 100 categories/import; zero bulk |-| CATEGORY_BY_CATEGORY | 25.282 s | 25.305 s | 25.224 s | 10,000 | 100 categories/import; zero bulk |--All 18 imports, including warmups, passed expected channel counts and provider-cleanup. Instrumentation passed, the completion marker was captured, all samples-were recorded, and the bounded request-event history was not truncated. Global-server request high-water was two, including background traffic; it is not proof-of parallel live category downloads for an individual import.--**This is not a bulk-versus-category performance comparison.** The current-engine's strategy/safety checks redirected the requested STREAM_ALL runs to-categories before a bulk request. Logs confirmed the full-catalog skip. AUTO-also selects categories for this device's LOW tier. A valid bulk comparison-requires an environment where the current guard permits a complete bulk attempt.--Maximum sampled Java heap among measured samples: AUTO 14,443,440 bytes,-STREAM_ALL 16,101,696 bytes, categories 12,169,536 bytes. ART GC count deltas-ranged from 374–504, 359–370 and 356–361 respectively. These are process-wide-debug values, including potential background work, not allocation measurements-or evidence that Android's system-wide low-memory signal must be false.--One representative measured import had 2,028 ms summed staging time across 100-100-row batches. Final category staging/commit took 10/1 ms; channel promotion-took 47 ms and FTS rebuild 8 ms. Most wall time precedes final promotion.-The healthy category request spacing of 250 ms imposes a roughly 24.75-second-floor for 100 sequential starts. Mapping and staging also occupy that interval;-these overlapping costs must not be added as independent delays. Profile mapping-and decoding further before assigning CPU percentages.--## Settings refresh smoke check and recovery--A separate 2,000-row/10-category run passed initial import and live Settings-repair for every mode, with exact counts and cleanup. It is one sample per-phase/mode with no warmup, so it is a functional smoke check, not a refresh-performance gate. That run showed interrupted bulk attempts due to-`LowMemoryCatalogAbortException` followed by category recovery. One completed-bulk response also appeared in logs; concurrent follow-up work prevents using-it as an isolated bulk latency sample.--Queued follow-up work for a removed synthetic provider was observed trying-categories after its workflow generation was superseded. Commit fencing rejected-its writes, but the continuing request/fallback work needs investigation in P1.-Superseded workflow ownership should terminate work rather than initiate decoder-or category recovery. Background requests can affect account-level counts and-later process-wide heap/GC samples.--## Artifacts and remaining gates--Local baseline artifacts are in:-`build/xtream-sync-performance/20261009T165800195284Z/`.-The successful refresh smoke check is in:-`build/xtream-sync-performance/20261009T165718649672Z/`.-Raw general logcat and provider credentials are not exported.--Installed APK SHA-256 values for these successful runs:--- App: `852b8b19bb3c108191a7fed204cea19708173ca988e758c054b2a83b74b24307`.-- Instrumentation: `570084179468ca74554398f8d22b9e275f220ddc19f71c71ac511a19079fc06a`.--Builds passed; nine Xtream HTTP tests and thirteen fixture/report tests passed.-Provider accounts were synthetic and the existing debug application was retained.-The comparator notes use a neutral filename and contain no reference app name.--P0 remains open for an actual bulk comparison, representative device/release-measurements, repeated refresh scenarios, row identity/field equivalence,-allocation profiling, precise attempt/coverage diagnostics and UI readiness.-No default, parser, worker-pool, snapshot receipt, or import semantics changed-in this package. P1 correctness work precedes the planned P2–P6 performance-changes. Performance gates are not frozen from this limited environment.diff --git a/docs/XTREAM_SYNC_P0_SCALE_REPORT.md b/docs/XTREAM_SYNC_P0_SCALE_REPORT.mddeleted file mode 100644index 2e4c337e..00000000--- a/docs/XTREAM_SYNC_P0_SCALE_REPORT.md+++ /dev/null@@ -1,269 +0,0 @@-# Xtream sync 50k scale and batch sweep--Status: **Done** for an exploratory synthetic emulator sweep. This does not-close P0 or establish a release performance result.--Measured 2026-10-10 on the API 36 Android TV x86_64 emulator using the isolated-`com.streamvault.app.syncbenchmark` package. Each profile used one warmup and-three measured imports of the same deterministic 50,000-channel, 200-category-fixture (seed 1). The live payload was 12,250,789 bytes with SHA-256-`fb0b72467c66305c3780a9ff1b23fe5d4bd0ad3d8a03b0d34e8082558e02e073`.-Every measured import committed exactly 50,000 rows through one complete live-bulk request and made zero per-category live requests. The API 36 emulator had-a 192 MiB memory class and 201,326,592-byte maximum Java heap. Tier and batch-settings below are benchmark overrides on this one emulator; they do not-represent physical LOW/MID/HIGH devices.--## Results--| Profile | Stage batch / queue | Staged batches | Setup median / max | Live commit median | Max sampled Java heap | Measured GC delta range |-| --- | ---: | ---: | ---: | ---: | ---: | ---: |-| LOW / 100 | 100 / 1 | 500 | 19.446 / 20.781 s | 19.364 s | 13.21 MiB | 431–436 |-| LOW / 256 | 256 / 1 | 196 | 20.339 / 20.817 s | 20.247 s | 13.25 MiB | 367–372 |-| LOW / 512 | 512 / 1 | 114 | 20.175 / 25.303 s | 20.072 s | 13.93 MiB | 321–328 |-| MID / 512 | 512 / 2 | 98 | 18.627 / 23.591 s | 18.544 s | 15.96 MiB | 308–318 |-| HIGH / 500 | 500 / 2 | 100 | 21.030 / 24.338 s | 20.927 s | 14.21 MiB | 311–320 |-| HIGH / 1,024 | 1,024 / 2 | 49 | 24.470 / 24.614 s | 24.357 s | 16.38 MiB | 293–296 |--LOW/256, LOW/512 and HIGH/500 were respectively 4.6%, 3.8% and 8.1% slower-by median setup time than LOW/100. MID/512 was 4.2% faster by median, but its-23.591 s maximum was 13.5% above the LOW/100 maximum and its 15.96 MiB sampled-heap was 20.8% higher. That three-sample, single-emulator median does not-establish a safe improvement. HIGH/1,024 was 25.8% slower by median than-LOW/100 and had a 16.38 MiB sampled peak. Larger batches reduced staging batch-and sampled GC counts, but did not provide a repeatable elapsed-time gain;-several profiles had higher maxima. Sampled heap is process telemetry, not an-allocation profile or device memory-pressure measurement. The one-off 50k-smoke run without warmup took 29.515 s and is excluded from the controlled-comparison as an outlier.--## Matched bulk and category route comparison--The same fixture, emulator build, LOW runtime override and batch size 100 were-also measured using explicit `CATEGORY_BY_CATEGORY` mode (one warmup plus three-measured imports). Both runs used the same payload hash, committed exactly-50,000 rows, completed every live response, and retained full request logs.--| Live route | Live requests per import | Rows per response | Setup median / max | Live commit median | Max sampled Java heap |-| --- | ---: | ---: | ---: | ---: | ---: |-| STREAM_ALL bulk | 1 | 50,000 | 19.446 / 20.781 s | 19.364 s | 13.21 MiB |-| CATEGORY_BY_CATEGORY | 200 | 250 | 25.950 / 28.739 s | 25.878 s | 9.62 MiB |--On this synthetic LOW profile, category mode was 33.5% slower by median setup-time and had a 38.3% higher maximum. It had a 27.2% lower maximum sampled heap.-The request trace showed a maximum of one active server request during category-mode. This supports the bulk route for this healthy, zero-delay fixture, while-also showing the category route's lower sampled heap in this run. It does not-establish behavior for real providers, different category distributions,-throttling, physical devices or release builds. The run order was not-randomized, so treat the comparison as exploratory rather than a frozen release-gate.--### Repeated alternating-order 10k follow-up--To reduce simple run-order bias, the same API 36 emulator and LOW/100 profile-ran three paired blocks against a deterministic 10,000-channel, 100-category-fixture. Each route had one warmup and one measured import per block. Route-order alternated bulk-first, category-first, bulk-first. All reports used the-same payload SHA-256 (`4dfbcaf7e39ce168eb4cd58e34b5d8c78dddf4592d6638cb46c76b0fb31d63a3`),-recorded all expected samples, passed instrumentation, and retained complete-request-event logs. Every measured import committed all 10,000 rows.--| Paired block | Order | STREAM_ALL setup | CATEGORY_BY_CATEGORY setup | Bulk faster in pair |-| --- | --- | ---: | ---: | ---: |-| 1 | Bulk first | 5.482 s | 6.971 s | 21.4% |-| 2 | Category first | 5.181 s | 8.847 s | 41.4% |-| 3 | Bulk first | 4.534 s | 6.709 s | 32.4% |--Across the three measured imports per route, `STREAM_ALL` had a 5.181 s median-and 5.482 s maximum setup time; `CATEGORY_BY_CATEGORY` had a 6.971 s median-and 8.847 s maximum. Bulk was faster in all three pairs. Maximum sampled Java-heap was 11.08 MiB for bulk and 9.93 MiB for category mode. Each bulk import-made one live request; each category import made 100. These samples support a-bulk latency advantage on this specific synthetic fixture, with lower sampled-heap for category mode. The sequence was alternating rather than randomized,-and the category-first block had the slowest category-mode sample; bulk ranged-from 4.534 to 5.482 s. Run-to-run and ordering effects remain plausible. This-exploratory result alone did not justify a production AUTO/default decision or-replace measurements on other fixtures, release builds, physical devices or-real providers. Bulk-first AUTO was subsequently enabled on this branch for-direct testing; the activation and fresh synthetic checks are recorded in the-[P6 tuning report](XTREAM_SYNC_P6_TUNING_REPORT.md).--### Seeded randomized comparisons across simulated tiers--A follow-up used the same 10k/100 fixture, payload hash, API 36 Android TV-x86_64 emulator and isolated benchmark package. We ran three paired blocks per-simulated tier with one warmup and one measured import per route in every-block. Both tier and route order were shuffled with seed `20261010`; each tier-had two bulk-first and one category-first pair. Tier overrides select the-application policy only: these are not physical LOW/MID/HIGH devices. The-profile's default stage batch sizes were LOW/100, MID/300 and HIGH/500. All-reports were complete, instrumentation passed, measured rows were exactly-10,000, hashes matched, and request-event logs were not truncated.--Positive paired advantage means bulk had lower setup time; a negative value-means category mode was faster.--| Run order | Tier / pair | First route | STREAM_ALL setup | CATEGORY_BY_CATEGORY setup | Bulk paired advantage |-| ---: | --- | --- | ---: | ---: | ---: |-| 1 | LOW / 1 | Bulk | 6.308 s | 8.685 s | +27.4% |-| 2 | MID / 1 | Bulk | 5.651 s | 6.269 s | +9.9% |-| 3 | HIGH / 1 | Category | 5.345 s | 5.352 s | +0.1% |-| 4 | LOW / 3 | Bulk | 4.559 s | 6.814 s | +33.1% |-| 5 | MID / 2 | Category | 5.468 s | 6.540 s | +16.4% |-| 6 | MID / 3 | Bulk | 5.499 s | 6.224 s | +11.7% |-| 7 | HIGH / 2 | Bulk | 5.622 s | 5.217 s | -7.8% |-| 8 | HIGH / 3 | Bulk | 4.436 s | 5.042 s | +12.0% |-| 9 | LOW / 2 | Category | 5.756 s | 8.618 s | +33.2% |--| Simulated tier / default batch | Route | Setup median / max | Faster in paired blocks | Max sampled Java heap |-| --- | --- | ---: | ---: | ---: |-| LOW / 100 | STREAM_ALL | 5.756 / 6.308 s | 3 / 3 | 11.71 MiB |-| LOW / 100 | CATEGORY_BY_CATEGORY | 8.618 / 8.685 s | — | 9.66 MiB |-| MID / 300 | STREAM_ALL | 5.499 / 5.651 s | 3 / 3 | 12.19 MiB |-| MID / 300 | CATEGORY_BY_CATEGORY | 6.269 / 6.540 s | — | 13.92 MiB |-| HIGH / 500 | STREAM_ALL | 5.345 / 5.622 s | 2 / 3 | 12.45 MiB |-| HIGH / 500 | CATEGORY_BY_CATEGORY | 5.217 / 5.352 s | — | 21.21 MiB |--Bulk won all six LOW and MID paired blocks. At HIGH, category mode won one-pair and the median route times were close (bulk 5.345 s; category 5.217 s).-Bulk made one live request per import; category mode made 100. The measured-heap direction varied by tier, with the category route's HIGH-profile maximum-the largest sample in this sweep. This matrix suggests the route advantage can-depend on the simulated policy tier and does not support a universal AUTO-choice. All runs used one emulator with the same 192 MiB memory class; results-do not establish behavior on physical devices, release builds or real providers.--The bulk per-run request trace confirms one complete `get_live_streams`-response, zero per-category live requests, and exact row counts. The request-also fetches authentication/category metadata and empty movie/series category-shells. One representative LOW/100 measured run spent 14.2 s in the live HTTP-response and 19.8 s in the instrumented streaming callback; these overlap with-decode, mapping, and staging and must not be summed as separate wall-time-costs. The pipeline trace records substantial producer send-wait, but this-sweep alone does not isolate a safe optimization target.--## Persisted row and field equivalence--The benchmark now has an opt-in `--verify-channel-fields` pass. After setup-timing stops, it walks Room in 1,024-row pages and checks fixture-derived source-order, stream IDs, names, category IDs and the row fallback category name, EPG-IDs, archive support/duration, provider/adult/protection fields, logical group-IDs, internal URL tokens, and required local/fingerprint fields. It separately-checks the persisted category table against the category-list names. The channel-rows intentionally omit `category_name`, so their expected row value is the-existing `Category N` fallback; the authoritative `Benchmark Group NNNN`-values are verified in category records.--| Route / fixture | Persisted rows checked | Category records checked | Verification time (outside setup timing) | Result |-| --- | ---: | ---: | ---: | --- |-| STREAM_ALL / 50k | 50,000 | 200 | 10.883 s | Pass |-| CATEGORY_BY_CATEGORY / 50k | 50,000 | 200 | 14.756 s | Pass |-| STREAM_ALL / 103 rows, every tenth malformed | 93 | 12 | 0.038 s | Pass |-| STREAM_ALL / 10k initial + hidden 20% refresh | 10,000 after each phase | 100 after each phase | 2.581 / 2.464 s | Pass |-| CATEGORY_BY_CATEGORY / 10k initial + hidden 20% refresh | 10,000 after each phase | 100 after each phase | 2.750 / 2.595 s | Pass |-| STREAM_ALL / HTTP 503 then category fallback | 10,000 | 100 | 2.693 s initial / 3.449 s follow-up | Fields pass; follow-up settled Partial with no post-fallback bulk retry |-| STREAM_ALL / truncated body then category fallback | 1,000 | 20 | 0.293 s | Fields pass; final state Partial |--Each 50k route check was one no-warmup correctness run, not a timing sample. The-bulk run made one complete live request; the category run made 200 complete-category requests. All live response rows summed to 50,000 and request-event-logs were not truncated. The malformed smoke confirms the checker skips the-fixture's invalid stream-ID rows and covers the remaining 93 persisted rows.-The 10k refresh probe hid 20% of categories before the Settings-style live-refresh; both phases retained all expected rows and categories, and the verifier-matched every row after refresh. Each phase made one complete bulk request and-zero category-stream requests. This is one synthetic correctness sample per-phase, not refresh performance evidence.--The explicit category-mode refresh retained the same 10,000 rows and 100-category records after hiding 20% of categories; fixture comparison passed-after both setup and refresh. It made 100 category requests for setup and 80-visible-category requests for refresh. The original 10k HTTP 503 run retried-the bulk endpoint, then completed all 100 category responses and verified every-persisted field, but its state snapshot was `Syncing` and three later bulk-requests followed the fallback. This exposed a queued onboarding recovery that-could rerun completed primary work when fallback left the overall sync-`PARTIAL`.--After updating `resumePrimaryCatalog` to coalesce a queued initial-onboarding-resume when onboarding completed and the durable live snapshot is fresh and-complete, a follow-up 10k HTTP 503 run passed instrumentation and verified all-10,000 rows and 100 categories. It made three bulk attempts, all HTTP 503,-followed by 100 successful category requests; there were zero bulk requests-after fallback. The sampled sync state was `Partial`, and logcat recorded-`Xtream primary resume coalesced ... onboarding completed while queued.` The-request trace was complete. Setup took 17.841 s and the post-setup field check-took 3.449 s; this is one emulator verification run, not evidence for other-failed-response shapes. The 1k truncated-body run made four-incomplete 500-row bulk attempts, completed 20 category responses, and verified-all 1,000 persisted fields; its state snapshot was `Partial`. It has not been-rerun after the coalescing change.--## Decision and limits--Follow-up on 2026-10-10: the corrected bulk-first truncated-response scenario-and an HTTP 503 scenario with VOD/series fallback now pass a 30-second terminal-state/count observation with zero bulk Live requests after category fallback.-See [failure handling and continuation queues](XTREAM_SYNC_FAILURE_HARDENING.md).-This closes that bounded truncated-response observation; other failures and-longer retry windows remain open. The earlier evidence below stays historical.--- **Done:** Synthetic 50k-row scale smoke and six-profile batch-size comparison;- all measured samples completed with exact fixture counts.-- **No default change:** Existing tier-specific production batch defaults stay- unchanged. The larger candidates did not show a repeatable end-to-end gain.-- **Done:** Three paired, alternating-order synthetic LOW/100 comparisons and- three seeded randomized pairs per simulated LOW/MID/HIGH policy at 10k rows.- Bulk won all LOW/MID pairs; HIGH was mixed and close by median. The separate- 50k comparison also favored bulk by median.-- **Done:** All-row field equivalence for both initial-import routes on the- 50k fixture, a malformed-row smoke check, and a 10k hidden-category refresh- check on both live routes, plus field checks after 503 and truncated-body- category fallback.-- **Still open:** Route comparisons across other fixture/provider profiles;- terminal-state/retry-quiescence behavior for truncated-body and other failure- paths; broader refresh/failure cases; attributable- allocation/CPU profiling; release-build and representative device- measurements; finalized P0 gates.-- **Deferred:** Physical LOW/MID/HIGH tuning and real-provider/playback checks.- No physical devices are available. The synthetic fixture has no playable- media; a branch debug APK is now installed for the user to run against their- provider, but that validation has not yet been performed.--Raw local reports (ignored build artifacts):--- `build/xtream-sync-performance/20261010T140737945520Z/report.json`-- `build/xtream-sync-performance/20261010T140737945520Z/requests.jsonl`-- `build/xtream-sync-performance/p0-scale-50k-low-batch100-3x1/report.json`-- `build/xtream-sync-performance/p0-scale-50k-low-batch256-3x1/report.json`-- `build/xtream-sync-performance/p0-scale-50k-low-batch512-3x1/report.json`-- `build/xtream-sync-performance/p0-scale-50k-mid-batch512-3x1/report.json`-- `build/xtream-sync-performance/p0-scale-50k-high-batch500-3x1/report.json`-- `build/xtream-sync-performance/p0-scale-50k-high-batch1024-3x1/report.json`-- `build/xtream-sync-performance/p0-scale-50k-low-category-3x1/report.json`-- `build/xtream-sync-performance/p0-field-equivalence-50k-verified/report.json`-- `build/xtream-sync-performance/p0-field-equivalence-50k-category-verified/report.json`-- `build/xtream-sync-performance/p0-field-equivalence-malformed-103/report.json`-- `build/xtream-sync-performance/p0-field-equivalence-10k-hidden-refresh/report.json`-- `build/xtream-sync-performance/p0-field-equivalence-10k-category-hidden-refresh/report.json`-- `build/xtream-sync-performance/p0-field-equivalence-10k-bulk-503-fallback/report.json`-- `build/xtream-sync-performance/p0-field-equivalence-1k-partial-disconnect-fallback/report.json`-- `build/xtream-sync-performance/p0-route-pair1-bulkfirst/report.json`-- `build/xtream-sync-performance/p0-route-pair2-categoryfirst/report.json`-- `build/xtream-sync-performance/p0-route-pair3-bulkfirst/report.json`-- `build/xtream-sync-performance/p0-route-randomized-LOW-pair1-bulkfirst/report.json`-- `build/xtream-sync-performance/p0-route-randomized-LOW-pair2-categoryfirst/report.json`-- `build/xtream-sync-performance/p0-route-randomized-LOW-pair3-bulkfirst/report.json`-- `build/xtream-sync-performance/p0-route-randomized-MID-pair1-bulkfirst/report.json`-- `build/xtream-sync-performance/p0-route-randomized-MID-pair2-categoryfirst/report.json`-- `build/xtream-sync-performance/p0-route-randomized-MID-pair3-bulkfirst/report.json`-- `build/xtream-sync-performance/p0-route-randomized-HIGH-pair1-categoryfirst/report.json`-- `build/xtream-sync-performance/p0-route-randomized-HIGH-pair2-bulkfirst/report.json`-- `build/xtream-sync-performance/p0-route-randomized-HIGH-pair3-bulkfirst/report.json`--Reproduction uses the commands documented in-[`XTREAM_SYNC_BENCHMARK.md`](XTREAM_SYNC_BENCHMARK.md), with-`--channels 50000 --categories 200 --modes STREAM_ALL --iterations 3---warmups 1` and the recorded tier/batch overrides.diff --git a/docs/XTREAM_SYNC_P6_TUNING_REPORT.md b/docs/XTREAM_SYNC_P6_TUNING_REPORT.mddeleted file mode 100644index d6657c7e..00000000--- a/docs/XTREAM_SYNC_P6_TUNING_REPORT.md+++ /dev/null@@ -1,238 +0,0 @@-# P6 live strategy and tuning report--Status: bulk-first AUTO is enabled in normal app profiles on this branch for-direct testing. Stage-batch defaults remain unchanged. Real-provider and-physical-device acceptance for P6 remain open.--| State | Work |-| --- | --- |-| Done | Bulk-first AUTO policy, hidden-category routing, progress changes, and the synthetic 10k-row matrix across batch sizes and policy overrides |-| Done | Synthetic setup-to-first-browsable-row timing through the real Welcome-to-Live screen on API 36 emulator |-| Done | No-ID stale `ProviderSyncWorker` refresh through WorkManager with catalog and metadata assertions |-| Done | Fresh APK emulator check: 10k-channel AUTO bulk success and 503-to-category fallback with full field verification |-| Done | Normal app debug APK installed and launched on the API 36 x86_64 emulator with app data preserved |-| Done | Successful new-provider completion now routes all setup protocols to Home; edited providers retain their prior return behavior |-| Deferred | Physical LOW/MID/HIGH-device acceptance; no physical devices are available |-| Pending | User real-provider compatibility and sustained-playback run, release-device comparison, and release rollout evidence |--Date: 2026-10-10-Branch: `codex/xtream-live-sync-performance`--## Implementation exercised--- Normal app packages now use bulk-first AUTO by default. The isolated- `com.streamvault.app.syncbenchmark` package can opt into this policy for the- benchmark run or retain the previous policy for comparison.-- Bulk-first AUTO tests remembered category stress independently from- bulk failure, honors an active full-catalog cooldown, and considers known- hidden-category coverage. With at least 60% of known live channels hidden, it- avoids downloading a full list for a selected-category refresh.-- Bulk results are filtered before staging for hidden categories, while- previously committed hidden rows and required hidden rows are retained.-- Add Provider and Settings Live refresh use the same live strategy. Progress- labels now distinguish loading, saving/committing, and committed Live TV.- Committed row counts are reported after catalog promotion.-- Newly added Xtream providers use the bulk-first strategy when live sync is- left at the default `AUTO` mode.-- Explicit category mode and bulk-failure fallback remain available.--## Branch activation and fresh-build verification (2026-10-10)--The normal debug APK was built from this branch and verified as-`com.streamvault.app.debug`, version `1.0.19-debug` (version code 21). It was-built with `-PcompatAbi=x86_64`; package inspection confirmed native ABIs-`arm64-v8a`, `armeabi-v7a`, and `x86_64`. The saved APK is-`build/xtream-sync-performance/streamvault-bulk-first-debug.apk`. It was-installed on `emulator-5554` with `adb install -r --no-streaming`, preserving-app data; `pm path` confirmed the installed package, and-`monkey -p com.streamvault.app.debug 1` launched it successfully. This is the-branch's ordinary debug app, not the isolated benchmark package or a Play Store-release. It is ready for the user to enter a real provider. No real-provider-credentials or provider requests were used in this validation.--The focused `XtreamLiveSyncPolicyTest` and `CatalogSyncRuntimeProfileTest`-passed, including the normal-package bulk-first default. The isolated benchmark-app and test APKs were then rebuilt, installed without clearing app data, and-rerun against the deterministic local fixture using AUTO with the LOW tier-profile simulated on the API 36 Android TV emulator (192 MB memory class).-Existing per-tier stage-batch sizes were kept.--The provider-completion navigation follow-up uses the shared setup route, so-Xtream, M3U, Stalker, Jellyfin, QR pairing, and backup import all send a newly-created provider to Home. Editing an existing provider still returns to its-launching screen. `ProviderGraphNavigationTest` covers the add-versus-edit-navigation rule. The ordinary debug APK was rebuilt and reinstalled after this-change; the install preserved app data. Real-provider behavior has not yet been-tested.--Build and launch the ordinary branch APK with:--```powershell-.\gradlew.bat :app:assembleDebug -PcompatAbi=x86_64 --console=plain-New-Item -ItemType Directory -Force build/xtream-sync-performance | Out-Null-Copy-Item app/build/outputs/apk/debug/app-debug.apk build/xtream-sync-performance/streamvault-bulk-first-debug.apk -Force-adb -s emulator-5554 install -r --no-streaming build/xtream-sync-performance/streamvault-bulk-first-debug.apk-adb -s emulator-5554 shell monkey -p com.streamvault.app.debug 1-```--| Scenario | State | Coverage | Live requests | Setup elapsed |-| --- | --- | --- | --- | ---: |-| Bulk succeeds | Success | 10,000/10,000 channels and all fixture fields verified; 100 categories | 1 bulk, 0 category | 7.00 s ([report](../build/xtream-sync-performance/20261010T142614124918Z/report.json)) |-| Bulk HTTP 503, then fallback | Partial after complete live fallback | 10,000/10,000 channels and all fixture fields verified; 100 categories | 3 bulk attempts (503), 100 category successes, no post-fallback bulk retries | 16.77 s ([report](../build/xtream-sync-performance/20261010T142632162841Z/report.json)) |--Both runs completed instrumentation successfully. The second run also logged-that queued onboarding recovery was coalesced after the category fallback.-These are single-run synthetic diagnostics, not a performance comparison or a-real-provider/playback acceptance result. The fixture contains no playable-media; sustained playback validation is still deferred.--## Benchmark setup--The isolated debug and Android test APKs were built with:--```powershell-.\gradlew.bat :app:assembleDebug :app:assembleDebugAndroidTest `- -PxtreamSyncBenchmark=true -PcompatAbi=x86_64-```--The generated application IDs were `com.streamvault.app.syncbenchmark` and-`com.streamvault.app.syncbenchmark.test`. The APKs were installed with-`adb install -r --no-streaming`; application data was not cleared. The device-was the API 36 Android TV emulator (`sdk_google_atv64_x86_64`), with a 192 MB-memory class and a 192 MiB maximum Java heap. All measurements used the debug-benchmark package, a local synthetic provider, 10,000 channels, 100 categories,-and the same 2,426,989-byte fixture payload (`4dfbcaf7…31d63a3`). The fixture-contains no playable media.--Each table row below has one warm-up and five measured setup/refresh pairs.-Request counts are per synthetic account and include both setup and Settings-refresh. Timings cover backend setup or refresh completion; they do not measure-the first usable screen. Java heap is sampled by instrumentation and excludes-native RSS.--## Stage batch exploration--These runs used explicit `STREAM_ALL`. Tier names are policy overrides on one-emulator, not measurements from physical LOW/MID/HIGH devices.--| Tier override | Batch rows | Add Provider median / max (ms) | Settings refresh median / max (ms) | Max sampled Java heap (MB) | Evidence |-| --- | ---: | ---: | ---: | ---: | --- |-| LOW | 100 | 5,726 / 5,777 | 5,541 / 5,657 | 11.3 | [report](../build/xtream-sync-performance/20261010T093957897893Z/report.json) |-| LOW | 128 | 5,518 / 5,529 | 5,223 / 5,393 | 11.6 | [report](../build/xtream-sync-performance/20261010T094107248725Z/report.json) |-| LOW | 256 | 5,255 / 5,446 | 5,092 / 5,137 | 11.6 | [report](../build/xtream-sync-performance/20261010T094217729971Z/report.json) |-| MID | 300 | 5,279 / 5,317 | 5,057 / 5,121 | 12.7 | [report](../build/xtream-sync-performance/20261010T094326043505Z/report.json) |-| MID | 512 | 5,156 / 5,311 | 4,985 / 5,037 | 11.9 | [report](../build/xtream-sync-performance/20261010T094434065503Z/report.json) |-| HIGH | 500 | 4,964 / 5,424 | 4,896 / 5,021 | 13.9 | [report](../build/xtream-sync-performance/20261010T094540490695Z/report.json) |-| HIGH | 1,024 | 3,877 / 3,987 | 3,656 / 3,776 | 12.9 | [report](../build/xtream-sync-performance/20261010T094643512690Z/report.json) |--Every measured operation retained all 10,000 channels and used two bulk live-requests per account, with no category requests. Larger batches were faster in-these sequential runs. The emulator, run order, and synthetic provider limit-that observation; no production batch size is promoted from this result.--## Candidate AUTO and behavior checks--| Scenario | Tier / batch | Add Provider median (ms) | Settings refresh median (ms) | Live requests per account | Evidence |-| --- | --- | ---: | ---: | --- | --- |-| Candidate AUTO | LOW / 256 | 5,043 | 4,932 | 2 bulk, 0 category | [report](../build/xtream-sync-performance/20261010T094742058234Z/report.json) |-| Candidate AUTO | MID / 512 | 5,200 | 4,945 | 2 bulk, 0 category | [report](../build/xtream-sync-performance/20261010T094841875839Z/report.json) |-| Candidate AUTO | HIGH / 1,024 | 5,159 | 4,911 | 2 bulk, 0 category | [report](../build/xtream-sync-performance/20261010T094948164463Z/report.json) |-| 80% hidden before refresh | LOW / 256 | 3,856 | 2,263 | 1 bulk, 20 category | [report](../build/xtream-sync-performance/20261010T095100069509Z/report.json) |-| 80% hidden before refresh | MID / 512 | 3,833 | 1,983 | 1 bulk, 20 category | [report](../build/xtream-sync-performance/20261010T095141776371Z/report.json) |-| 80% hidden before refresh | HIGH / 1,024 | 5,114 | 2,506 | 1 bulk, 20 category | [report](../build/xtream-sync-performance/20261010T095221680576Z/report.json) |-| Remembered category stress | HIGH / 1,024 | 3,663 | 3,516 | 2 bulk, 0 category | [report](../build/xtream-sync-performance/20261010T095319396060Z/report.json) |-| Full-catalog cooldown active | HIGH / 1,024 | 5,053 | 4,676 | 1 bulk, 100 category | [report](../build/xtream-sync-performance/20261010T095408941106Z/report.json) |--Every operation in these groups recorded the expected 10,000-channel count.-The hidden-category runs retained hidden rows while using the 20 visible-categories for the Settings refresh. Remembered category stress did not force-the candidate into category mode. An active bulk cooldown did select category-mode for refresh.--### Bulk HTTP 503 fallback--The 10,000-channel HIGH candidate run with bulk HTTP 503 completed all sample-iterations and preserved the 10,000-row count. Per account, instrumentation-recorded six bulk attempts and 200 category requests across setup and refresh;-the initial phase retried/recovered through category requests, and the active-cooldown kept refresh on categories. The resulting sync state was `Partial`-because the failed bulk attempt remained a warning, despite complete row-count-assertions. Treat this as evidence of data retention and fallback execution,-not a clean-success status.--[Bulk 503 report](../build/xtream-sync-performance/20261010T095515495918Z/report.json)--All reports have `complete=true`, `request_events_truncated=false`, and five-measured samples per phase. The benchmark runner checked instrumentation exit-status and exact row counts. These checks establish the synthetic backend path;-they do not establish provider compatibility or production-device readiness.--## Invalid preliminary batch--The first set of batch measurements ran before the newly built isolated APK was-installed, so its runtime tier and batch overrides were not active. Reports-from `20261010T092817951398Z` through `20261010T093826139108Z` were discarded-and are not used in the tables. The APK was then installed without a data wipe,-and a smoke run confirmed the HIGH candidate settings and two-request route-before collecting the reported measurements.--## Synthetic first-browsable-screen check--The opt-in UI probe launched the isolated app on Welcome, ran the production-`ValidateAndAddProvider.loginXtream` use case against the local fixture, and-waited for the first channel row to become accessible in Live TV. It temporarily-hid empty virtual Favorites and Recent categories so the initial selection was-All Channels, then restored the prior landing and category preferences. This-drives the real navigation and screen but does not interact with the provider-form.--| Fixture / device | Runs | Setup median / max | First browsable row median / max | Channels retained |-| --- | ---: | ---: | ---: | ---: |-| 10,000 live rows / 100 categories; API 36 Android TV emulator; DEVICE policy | 1 warmup + 5 measured | 5.71 / 5.77 s | 6.71 / 6.87 s | 10,000 / 10,000 |--The run peaked at 36,060,832 sampled Java-heap bytes, observed at most two-simultaneous synthetic HTTP requests, recorded all expected samples, and had no-truncated request events. The setup median is backend setup completion; the-first-row median includes navigation and screen readiness. These are debug-emulator measurements, not a physical-device or release-build comparison, and-do not validate media playback.--[First-browsable report](../build/xtream-sync-performance/20261010T113111995992Z/report.json)--## Synthetic background-worker check--The opt-in `--background-worker` probe created one active synthetic provider,-set only its `lastLiveSuccess` metadata stale, and enqueued an actual-no-provider-ID `ProviderSyncWorker` request through WorkManager. This exercises-the provider-enumeration stale-refresh branch used by periodic and launch-stale-work. It waited for the work's terminal state, required `SUCCEEDED`, checked-that all 10,000 channels remained, and required `lastLiveSuccess` to advance.--| Fixture / device | Runs | Worker median / max | Work state | Channels retained |-| --- | ---: | ---: | --- | ---: |-| 10,000 live rows / 100 categories; API 36 Android TV emulator; DEVICE policy | 1 warmup + 1 measured | 5.80 / 5.80 s | SUCCEEDED for both | 10,000 / 10,000 |--The measured synthetic account made two bulk live-list requests (initial setup-and worker refresh), no category-scoped live-list requests, and the fixture-recorded no truncated request events. This validates the worker execution path-and catalog preservation on the debug emulator; it does not validate WorkManager-six-hour scheduling constraints, real-provider behavior, physical devices, or-playback.--[Background-worker report](../build/xtream-sync-performance/20261010T113351914960Z/report.json)--## Direct-test status and release gate--The exploratory data does not meet the P6 release gate. It is from one debug-emulator with simulated policy tiers and a synthetic provider. Bulk-first AUTO-is active in normal app packages on this branch for direct testing.-An opt-in-setup-to-first-browsable-row check now exercises the real Welcome-to-Live UI on-that emulator, but physical LOW, MID, and HIGH device measurements,-release-build memory and first-screen readiness comparison, the user's-real-provider compatibility run, and WorkManager scheduling-constraint-validation remain open. The required two-channel sustained-playback validation also remains open: the fixture has no media, and no real-provider has yet been tested. Follow the repository live-TV validation-instructions for that playback run. Stage-batch defaults stay unchanged pending-broader device evidence.diff --git a/docs/XTREAM_SYNC_P7_IMPLEMENTATION.md b/docs/XTREAM_SYNC_P7_IMPLEMENTATION.mddeleted file mode 100644index acbe9f00..00000000--- a/docs/XTREAM_SYNC_P7_IMPLEMENTATION.md+++ /dev/null@@ -1,241 +0,0 @@-# P7 Xtream summary and background work--Status: P7 implementation, the synthetic emulator matrix, the pre-change-unchanged-refresh comparison, and the fingerprint-allocation follow-up are-complete. Physical-device tuning is deferred; full release validation remains-pending.--| Work item | Status | Evidence / remaining |-| --- | --- | --- |-| P7 implementation | Done | Summary diffing/fingerprints, local and hydrated state preservation, checkpointed tier slices, catalog-before-guide scheduling, focused tests, and APK builds |-| Small-catalog bulk-fallback tier sweep | Done | 2,000 movies / 1,000 series; LOW, MID, HIGH, and DEVICE profiles; five measured runs per profile |-| Bulk-success and larger-catalog comparisons | Done | 2k/1k DEVICE bulk success (five runs), 8k/4k DEVICE bulk success (three runs), and 8k/4k LOW bulk fallback (two runs) |-| Emulator Room preservation check | Done | Each run's warmup refreshed stale titles while retaining local IDs, hydrated fields, watch history, protection flags, playback metadata, and hydrated index timestamps |-| Fingerprint allocation follow-up | Done | Replaced per-byte formatter and per-field ByteBuffer allocations without changing digest bytes; sampled unchanged-refresh heap fell on both tested routes |-| Physical-device tuning | Deferred | No physical devices are available |-| Before/after unchanged VOD refresh comparison | Done | Ten measured bulk-success runs and five measured fallback runs per build on the same API 36 emulator; bulk success was about 60% faster, category fallback was effectively unchanged, and sampled Java heap increased |-| P8 end-to-end release validation | Pending | Real-provider validation and sustained live playback remain outstanding |--Date: 2026-10-10-Branch: `codex/xtream-live-sync-performance`--## Summary indexing--The existing summary executor continues to stream full movie/series responses-first and fall back to category work when full streaming fails or a priority-category is requested. Category work now receives a device-tier slice budget:--| Tier | Categories per slice | Target rows | Target duration |-| --- | ---: | ---: | ---: |-| LOW | 4 | 1,000 | 10 s |-| MID | 8 | 3,000 | 20 s |-| HIGH | 16 | 8,000 | 30 s |--The executor checkpoints `nextCategoryIndex` after each completed category and-schedules continuation work when categories remain. A fetch is atomic at the-category boundary, so one unusually large or slow category can exceed its row-or time target before the next checkpoint. The budgets are conservative initial-values, not measured production tuning.--Summary persistence computes stable remote-field fingerprints, compares-existing movie/series rows, and writes only changed summaries. Index projections-are compared without the changing `indexedAt` field, so unchanged refreshes do-not rewrite the same index rows. Existing local IDs, movie watch state,-protection, TMDB identity, hydrated detail fields and local playback metadata-are preserved. The summary fingerprint excludes local watch, protection,-hydration and playback-metadata state.--## Scheduling and guide handoff--Xtream movie and series indexing continuations are scheduled before guide work.-Guide work uses a separate unique WorkManager chain and defers while any Xtream-LIVE, MOVIE or SERIES index job is queued or running. This keeps guide retries-from occupying the provider catalog continuation chain. Settings can continue-to report the durable live/movie/series index state separately from EPG state.--## Verification completed--- `XtreamIncrementalIndexExecutorTest`: row and duration budget checkpoint- coverage passed.-- `XtreamSummaryFingerprintTest`: remote summary changes affect fingerprints;- local watch, hydration, protection and playback-metadata changes do not.-- `ProviderContinuationSchedulerTest`: catalog continuations precede guide- work.-- Focused `SyncManagerTest` passed all 98 tests, including changed-row and- index-projection cases. `SyncManagerXtreamLiveStrategyTest` also passed.-- The app and benchmark debug APKs assembled successfully with the new worker- interfaces and instrumentation sources.-- The synthetic performance fixture now supports deterministic movie and- series summaries, independent category counts and payload hashes, and- configurable bulk VOD/series rejection with category fallback.-- Fixture and report tests passed: `python -m unittest- tools.tests.test_xtream_sync_perf_fixture- tools.tests.test_xtream_sync_benchmark` (13 tests).-- The API 36 Android TV emulator completed a LOW-tier scenario with 1,000 live- channels, 2,000 movies across 20 categories, and 1,000 series across 10- categories. Bulk movie and series requests returned 503, then category- fallback completed all sections. One warmup plus five measured runs were- recorded; all six instrumentation samples completed and request events were- not truncated.-- On each measured run, live import committed 1,000 rows, movie and series- jobs ended in `SUCCESS`, and both Room entities and active index projections- matched the expected 2,000 movie / 1,000 series counts. Median index- completion was 8.593 s for movies and 8.594 s for series from setup start;- median completion after Live TV commit was 7.930 s and 7.931 s respectively.- Each measured account used 1 bulk plus 20 category movie requests, and 1 bulk- plus 10 category series requests.-- The warmup Room check deliberately seeded an old title, hydrated detail,- protection state, playback metadata, and playback-history progress, then- forced both summary sections to reindex. The remote titles refreshed while- stable IDs and local/hydrated fields remained intact. Both Xtream content- index rows retained the hydrated timestamp. This check does not use playable- media.-- The harness sampled Java heap and ART GC during summary indexing; aggregate- maxima across all profiles and catalog sizes are recorded below.--## Emulator matrix results--All runs used the API 36 Android TV x86_64 emulator (192 MB memory class,-201,326,592-byte Java max heap), synthetic data, and a stage batch override of-256. LOW/MID/HIGH are simulated policy budgets on that same emulator. Times are-from setup start; the after-Live column subtracts the recorded Live commit-milestone. Each report completed every expected instrumentation sample without-truncated request events. Every measured sample reached `SUCCESS` for both-summary jobs and had Room row counts matching its fixture. Each configured-warmup reported `room_preservation_verified=true`.--Small catalog, category fallback (one bulk request rejected with 503, then one-request per category):--| Profile | Measured runs | Movie median (s) | Movie after Live (s) | Series median (s) | Series after Live (s) | Max sampled summary heap (MB) | Max GC delta |-| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |-| LOW | 5 | 8.593 | 7.930 | 8.594 | 7.931 | 12.78 | 35 |-| DEVICE | 5 | 7.961 | 7.507 | 7.963 | 7.509 | 10.70 | 35 |-| MID | 5 | 7.946 | 7.500 | 7.947 | 7.502 | 11.29 | 34 |-| HIGH | 5 | 7.961 | 7.509 | 7.962 | 7.510 | 10.02 | 32 |--Bulk-success and larger-catalog comparisons:--| Scenario | Measured runs | Movies / series | Movie median (s) | Series median (s) | Requests per measured sample (movie / series) |-| --- | ---: | ---: | ---: | ---: | --- |-| DEVICE, bulk success | 5 | 2,000 / 1,000 | 1.856 | 1.857 | 1 full + 0 category / 1 full + 0 category |-| DEVICE, bulk success | 3 | 8,000 / 4,000 | 5.241 | 5.243 | 1 full + 0 category / 1 full + 0 category |-| LOW, category fallback | 2 | 8,000 / 4,000 | 30.596 | 30.598 | 1 rejected full + 80 category / 1 rejected full + 40 category |--For the small fixture, the synthetic bulk-success path completed sooner than-fallback: about 1.86 s versus 7.95–8.59 s across the tested fallback profiles.-For the larger fixture, LOW-tier fallback completed all rows and checkpoints-in about 30.6 s. These are path and policy observations on one debug emulator;-they are not a before/after optimization result or production-device targets.-The largest measured summary heap sample was 12.89 MB, and the largest ART GC-count delta was 148 in the 8k/4k LOW fallback run. Heap sampling was every 50 ms-and does not include native RSS or allocation attribution.--## Pre-change comparison: unchanged VOD refresh--The probe first imports one deterministic catalog and waits for successful-movie/series jobs. It then invokes the existing forced summary-index command-once for movies and once for series, sequentially, without changing the fixture-or local rows. The reported combined time is the per-sample sum of those two-calls; it excludes setup, authentication and live import. Each sample verifies-the movie/series Room row counts and active search-index counts afterward.--Both builds used the API 36 Android TV x86_64 emulator (192 MB memory class,-201,326,592-byte Java max heap), LOW policy and 100-row stage batches. The-pre-change build is commit `2af03f5149e888d25307457d4cce82fab3de74d9`; P7 was-built from the same base commit plus the current uncommitted working-tree-changes. Each run used one warmup and five measured accounts, the same seed,-the same 1,000-channel / 2,000-movie / 1,000-series fixture, identical movie-and series payload hashes, and successful instrumentation. Bulk success used-three warmups and ten measured accounts per build. Category fallback used one-warmup and five measured accounts per build. All samples completed; medians-below exclude the warmups. Bulk success returned HTTP 200. Fallback returned-HTTP 503 for both full summary requests, then served the categories.--| Route | Build | Movie refresh median (s) | Series refresh median (s) | Sequential VOD median (s) | Max sampled heap (MiB) | Max ART GC delta |-| --- | --- | ---: | ---: | ---: | ---: | ---: |-| Bulk success, 10 measured | Pre-P7 | 0.886 | 0.883 | 1.769 | 10.09 | 23 |-| Bulk success, 10 measured | P7 | 0.478 | 0.234 | 0.713 | 17.19 | 24 |-| Category fallback, 5 measured | Pre-P7 | 5.232 | 2.688 | 7.906 | 9.01 | 21 |-| Category fallback, 5 measured | P7 | 5.212 | 2.628 | 7.836 | 10.83 | 31 |--On bulk success, the unchanged sequential refresh median fell by 59.69% (2.48x-faster). The full ten-sample series is retained because baseline refresh times-settled during the measured run even after three warmups; no measured samples-were trimmed. Category fallback fell by 0.89%, which is effectively unchanged-at this sample size and should not be presented as a fallback speedup. Request-counts matched between builds: bulk success used two full movie and two full-series requests per account; fallback used two rejected full requests plus 40-movie-category and 20 series-category requests per account. Those totals cover-initial indexing plus the explicit repeated refresh.--The refresh-path maximum sampled Java heap rose from 10.09 to 17.19 MiB on bulk-success and from 9.01 to 10.83 MiB on fallback; maximum ART GC deltas were 24-and 31 for P7. This is an observed emulator memory tradeoff to carry into-physical-device tuning. Java heap is sampled every 50 ms and is not native RSS-or allocation attribution. These results support a route-specific bulk-refresh-gain, not a general VOD speedup claim or a release-device conclusion.--All four reports show successful instrumentation, complete request events and-exact Room/index coverage. The P7 working-tree build is identified by app APK-SHA-256 `FA643853B4CA8008F3FB68B61A7C7D1EC41D76B21145AF7D6022D8F296FA07E7`;-the pre-change app APK is `29E1238BEE4AFAF70CE161A18296AD0AF55E32574BF094413646DF9B468438C9`.-The baseline probe source is retained in the temporary baseline checkout at-`build/xtream-sync-p7-baseline/app/src/androidTest/java/com/streamvault/app/benchmark/XtreamLiveSyncBenchmarkTest.kt`.--## Fingerprint allocation follow-up--Inspection of `XtreamSummaryFingerprint` found repeated allocation in the hot-path: each non-null field created a `ByteBuffer` for its four-byte length-prefix, and every output digest byte called `String.format`. The implementation-now writes the same big-endian length prefix directly and encodes the digest-with a fixed lowercase hexadecimal lookup table. Field order, null markers,-UTF-8 field bytes, SHA-256, and persisted fingerprint values remain unchanged.--The optimized build was compared with the recorded P7 build using the same API-36 Android TV x86_64 emulator, LOW policy, 100-row stage batch, seed, and-2,000-movie / 1,000-series payload hashes. Bulk success used three warmups and-ten measured runs; fallback used one warmup and five measured runs. All-instrumentation samples completed, request events were not truncated, and-Room plus active-index counts matched the fixture.--| Route | Build | Movie median (s) | Series median (s) | Sequential VOD median (s) | Max sampled heap (MiB) | Max ART GC delta |-| --- | --- | ---: | ---: | ---: | ---: | ---: |-| Bulk success, 10 measured | P7 | 0.478 | 0.234 | 0.713 | 17.19 | 24 |-| Bulk success, 10 measured | Fingerprint allocation follow-up | 0.447 | 0.206 | 0.652 | 11.61 | 15 |-| Category fallback, 5 measured | P7 | 5.212 | 2.628 | 7.836 | 10.83 | 31 |-| Category fallback, 5 measured | Fingerprint allocation follow-up | 5.232 | 2.629 | 7.857 | 8.07 | 18 |--The sampled refresh peak fell by 32.4% on bulk success and 25.5% on fallback-relative to P7. Bulk refresh time was 8.5% lower in this follow-up run; the-fallback time was 0.27% higher and remains effectively unchanged. Treat these-time differences as emulator observations, not a new speed claim. Compared-with the pre-P7 build, bulk sampled peak remains 1.52 MiB higher while fallback-is 0.94 MiB lower. Heap is sampled every 50 ms and this does not attribute-allocations or measure native RSS.--The optimized app APK SHA-256 is-`A77C0E63F0172C6C91EE91DEEE57B61C3A6BEEB46821E68196EB8C2B7D18E783`. Reports:--- `build/xtream-sync-performance/p7-post-fingerprint-optimized-bulk-2k-1k-low-10x3/report.json`-- `build/xtream-sync-performance/p7-post-fingerprint-optimized-fallback-2k-1k-low-5x1/report.json`--Local full reports are stored under the following ignored build directories:--- `build/xtream-sync-performance/20261010T111134999266Z/report.json` — LOW fallback.-- `build/xtream-sync-performance/20261010T111449834886Z/report.json` — DEVICE fallback.-- `build/xtream-sync-performance/20261010T111551636742Z/report.json` — MID fallback.-- `build/xtream-sync-performance/20261010T111652926306Z/report.json` — HIGH fallback.-- `build/xtream-sync-performance/20261010T111807126816Z/report.json` — DEVICE bulk success.-- `build/xtream-sync-performance/20261010T111829207899Z/report.json` — 8k/4k DEVICE bulk success.-- `build/xtream-sync-performance/20261010T111935389752Z/report.json` — 8k/4k LOW fallback.-- `build/xtream-sync-performance/p7-pre-change-phase-aligned-bulk-2k-1k-10x3/report.json` — pre-P7 unchanged bulk refresh, ten measured runs.-- `build/xtream-sync-performance/p7-post-change-refresh-bulk-2k-1k-low-10x3/report.json` — P7 unchanged bulk refresh, ten measured runs.-- `build/xtream-sync-performance/p7-pre-change-refresh-fallback-2k-1k/report.json` — pre-P7 unchanged fallback refresh.-- `build/xtream-sync-performance/p7-post-change-refresh-fallback-2k-1k-low/report.json` — P7 unchanged fallback refresh.--These synthetic runs used no real provider or playable media. Physical-device-tuning is deferred because no physical devices are available. The branch debug-APK is now installed for user-side provider testing, but live playback has not-yet been validated. Follow the sustained capture and log requirements in-`AGENTS.md` when recording that run.diff --git a/docs/XTREAM_SYNC_PARSING_IMPLEMENTATION.md b/docs/XTREAM_SYNC_PARSING_IMPLEMENTATION.mddeleted file mode 100644index 40745618..00000000--- a/docs/XTREAM_SYNC_PARSING_IMPLEMENTATION.md+++ /dev/null@@ -1,105 +0,0 @@-# Xtream live parsing and group identity--Implemented after the attempt-isolation package on-`codex/xtream-live-sync-performance`, 2026-10-09.--## Changes--The thin live sync projection now reads tokens directly into its DTO. It skips-unknown fields without building their JSON trees and removes the Gson-tree to-JSON-text to Kotlin-serializer conversion for every row. The existing domain-mapper continues to decide channel admission, category identity, adult flags,-text compatibility, catch-up values, stream URLs and protection defaults.--Retained fields preserve lenient scalar/list behavior, missing/null defaults,-last-key-wins handling, including nested category objects, and text escaping.-The service honors strict unknown-key configuration. Category-list recursion has-an explicit depth limit. Truncated and malformed array syntax is classified as-parsing failure; transport failures and cancellation keep their own semantics.-The legacy decoder remains available through the existing compatibility path.--Group-ID generation now executes the existing canonical-name/key algorithm-directly. It avoids calculating playback resolution, codec, language, source,-transport and variant attributes that sync does not use. Playback classification-continues to calculate those attributes. Frequently used canonical separators-reuse compiled expressions. The group-ID format and canonicalization stay the-same, preserving grouping identity across refreshes and providers.--## Component measurements--API 36 Android TV x86_64 emulator, debug library instrumentation. Each scenario-uses 10,000 synthetic entries, two warmups per method and five measured samples,-alternating method order. Measurements use a monotonic wall clock and Android's-current-thread CPU clock. Every parser sample verifies row count and stream-ID-sum; every group-ID sample verifies the aggregate identity against classification.--| Component | Previous method median CPU | New method median CPU | Previous/new median wall | Previous/new median GC count |-| --- | ---: | ---: | ---: | ---: |-| Core live fields | 322.492 ms | 62.959 ms | 375.706 / 73.299 ms | 36 / 8 |-| Core fields plus ignored metadata | 480.483 ms | 62.703 ms | 534.320 / 69.136 ms | 30 / 4 |-| Group identity for tagged names | 7,138.095 ms | 1,335.489 ms | 8,101.808 / 1,513.209 ms | 505 / 117 |--The parser CPU reduction is about 80% for core fields and 87% with extra-metadata; group-ID CPU falls about 81% for these names. GC counts cover the-whole process and can include other work. These are component measurements,-excluding network, Room, the app graph, promotion and screen readiness. They-cannot establish a total-sync multiplier or release-device performance.--All 30 measured samples completed with matching fingerprints. Report:-`build/xtream-sync-performance/p2-components-20261009T174801Z/report.json`.-The synthetic instrumentation benchmark is-`XtreamLiveComponentBenchmarkTest#compareLiveDecoderAndGroupIdentity`.-It requires an explicit argument so routine correctness suites skip the timed-comparison:--```powershell-.\gradlew.bat :data:connectedDebugAndroidTest '-Pandroid.testInstrumentationRunnerArguments.class=com.streamvault.data.remote.xtream.XtreamLiveComponentBenchmarkTest#compareLiveDecoderAndGroupIdentity' -Pandroid.testInstrumentationRunnerArguments.xtreamLiveComponentBenchmark=true-```--## Correctness and integration--Differential decoder checks compare directly against the previous conversion,-covering every retained field across loose scalar types, nested category IDs,-duplicate keys, escaping and 1,000 deterministic mixed provider rows. Additional-checks cover strict unknown keys and the nesting bound. Group-ID equivalence-covers multilingual, accented, blank, punctuation-only, tagged and quality names-across multiple provider IDs, alongside existing expected-identity checks.--The final integration build passed 207 data and 16 domain tests and built both-isolated benchmark APKs. The instrumentation opt-in guard was also verified:-routine runs skip the component comparison.--Synthetic Add Provider and Settings Live refresh passed in all three requested-modes: six samples, 2,000 saved channels in every sample and successful cleanup.-The STREAM_ALL account issued two bulk requests and no category requests across-its initial/refresh lifecycle; its initial import took 1,137 ms and refresh-1,090 ms. These single samples are smoke evidence, not a performance median.-Report: `build/xtream-sync-performance/20261009T175109203489Z/report.json`.--A larger STREAM_ALL run used 10,000 rows/100 categories, one warmup and five-measured initial/refresh pairs. All 12 samples, including warmups, retained all-10,000 channels and passed cleanup. The completion marker and sample count-matched, instrumentation passed, and request history was not truncated.-Report: `build/xtream-sync-performance/20261009T175359801867Z/report.json`.--| Phase | All measured samples median | Maximum | Measured samples |-| --- | ---: | ---: | ---: |-| Initial import | 4,566.944 ms | 26,110.422 ms | 5 |-| Settings Live refresh | 4,579.747 ms | 27,734.189 ms | 5 |--These groups mix strategies. Two measured accounts used only bulk requests,-with initial/refresh medians of 4,488.678 / 4,566.173 ms (two samples per phase).-The other accounts mixed bulk with category requests. Logs confirmed three-low-memory aborts and one pre-request full-catalog skip; aborted attempts safely-fell back and retained complete counts. Maximum measured sampled Java heap was-15,331,632 bytes, but Android's system-memory signal changed independently.-Request high-water was one: this implementation has no new retrieval overlap.--The payload checksum matches the original 10,000-row baseline. That baseline-ran entirely through categories, so these results do not establish a before/after-bulk speedup or a reliable AUTO time. They demonstrate faster components, a-working bulk path and a remaining source of inconsistent import time.--AUTO strategy, request concurrency and healthy-provider pacing remain governed-by their existing rules. The bounded pipeline and category scheduling packages-follow before the default-strategy release gate.diff --git a/docs/XTREAM_SYNC_PERFORMANCE_REVIEW.md b/docs/XTREAM_SYNC_PERFORMANCE_REVIEW.mddeleted file mode 100644index 3b150a18..00000000--- a/docs/XTREAM_SYNC_PERFORMANCE_REVIEW.md+++ /dev/null@@ -1,221 +0,0 @@-# Xtream sync performance review--Inspected 2026-10-09 at commit `540ec30c`. Scope: adding a provider first,-then Settings sync and the background work that makes the catalog usable.-This is a source inspection, not a measured speedup or an implementation.--Scope clarification: the reported primary delay is the initial Live TV import,-before queued work. The EPG/continuation findings below concern later catalog-availability and do not explain that initial live phase. See-[the live-only import comparison](XTREAM_LIVE_IMPORT_COMPARISON.md) for the-revised priority and concrete reference-code comparison.--## Current execution--ProviderSetupViewModel → ValidateAndAddProvider → ProviderRepositoryImpl:-authenticate, save/stage configuration, run initial onboarding sync.-SyncManager/SyncCoordinator route into XtreamCatalogSyncExecutor.syncFull.--The foreground sequence is:--1. Fetch live categories.-2. Import the complete live lineup, with bulk or category requests; stage batches.-3. Commit live rows and rebuild channel FTS.-4. Fetch and commit movie category shells.-5. Fetch and commit series category shells.-6. Return continuation work for live index backfill, movie summaries, series- summaries, and EPG. Provider setup can finish before movie/series items exist.--ProviderContinuationScheduler enqueues EPG first, then live, movie, and series-index workers. All use `provider-workflow-<id>` with APPEND_OR_REPLACE.-The EPG worker has a 30-second initial delay. Index workers behind it wait for-that delay and guide execution, including any WorkManager retries.--Settings Sync Now performs TV, Movies, Series, EPG section calls in sequence.-Xtream movie/series section calls update category shells and queue indexing;-they do not await the complete item catalog. Settings shares the executors, but-its operation sequence and live policy differ from initial onboarding.-Full refresh/rebuild routes use the full plan, whose non-onboarding live reason-is FOREGROUND; they should not be confused with the Settings TV section route.--## Findings supported by code--### 1. AUTO often deliberately chooses the expensive request topology--`data/.../sync/XtreamLiveSyncPolicy.kt:38` selects category loading for LOW tier,-current low-memory state, hidden categories, remembered stress/full avoidance,-MID onboarding, and MANUAL_SETTINGS/BACKGROUND_STALE.-`CatalogSyncRuntimeProfile.kt` defines LOW as memory class <=192 MB or low-RAM,-MID as <=320 MB. MID onboarding prefers categories and permits at most two-category requests; LOW permits one. HIGH may use bulk.--`XtreamAdaptiveSyncPolicy.kt` adds 250 ms between CATEGORY request starts even-on a healthy provider. For 200 category requests, the healthy start-spacing-floor alone is about 49.75 seconds, before the final request finishes. This is-a theoretical floor from policy, not a recorded provider timing. Concurrency-does not remove this global pacing floor.--`SyncManagerXtreamSupport.executeCategoryRecoveryPlan` processes small windows-with awaitAll before starting the next window. A slow category prevents idle-slots from taking new work. Concurrency is selected initially; the window loop-can downgrade to sequential but does not continuously refill or increase slots.--### 2. Guide scheduling blocks catalog availability--Sources: `ProviderContinuationScheduler.kt:18`, `ProviderWorkScheduling.kt`,-`BackgroundEpgSyncWorker.kt:131`, and `XtreamIndexWorker.enqueue`.-The 30-second EPG delay and serial queue are structural delays in the normal-onboarding continuation path. Their actual contribution to an observed run-still needs timing evidence. EPG SKIP bypasses this part.--This can explain a provider becoming active while movie/series categories stay-empty. First improvement: put catalog indexing before EPG in the existing-durable queue. A later scheduler can prioritize requested categories and guide-availability explicitly, while preserving generation/lease/commit ownership.-Creating independent queues alone would not address the provider-wide lock.--### 3. Streaming still parses every row twice--`remote/xtream/OkHttpXtreamApiService.kt:496` reads each row through Gson's-JsonParser, serializes the resulting tree via element.toString(), and parses-that string with kotlinx.serialization at line 504. This applies to streaming-live, movie, and series arrays. Thin live DTOs reduce retained fields but do-not eliminate the first parse, tree allocation, or second parse.--All streaming callbacks await mapping and DB writes before reading more rows.-This keeps memory bounded, but puts transfer/parse and persistence in sequence.-A bounded producer/consumer pipeline can overlap stages when their costs-justify it; it does not guarantee a win when the provider/network dominates.--### 4. Live import does substantial repeated and additional database work--`SyncCatalogStore.stageChannelBatch:371` enters a fenced transaction, counts-all staged channels for the session, deduplicates the batch, fingerprints it,-and inserts rows. LOW/MID/HIGH batches are only 100/300/500 rows. A 50,000-row-LOW import therefore performs approximately 500 staging transactions and-growing stage-count queries. The cost of those queries needs measurement.--`SyncCatalogStore.applyStagedLiveCatalog:163` applies categories/channels and-rebuilds channel FTS inside the commit transaction. The DAO rebuild is global-to channels_fts, so other providers contribute to its cost too.-Entities declare Fts4 contentEntity links; existing generated release Room code-confirms automatic channel insert/update/delete FTS triggers. This suggests-redundant work, but removing rebuilds requires proving search correctness for-every affected write path and supported DB upgrade path.--`SyncManager.backfillXtreamLiveIndex:2115` later reads every provider channel,-creates a second full list of index entities, deletes its previous Xtream live-index rows, and rewrites them. This also weakens the bounded-memory story of-the earlier streaming stage. Index maintenance could use SQL projection or-bounded changed-row updates during catalog promotion instead.--The live refresh SQL (`CatalogSyncDao.updateChangedChannelsFromStage`) uses a-separate correlated stage lookup for each field of a changed channel. It skips-matching fingerprints, so this primarily matters for changed rows; first-add-timings must be considered separately from refresh timings.--### 5. Movies/series already have a bulk path, with a costly fallback--`XtreamIncrementalIndexExecutor.processSummary` first attempts one full summary-stream for a fresh job. Therefore the whole Xtream engine is not universally-category-by-category. The existing bulk path is worth improving and reusing.--Full summaries use 500-row batches. Each batch reads existing rows, merges-metadata, writes catalog rows, rereads persisted IDs, writes Xtream index rows,-and updates the durable job. The path does not filter unchanged summaries-before writing all merged rows. Rich movie/series details remain separate from-this summary import; background "indexing" includes downloading basic catalog-items, not just constructing a search index.--When full streaming fails, summaries use a sequential category loop and the-worker limits each invocation to two categories (`CATEGORY_SLICE_SIZE = 2`).-Each slice schedules another durable worker. A 200-category fallback requires-about 100 worker invocations, plus the failed bulk attempt. Fresh/full streams-are not limited to two categories.--Large bulk bodies have ceilings: live 96 MiB, movies 80 MiB, series 100 MiB-(plus the configured headroom). A rejected oversized response can send work-into the slower fallback. Preserve limits, but measure whether wire-size caps-remain the right protection for a bounded streaming parser.--### 6. Legacy settings are misleading foundations for optimization--Provider setup and repository onboarding force xtreamFastSyncEnabled=false.-Current syncFull already queues movie/series summaries instead of loading-complete detail catalogs in the foreground. Toggling that legacy flag should-not be assumed to activate a faster onboarding engine.--## Proposed design--Use one catalog ingestion pipeline, with different fetch strategies feeding-it. Preserve existing configuration generations, commit fences, cancellation,-hidden/protected categories, stable IDs, favorites and watch progress.--- Fetch category metadata once per section and reuse it for classification.- Independent metadata requests can overlap under a modest provider budget.-- Prefer streaming bulk for healthy providers when the new parser/pipeline has- demonstrated bounded memory on LOW devices too. Learn provider capability- and outcomes; retain explicit user modes and category fallback. Device tier- should primarily select memory/batch budgets, rather than decide request- count on its own.-- Parse directly into thin rows with one parser; tolerate provider field- variants without reparsing whole responses. Map rows once.-- Feed a bounded queue to one DB writer. Tune batch size by measured throughput,- row size, heap headroom and transaction duration. Maintain cheap incremental- counts, with durable reconciliation on resume and existing size limits.-- Promote complete snapshots safely and avoid duplicate full index passes.- Refresh writes should skip unchanged records. A partial import must preserve- rows outside its confirmed scope; stale pruning follows complete generations.-- For category fallback use a continuously refilled, bounded worker pool.- Adapt concurrency and pacing to observed server stress, including Retry-After- when supplied, and retry only failed categories with durable checkpoints.-- Prioritize catalog availability before EPG and enrichment. Requested category- work should outrank background completion. Worker slices should have measured- time/row budgets rather than a universal two-category limit.-- Keep details/episodes/enrichment on demand or in lower-priority background- work. Show separate live-ready, catalog-ready, search-ready and guide-ready- states instead of treating queued category shells as completed item sync.--An optional small live preview could shorten first-playable time. Treat that-as a separate product choice; it is not proof of faster complete ingestion and-must not delete the rest of the lineup as if the preview were a full snapshot.--## Implementation and measurement order--1. Instrument baseline milestones and stage costs, then fix continuation order.-2. Benchmark and replace the double parse; add the bounded writer pipeline.-3. Reduce staging/query/index work and skip unchanged refresh writes.-4. Validate bulk on constrained devices, then change AUTO and category workers.-5. Align Settings completion/progress with the same readiness milestones.--Measure request counts, bytes, response-header latency, end-to-end transfer,-parse/map CPU, writer queue wait, staging, commit, FTS, Xtream index, scheduling-wait, peak heap/GC, retry/fallback counts, and total elapsed time. End-to-end-stream duration includes downstream callback work today; do not call that pure-network time. Correlate sanitized records by run/provider/section/strategy.--Compare both first usable live playback and full catalog/search completion.-Use identical provider snapshot, device, section counts, network, hidden-category-configuration, and metadata scope for this app and any reference implementation.-Repeat runs and report median and spread. A 10x target remains unproven.--Use synthetic small and large datasets (for example 50k live, 100k movies,-20k series; many tiny categories and uneven large categories), low/mid/high-device budgets, slow/rate-limited/bulk-rejecting servers, malformed rows,-interrupted imports, and refreshes with zero/small/large changes. Verify counts,-category coverage, playback URLs, search, preserved user state, process-death-resume, provider edits/deletion and failed-snapshot preservation.--The existing local catalog fixture is a correctness fixture: one live channel,-63 movies and 63 series. It cannot establish large-catalog throughput. An-emulator is connected, but its available filtered logcat contained no matching-Xtream sync timing records during inspection. No add-provider operation or-runtime benchmark was performed, and no playback validation is claimed.--## Reference repository comparison--Compare endpoint/request topology, parsing allocations, write and indexing-strategy, readiness criteria, metadata scope, and recovery behavior before-borrowing implementation ideas. Check its license before adapting source.-Use its results to revise this proposal rather than committing to a rewrite-based only on this initial inspection.diff --git a/docs/XTREAM_SYNC_PIPELINE_IMPLEMENTATION.md b/docs/XTREAM_SYNC_PIPELINE_IMPLEMENTATION.mddeleted file mode 100644index ec0588eb..00000000--- a/docs/XTREAM_SYNC_PIPELINE_IMPLEMENTATION.md+++ /dev/null@@ -1,162 +0,0 @@-# Xtream live import pipeline--P3 implementation on `codex/xtream-live-sync-performance`, following the-[improvement plan](XTREAM_SYNC_IMPROVEMENT_PLAN.md). This package changes bulk-live ingestion used by provider setup and Settings Live refresh. AUTO selection-remains behind the P6 gate. Category mode and automatic fallback remain available;-their worker scheduling and pacing improvements belong to P5.--## Retrieval and ownership--For a healthy provider, live category metadata and one bulk live response start-concurrently. Both use the existing provider backoff/retry policy. A provider-with remembered request stress gets one local request slot: metadata resolves-first, then bulk retrieval begins. There are no parallel downloads of the same-bulk endpoint.--The reader sends typed batches through a bounded coroutine channel. A single-consumer on `Dispatchers.Default` waits for category context once, then maps and-stages rows while the HTTP reader continues. Metadata failure explicitly primes-empty adult-category context and retains fallback category semantics. Mapping-does not issue another category request for each batch. Authoritative category-shells, adult flags, hidden/required scope and stream ordering retain their-existing semantics.--Only the consumer owns the staging session, duplicate set, fallback categories,-accepted count and write timings. Reader success requires valid END_DOCUMENT.-Import success also requires channel drain and completion of the final write;-the P1 completion receipt is sealed only after that return.--Reader failure cancels and joins the writer before discarding its attempt.-Writer failure cancels the reader and its HTTP call. Workflow supersession is a-CancellationException, which normally would only cancel the child; the consumer-explicitly cancels its enclosing pipeline scope too. Parent cancellation closes-the queue/response and joins children. Retry gets a fresh queue and the existing-fresh attempt state. No late writer can write into an already discarded session.--## Resource limits--| Tier | Existing row batch limit | Estimated raw batch bytes | Queued batches |-| --- | ---: | ---: | ---: |-| LOW | 100 | 256 KiB | 1 |-| MID | 300 | 512 KiB | 2 |-| HIGH | 500 | 1 MiB | 2 |--These preserve the current row limits; larger tuning candidates remain unselected.-A byte threshold can flush earlier. A row larger than its batch budget fails-explicitly instead of being trimmed or admitted into an oversized queue.-The estimate includes UTF-16 text, category-ID strings and conservative fixed-object/list overhead. It is an accounting limit, not an exact ART heap reading.--At most `queue capacity + 2` full batches are retained by the writer, queue and-suspended sender. While assembling a batch, the producer may also hold its next-decoded row: use `(queue capacity + 3) * batch bytes` as a conservative raw-row-budget. Mapped channels/entities, parser buffers, metadata, duplicate tracking,-Room and indexes are additional allocations.--Live streamed JSON rows also have a 1,048,576-character token-read budget, plus-up to JsonReader's 1,024-character read-ahead. This applies to thin and legacy-streamed live decoders, including category responses, and includes skipped-metadata. It rejects pathological fields before building an entire huge token-or JSON tree. This is a new conservative resource admission rule: large ignored-metadata can also exceed it. No string is silently truncated. Resource failures-do not trigger the more expensive legacy decoder.--The existing 100,000-channel store cap bounds duplicate tracking to that count-plus one incoming batch before rejection. Existing HTTP response caps bound-metadata/response input. Fallback category accumulation is bounded by admitted-rows. P4 will evaluate stage uniqueness instead of the in-memory duplicate set.--The shared policy in singleton SyncManager permits one bulk pipeline across all-providers, so simultaneous imports cannot multiply these queues. Category and-other section jobs still follow their existing concurrency rules; this is not-a general app-wide network or memory scheduler. Live low-memory admission and-runtime abort signals remain active.--## Evidence--Barrier-based tests demonstrate metadata/bulk overlap, adult-context readiness,-one metadata resolution after failure, byte flushing, bounded queue backpressure,-final writer drain and parent/reader/writer cancellation. A transport test-supersedes the writer while the HTTP body is blocked after the first row and-observes underlying Call cancellation. Room attempt-isolation, retry, partial-fallback, supersession and sealed snapshot tests remain part of the regression-suite. Request-stress serialization and shared bulk permits are tested too.--Final regression run: 232 data tests and 16 domain identity tests passed;-both isolated benchmark APKs built. The fixture/report suite passed 14 tests.-The benchmark package is `com.streamvault.app.syncbenchmark`, separate from-ordinary app storage. No user app data was cleared.--Android TV API 36 x86_64 emulator: memory class 192 MB, max Java heap-201,326,592 bytes. Production LOW row batches (100) and one queued batch were-used. Background work stayed enabled. All 24 setup/refresh samples below-(including two warmup samples) retained their full expected channel count and-passed account cleanup, instrumentation, completion/sample-count checks and-untruncated request history.--| Scenario | Initial | Settings Live refresh | Evidence |-| --- | ---: | ---: | --- |-| 2k rows, 10 categories, all modes | STREAM_ALL 1,018 ms | STREAM_ALL 937 ms | Six samples; AUTO/category about 2.5 s |-| 10k rows, 100 categories, STREAM_ALL | Median 4,246 ms; max 4,289 ms | Median 4,306 ms; max 8,290 ms | One warmup + five measured pairs |-| 2k rows, category metadata delayed 1.5 s | 2,725 ms | 2,509 ms | Single pair; bulk begins during metadata wait |-| 2k rows, bulk returns HTTP 503 | 10,523 ms | 16,805 ms | Single pair; complete category fallback |-| 50k rows, 200 categories, STREAM_ALL | 21,090 ms | 40,451 ms | Single pair; three completed bulk imports |--Reports under ignored `build/xtream-sync-performance/`:--- All-mode smoke: `20261010T063839794250Z/report.json`.-- Repeated 10k: `20261010T063927249264Z/report.json`.-- Delayed metadata: `20261010T064037889878Z/report.json`.-- Bulk rejection: `20261010T064106880909Z/report.json`.-- Large catalog: `20261010T064201982860Z/report.json`.--The delayed-metadata request log proves bulk started 2.994 ms after metadata-started, before its 1,500.719 ms response completed. Request high-water was two.-Each synthetic account in the healthy small run issued two bulk requests-(setup + refresh) and no category stream requests. AUTO and explicit category-mode still issued 20 category requests across each account's two phases.--For the repeated 10k run, maximum estimated outstanding batch bytes were-178,154; maximum final drain was 86 ms. Median send time was 3,797 ms: the-reader mostly waited for mapping/staging. Maximum measured sampled Java heap-was 12,964,864 bytes. Thirteen completed bulk responses were observed for-twelve setup/refresh samples; one measured account incurred an extra full-import during its refresh interval, explaining the approximately doubled tail.-The 50k run similarly had three completed responses for two samples, with-maximum outstanding batch bytes 179,184 and drain 85 ms. Peak sampled Java-heap was 59,484,816 bytes on its cold initial sample, falling to 14,574,624-on refresh. These samples do not isolate all sources of heap allocation.--The extra completed imports are not evidence of a partial-body transport retry.-Background scheduling/coalescing needs investigation under P6/P7 before making-latency guarantees. The bulk-rejection account also executed additional import-work: nine rejected bulk requests and 30 category requests across its lifecycle.-Fallback is correct but still slow; P5 pacing and duplicate-work handling remain-necessary.--The 10k payload checksum matches P0/P2. P2's nominal bulk-only initial/refresh-medians were 4,489/4,566 ms (only two samples per phase); its mixed-strategy tail-included low-memory category fallback. P3 shows a modest nominal reduction,-not a controlled speedup ratio. The emulator restarted before P3 and background-timing differed. No category fallback appeared in the healthy P3 bulk runs,-which does not prove that memory pressure was fixed. AUTO's release gate-remains unmet.--The evidence prioritizes P4 writer/mapping and database cost, followed by P5-category fallback. Include redundant completed live imports in the P6/P7-scheduling audit. The fixture supplies no playable media. Playback acceptance,-screen readiness and release-device results remain P8/P0 gates.--## Timing interpretation--`XtreamSyncTiming phase=live-pipeline` records rows, batches, reader elapsed time,-post-reader drain, time spent sending batches, maximum estimated outstanding-batch bytes, queue capacity and byte limit. Outstanding bytes include the-consumer and suspended sender, not just the queue. They exclude the next row-and a producer batch that has not reached send.--Send time includes scheduling/channel overhead as well as backpressure. Reader-wall time includes that waiting. Mapping/staging and response durations overlap;-do not add them together or interpret them as CPU time. The benchmark exporter-accepts only the exact numeric format and discards general logs.diff --git a/docs/XTREAM_SYNC_RECOVERY_IMPLEMENTATION.md b/docs/XTREAM_SYNC_RECOVERY_IMPLEMENTATION.mddeleted file mode 100644index a5bfa66a..00000000--- a/docs/XTREAM_SYNC_RECOVERY_IMPLEMENTATION.md+++ /dev/null@@ -1,93 +0,0 @@-# Xtream live attempt isolation and recovery--Implemented on `codex/xtream-live-sync-performance`, 2026-10-09, after the-initial backend baseline. This package supplies the safety boundary needed-before overlapping retrieval and database writes. Production AUTO selection,-request concurrency and healthy-provider spacing retain their existing behavior.--## Attempt boundaries--Every full response attempt owns its session, duplicate set, pending raw batch,-category collector and accepted-row count. Failure or cancellation clears that-session before retrying. A duplicate admitted by a failed attempt can therefore-be admitted correctly by the successful retry.--Every category attempt uses its own staging session. Only a completed category-is merged into the combined import session. Failed thin decoding, legacy-decoding and transport retries discard their own rows first. SQL merging ignores-channels already present in the completed session, preserving the first-completed category's row. A failed category cannot reserve a duplicate or-overwrite a successful category. Partial results use the existing upsert-only-promotion, preserving channels absent from the completed scopes.--Superseded workflows are cancellation control flow. They stop retry/decoder-fallback and return the workflow's superseded disposition. Provider-wide stage-cleanup and onboarding state writes now check ownership inside their database-transactions. Scoped cancellation cleanup remains possible for the old attempt-without touching a newer session.--HTTP cancellation remains connected throughout response-body reading, including-after headers arrive. A response delivered during a cancellation race is closed.-Streamed arrays must reach their closing token and end of document; extra JSON-after an otherwise valid array cannot establish completion. Alternate decoding-is reserved for parsing/compatibility errors instead of arbitrary writer or-transport failures.--## Durable completion receipt--Schema 79 adds nullable sealed session, configuration generation and mapping-profile columns, plus a sealed row count defaulting to zero. The 78-to-79-migration preserves existing imports while giving them no completion proof.--After a complete full-catalog response, onboarding checks the exact staged row-count and atomically writes category metadata and the receipt. The receipt binds-the session to the authoritative provider configuration generation and the text-classification/base64 mapping flags. Configuration is rechecked inside the-sealing transaction. The receipt contains no credentials or request URLs.--Recovery requires a matching full-catalog receipt, current configuration and-mapping profile, exact accepted/staged row counts, no mixed catalog rows, and-an unrestricted category scope. Anything else is discarded and fetched again.-Normal promotion remains transactional and clears the receipt on completion.--Category snapshots deliberately refetch after interruption. Durable per-category-coverage and resume are still work for the subsequent scheduling package. Until-that exists, a nonempty category stage is never treated as a complete snapshot.-Hidden-category imports also refetch rather than reuse an unproven scope.--## Validation--Focused checks exercise real Room staging, retries after emitted rows,-cross-category duplicates, partial promotion preserving the active library,-supersession, atomic sealing and database close/reopen before promotion.-Orchestration checks cover unsealed rows, missing rows, configuration/mapping-mismatch, category snapshots and valid sealed recovery. HTTP tests cover blocked-body cancellation and trailing documents.--Results:--- 177 focused JVM/Robolectric tests passed, including catalog-store and shared- workflow/Jellyfin checkpoint regression checks.-- Android migration tests passed for a populated schema-78 onboarding record- and the complete migration path from every exported historical schema.-- Benchmark debug application and instrumentation APKs built successfully.- They use `com.streamvault.app.syncbenchmark`, separate from the user's app.-- Synthetic Add Provider and Settings Live refresh passed in all three requested- modes: six samples, 2,000 channels in each, successful sync states and provider- cleanup. No event-history truncation; instrumentation exited successfully.- Report: `build/xtream-sync-performance/20261009T173718237727Z/report.json`.- This is one sample per phase/mode with no warmups, a correctness smoke check.- The device continued to select category requests, so it is not a bulk speed- comparison. The fixture supplies no playable media.--Reproduction:--```powershell-.\gradlew.bat :data:testDebugUnitTest --tests '*XtreamLiveAttemptIsolationTest' --tests '*SyncManagerXtreamLiveStrategyTest' --tests '*SyncManagerTest' --tests '*ProviderWorkflowRunnerTest' --tests '*ProviderWorkflowCommitFenceTest' --tests '*OkHttpXtreamApiServiceTest' --tests '*StreamVaultDatabaseMigrationRegistryTest' --tests '*SyncCatalogStoreTest' --tests '*JellyfinCatalogCheckpointTest'-.\gradlew.bat :data:connectedDebugAndroidTest '-Pandroid.testInstrumentationRunnerArguments.class=com.streamvault.data.local.StreamVaultDatabaseMigrationTest#migrate78To79_preservesSavedImportWithoutGrantingCompletionProof,com.streamvault.data.local.StreamVaultDatabaseMigrationTest#everyExportedHistoricalSchemaMigratesToCurrent'-.\gradlew.bat :app:assembleDebug :app:assembleDebugAndroidTest -PxtreamSyncBenchmark=true-python tools/xtream_sync_benchmark.py --channels 2000 --categories 10 --iterations 1 --warmups 0 --refresh-```--This package makes no speedup claim; parsing, pipelining,-database costs, category scheduling and the AUTO release gate remain ahead.diff --git a/docs/XTREAM_SYNC_RESUME_IMPLEMENTATION.md b/docs/XTREAM_SYNC_RESUME_IMPLEMENTATION.mddeleted file mode 100644index a86ae47e..00000000--- a/docs/XTREAM_SYNC_RESUME_IMPLEMENTATION.md+++ /dev/null@@ -1,71 +0,0 @@-# Coalescing completed Xtream primary recovery work--Targeted recovery previously called full sync unconditionally. Periodic work-also called full sync when its earlier read found incomplete onboarding. A job-queued while foreground catalog work was running could acquire the provider-lock after completion and download the same live lineup again. Measured refresh-accounts sometimes made three complete bulk requests instead of the expected-two for initial import plus refresh, roughly doubling refresh latency.--Both recovery routes now call `resumePrimaryCatalog`. SyncManager rechecks persisted-state after acquiring its provider lock. An Xtream provider can skip-redundant primary work only when:--- onboarding has no incomplete receipt;-- the provider is ACTIVE or in the transitional PARTIAL state;-- the last sync status is SUCCESS;-- the last live success is fresh under the existing catalog TTL;-- no newer unsuccessful live attempt is recorded;-- the actual persisted live count matches metadata.--Failed, partial, stale and incomplete catalogs still run recovery. Initial setup-can still have an inactive PARTIAL provider row while its successful catalog is-already committed and the repository is finalizing activation. The metadata-and onboarding proofs distinguish that transition from an actual partial sync;-provider activation flags alone do not determine catalog completion.-Candidate configuration workflows retain their separate generation-aware path.-Manual full sync and Settings Live refresh retain explicit request semantics,-including nonforced manual full sync with fresh metadata. Other protocols retain-their existing full recovery behavior. Successful foreground work already owns-its durable movie/series/EPG continuations; skipping its duplicate primary import-does not cancel those jobs.--Regression tests exercise a resume queued behind foreground sync, fresh catalog-coalescing, incomplete-count recovery, failed-attempt recovery and existing-manual/worker/workflow behavior. The queued test confirms one live retrieval-across both callers after the foreground transaction completes.-The initial-activation test explicitly uses an inactive PARTIAL provider with-successful complete catalog metadata.--The 10,000-row/100-category emulator run passed all 12 requested samples and-made exactly 12 complete bulk responses, with exactly two requests per account.-Report: `build/xtream-sync-performance/20261010T080831597314Z/report.json`.-Initial median was 5,525 ms and refresh median 5,067 ms. Host unit-test execution-overlapped part of this run, so these times are not a controlled comparison with-P4 medians. No duplicate-import refresh tail occurred in the measured accounts.-This proves the tested path and coverage, not all possible background overlap.--The larger fixture reproduced another necessary handoff: initial provider-activation had not finalized when the periodic resume acquired the lock.-The intermediate runs still made three bulk imports, despite fixing the targeted-route. Their reports are `20261010T081002546566Z`, `20261010T081445540937Z` and-`20261010T081842264251Z` under the same benchmark directory. Recognizing complete-catalog metadata while that provider row is transitional fixes the reproduced-handoff.--Final 50,000-row/200-category report:-`build/xtream-sync-performance/20261010T082158044977Z/report.json`.-Exactly two complete bulk responses occurred for initial setup plus refresh;-both retained 50,000 channels, and cleanup/count assertions passed. Initial setup-took 25,863 ms and refresh 26,765 ms. The preceding run with the redundant import-took 25,213/53,129 ms. These are single-sample diagnostics, not release-device-performance medians. The fixed-format numeric/enum log evidence in-`resume-proof.log` confirms an inactive PARTIAL provider was coalesced. Setup's-final sync state was Success.--Large-catalog writer cost remains substantial. This work removes duplicate-primary retrieval; it does not claim to meet the complete latency target.--Normal app builds on this branch now use bulk-first AUTO. The policy change and-fresh synthetic rechecks are documented in the [P6 tuning report](XTREAM_SYNC_P6_TUNING_REPORT.md);-physical-device and first-screen acceptance remain open.diff --git a/docs/images/ChannelView.png b/docs/images/ChannelView.pngindex 3c61c97b..a2914c81 100644Binary files a/docs/images/ChannelView.png and b/docs/images/ChannelView.png differdiff --git a/docs/images/Guide.png b/docs/images/Guide.pngindex c9dd43ac..c813f369 100644Binary files a/docs/images/Guide.png and b/docs/images/Guide.png differdiff --git a/docs/images/Home.png b/docs/images/Home.pngdeleted file mode 100644index 7f41067b..00000000Binary files a/docs/images/Home.png and /dev/null differdiff --git a/docs/images/MovieInfo.png b/docs/images/MovieInfo.pngindex 25ba4236..cdd7e2f5 100644Binary files a/docs/images/MovieInfo.png and b/docs/images/MovieInfo.png differdiff --git a/docs/images/Movies.png b/docs/images/Movies.pngindex 7c2769e7..446dd62f 100644Binary files a/docs/images/Movies.png and b/docs/images/Movies.png differdiff --git a/docs/images/SeriesEpisodes.png b/docs/images/SeriesEpisodes.pngindex 7daee8cc..bfcf2b8f 100644Binary files a/docs/images/SeriesEpisodes.png and b/docs/images/SeriesEpisodes.png differdiff --git a/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt b/domain/src/main/java/com/streamvault/domain/manager/BackupManager.ktindex 381d3d5c..eb0fe6cb 100644--- a/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt+++ b/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt@@ -59,9 +59,37 @@ data class BackupData(/** v17 portable Stremio configuration; local Room row IDs are deliberately omitted. */val stremioAddons: List<StremioAddonBackup>? = null,/** v17 Stremio playback progress, keyed by stable content identity. */- val stremioPlaybackHistory: List<StremioPlaybackHistoryBackup>? = null+ val stremioPlaybackHistory: List<StremioPlaybackHistoryBackup>? = null,+ /** v18 sports provider configurations; account IDs remain stable for source preferences. */+ val sportsProviders: List<SportsProviderBackup>? = null,+ /** v18 sports API credentials, keyed by sports provider instance ID. */+ val sportsProviderCredentials: List<SportsProviderCredentialsBackup>? = null)+data class SportsProviderBackup(+ val instanceId: String,+ val typeId: String,+ val configurationVersion: Int,+ val enabled: Boolean,+ val priority: Int,+ val baseUrl: String? = null,+ val eventLeagueIds: List<String> = emptyList(),+ val customDefinitionJson: String? = null+) {+ override fun toString(): String =+ "SportsProviderBackup(instanceId=$instanceId, typeId=$typeId, enabled=$enabled)"+}++/** Credentials are carried separately from provider configuration and redact diagnostic output. */+data class SportsProviderCredentialsBackup(+ val instanceId: String,+ val secret: String,+ val username: String? = null+) {+ override fun toString(): String =+ "SportsProviderCredentialsBackup(instanceId=$instanceId, credentials=[REDACTED])"+}+data class StremioAddonBackup(val installUrl: String,val manifestId: String,diff --git a/domain/src/main/java/com/streamvault/domain/sports/provider/SportsProvider.kt b/domain/src/main/java/com/streamvault/domain/sports/provider/SportsProvider.ktindex 863b0910..dd2e41d9 100644--- a/domain/src/main/java/com/streamvault/domain/sports/provider/SportsProvider.kt+++ b/domain/src/main/java/com/streamvault/domain/sports/provider/SportsProvider.kt@@ -150,7 +150,7 @@ data class SportsProviderHealth(}}-/** Storage never participates in the general preferences export or cloud backup. */+/** Provider configurations stay separate from preferences and use dedicated portable backup records. */interface SportsProviderStore {suspend fun configurations(): List<SportsProviderConfig>suspend fun credentials(instanceId: String): SportsProviderCredentials?diff --git a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsBackupAboutSections.kt b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsBackupAboutSections.ktindex 238a9285..de05730b 100644--- a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsBackupAboutSections.kt+++ b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsBackupAboutSections.kt@@ -28,6 +28,9 @@ import com.streamvault.core.ui.theme.Primaryimport com.streamvault.core.ui.theme.Secondaryimport com.streamvault.domain.manager.DriveAuthState+private const val OPEN_SOURCE_LICENSES_URL =+ "https://github.com/Davidona/StreamVault-IPTV/blob/master/docs/THIRD-PARTY-LICENSES.md"+public fun LazyListScope.settingsBackupSection(uiState: SettingsUiState,viewModel: SettingsViewModel,@@ -564,6 +567,12 @@ public fun LazyListScope.settingsAboutSection(onClick = { onOpenUri(context.getString(R.string.settings_github_url)) },modifier = if (targetItemId == "about.github") targetFocusModifier else Modifier,)+ ClickableSettingsRow(+ label = stringResource(R.string.settings_open_source_licenses),+ value = "",+ onClick = { onOpenUri(OPEN_SOURCE_LICENSES_URL) },+ modifier = if (targetItemId == "about.open_source_licenses") targetFocusModifier else Modifier,+ )ClickableSettingsRow(label = stringResource(R.string.settings_donate),value = stringResource(R.string.settings_donate_url),diff --git a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsSearchSurface.kt b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsSearchSurface.ktindex b8141a5d..ac9c150f 100644--- a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsSearchSurface.kt+++ b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsSearchSurface.kt@@ -346,6 +346,7 @@ private fun resolvedSettingsCatalog(setting("support.crash_share", SettingsCategory.ABOUT, SettingsPage.REPORTS, R.string.settings_crash_report_share),setting("support.crash_delete", SettingsCategory.ABOUT, SettingsPage.REPORTS, R.string.settings_crash_report_delete),setting("about.github", SettingsCategory.ABOUT, SettingsPage.APP_INFO, R.string.settings_github, "source code"),+ setting("about.open_source_licenses", SettingsCategory.ABOUT, SettingsPage.APP_INFO, R.string.settings_open_source_licenses, "license notices", "third-party"),setting("about.donate", SettingsCategory.ABOUT, SettingsPage.APP_INFO, R.string.settings_donate, "support"),setting("about.close_app", SettingsCategory.ABOUT, SettingsPage.APP_INFO, R.string.settings_close_app, "exit"),)diff --git a/feature/settings/src/main/res/values-ar/strings.xml b/feature/settings/src/main/res/values-ar/strings.xmlindex 3ae27e44..947f8886 100644--- a/feature/settings/src/main/res/values-ar/strings.xml+++ b/feature/settings/src/main/res/values-ar/strings.xml@@ -946,4 +946,5 @@<string name="settings_sports_provider_beta">بيتا · لم يُختبر باستخدام حساب فعلي للمزوّد.</string><string name="settings_sports_custom_definition_example_action">إدراج مثال</string><string name="settings_sports_custom_definition_placeholder">الصق JSON الخاص بالمزوّد</string>+ <string name="settings_open_source_licenses">تراخيص وإشعارات البرامج مفتوحة المصدر</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-bg/strings.xml b/feature/settings/src/main/res/values-bg/strings.xmlindex 46ccd1de..0a319cc4 100644--- a/feature/settings/src/main/res/values-bg/strings.xml+++ b/feature/settings/src/main/res/values-bg/strings.xml@@ -932,4 +932,5 @@<string name="settings_sports_provider_beta">Бета · не е тестван с реален акаунт на доставчика.</string><string name="settings_sports_custom_definition_example_action">Вмъкване на пример</string><string name="settings_sports_custom_definition_placeholder">Поставете JSON на доставчика</string>+ <string name="settings_open_source_licenses">Лицензи и известия за софтуер с отворен код</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-cs/strings.xml b/feature/settings/src/main/res/values-cs/strings.xmlindex 74608596..76c590ea 100644--- a/feature/settings/src/main/res/values-cs/strings.xml+++ b/feature/settings/src/main/res/values-cs/strings.xml@@ -940,4 +940,5 @@<string name="settings_sports_provider_beta">Beta · nebylo testováno s živým účtem poskytovatele.</string><string name="settings_sports_custom_definition_example_action">Vložit příklad</string><string name="settings_sports_custom_definition_placeholder">Vložte JSON poskytovatele</string>+ <string name="settings_open_source_licenses">Licence a oznámení k softwaru s otevřeným zdrojovým kódem</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-da/strings.xml b/feature/settings/src/main/res/values-da/strings.xmlindex 097fbff5..84663b0c 100644--- a/feature/settings/src/main/res/values-da/strings.xml+++ b/feature/settings/src/main/res/values-da/strings.xml@@ -934,4 +934,5 @@<string name="settings_sports_provider_beta">Beta · ikke testet med en aktiv udbyderkonto.</string><string name="settings_sports_custom_definition_example_action">Indsæt eksempel</string><string name="settings_sports_custom_definition_placeholder">Indsæt udbyderens JSON</string>+ <string name="settings_open_source_licenses">Open source-licenser og meddelelser</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-de/strings.xml b/feature/settings/src/main/res/values-de/strings.xmlindex 9b8ce1f5..9a279650 100644--- a/feature/settings/src/main/res/values-de/strings.xml+++ b/feature/settings/src/main/res/values-de/strings.xml@@ -930,4 +930,5 @@<string name="settings_sports_provider_beta">Beta · nicht mit einem aktiven Anbieter-Konto getestet.</string><string name="settings_sports_custom_definition_example_action">Beispiel einfügen</string><string name="settings_sports_custom_definition_placeholder">JSON des Anbieters einfügen</string>+ <string name="settings_open_source_licenses">Open-Source-Lizenzen und Hinweise</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-el/strings.xml b/feature/settings/src/main/res/values-el/strings.xmlindex 8dafd4f8..5597ae9a 100644--- a/feature/settings/src/main/res/values-el/strings.xml+++ b/feature/settings/src/main/res/values-el/strings.xml@@ -934,4 +934,5 @@<string name="settings_sports_provider_beta">Beta · δεν έχει δοκιμαστεί με ενεργό λογαριασμό παρόχου.</string><string name="settings_sports_custom_definition_example_action">Εισαγωγή παραδείγματος</string><string name="settings_sports_custom_definition_placeholder">Επικολλήστε το JSON του παρόχου</string>+ <string name="settings_open_source_licenses">Άδειες και γνωστοποιήσεις λογισμικού ανοικτού κώδικα</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-es/strings.xml b/feature/settings/src/main/res/values-es/strings.xmlindex 1e7f9fb3..9a27099b 100644--- a/feature/settings/src/main/res/values-es/strings.xml+++ b/feature/settings/src/main/res/values-es/strings.xml@@ -930,4 +930,5 @@<string name="settings_sports_provider_beta">Beta · no se ha probado con una cuenta activa del proveedor.</string><string name="settings_sports_custom_definition_example_action">Insertar ejemplo</string><string name="settings_sports_custom_definition_placeholder">Pega el JSON del proveedor</string>+ <string name="settings_open_source_licenses">Licencias y avisos de código abierto</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-fa/strings.xml b/feature/settings/src/main/res/values-fa/strings.xmlindex b2e5f292..9acedfeb 100644--- a/feature/settings/src/main/res/values-fa/strings.xml+++ b/feature/settings/src/main/res/values-fa/strings.xml@@ -932,4 +932,5 @@<string name="settings_sports_provider_beta">بتا · با حساب فعال ارائهدهنده آزمایش نشده است.</string><string name="settings_sports_custom_definition_example_action">درج نمونه</string><string name="settings_sports_custom_definition_placeholder">JSON ارائهدهنده را جایگذاری کنید</string>+ <string name="settings_open_source_licenses">مجوزها و اطلاعیههای نرمافزار متنباز</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-fi/strings.xml b/feature/settings/src/main/res/values-fi/strings.xmlindex 93a5abbe..531ced8c 100644--- a/feature/settings/src/main/res/values-fi/strings.xml+++ b/feature/settings/src/main/res/values-fi/strings.xml@@ -934,4 +934,5 @@<string name="settings_sports_provider_beta">Beta · ei testattu toimivalla palveluntarjoajan tilillä.</string><string name="settings_sports_custom_definition_example_action">Lisää esimerkki</string><string name="settings_sports_custom_definition_placeholder">Liitä palveluntarjoajan JSON</string>+ <string name="settings_open_source_licenses">Avoimen lähdekoodin lisenssit ja ilmoitukset</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-fil/strings.xml b/feature/settings/src/main/res/values-fil/strings.xmlindex fac9a84b..f79430a2 100644--- a/feature/settings/src/main/res/values-fil/strings.xml+++ b/feature/settings/src/main/res/values-fil/strings.xml@@ -932,4 +932,5 @@<string name="settings_sports_provider_beta">Beta · hindi pa nasubukan gamit ang aktibong account ng provider.</string><string name="settings_sports_custom_definition_example_action">Maglagay ng halimbawa</string><string name="settings_sports_custom_definition_placeholder">I-paste ang JSON ng provider</string>+ <string name="settings_open_source_licenses">Mga lisensya at abiso ng open source</string></resources>diff --git a/feature/settings/src/main/res/values-fr/strings.xml b/feature/settings/src/main/res/values-fr/strings.xmlindex f6632c6c..660d7538 100644--- a/feature/settings/src/main/res/values-fr/strings.xml+++ b/feature/settings/src/main/res/values-fr/strings.xml@@ -934,4 +934,5 @@<string name="settings_sports_provider_beta">Bêta · non testé avec un compte actif du fournisseur.</string><string name="settings_sports_custom_definition_example_action">Insérer un exemple</string><string name="settings_sports_custom_definition_placeholder">Collez le JSON du fournisseur</string>+ <string name="settings_open_source_licenses">Licences et mentions des logiciels libres</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-hi/strings.xml b/feature/settings/src/main/res/values-hi/strings.xmlindex e351f2ef..b06e3b72 100644--- a/feature/settings/src/main/res/values-hi/strings.xml+++ b/feature/settings/src/main/res/values-hi/strings.xml@@ -932,4 +932,5 @@<string name="settings_sports_provider_beta">बीटा · प्रदाता के सक्रिय खाते से परीक्षण नहीं किया गया है।</string><string name="settings_sports_custom_definition_example_action">उदाहरण डालें</string><string name="settings_sports_custom_definition_placeholder">प्रदाता JSON पेस्ट करें</string>+ <string name="settings_open_source_licenses">ओपन-सोर्स लाइसेंस और सूचनाएँ</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-hr/strings.xml b/feature/settings/src/main/res/values-hr/strings.xmlindex 2fbc8ec4..8873d2d1 100644--- a/feature/settings/src/main/res/values-hr/strings.xml+++ b/feature/settings/src/main/res/values-hr/strings.xml@@ -935,4 +935,5 @@<string name="settings_sports_provider_beta">Beta · nije testirano s aktivnim računom pružatelja.</string><string name="settings_sports_custom_definition_example_action">Umetni primjer</string><string name="settings_sports_custom_definition_placeholder">Zalijepite JSON pružatelja</string>+ <string name="settings_open_source_licenses">Licence i obavijesti otvorenog koda</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-hu/strings.xml b/feature/settings/src/main/res/values-hu/strings.xmlindex 6786f008..8f763904 100644--- a/feature/settings/src/main/res/values-hu/strings.xml+++ b/feature/settings/src/main/res/values-hu/strings.xml@@ -934,4 +934,5 @@<string name="settings_sports_provider_beta">Béta · nem teszteltük élő szolgáltatói fiókkal.</string><string name="settings_sports_custom_definition_example_action">Példa beszúrása</string><string name="settings_sports_custom_definition_placeholder">Illeszd be a szolgáltató JSON-adatait</string>+ <string name="settings_open_source_licenses">Nyílt forráskódú licencek és közlemények</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-in/strings.xml b/feature/settings/src/main/res/values-in/strings.xmlindex fba1d0be..e0a1c29d 100644--- a/feature/settings/src/main/res/values-in/strings.xml+++ b/feature/settings/src/main/res/values-in/strings.xml@@ -934,4 +934,5 @@<string name="settings_sports_provider_beta">Beta · belum diuji dengan akun penyedia yang aktif.</string><string name="settings_sports_custom_definition_example_action">Sisipkan contoh</string><string name="settings_sports_custom_definition_placeholder">Tempel JSON penyedia</string>+ <string name="settings_open_source_licenses">Lisensi dan pemberitahuan sumber terbuka</string></resources>diff --git a/feature/settings/src/main/res/values-it/strings.xml b/feature/settings/src/main/res/values-it/strings.xmlindex 73b2673c..689980dc 100644--- a/feature/settings/src/main/res/values-it/strings.xml+++ b/feature/settings/src/main/res/values-it/strings.xml@@ -930,4 +930,5 @@<string name="settings_sports_provider_beta">Beta · non testato con un account attivo del provider.</string><string name="settings_sports_custom_definition_example_action">Inserisci esempio</string><string name="settings_sports_custom_definition_placeholder">Incolla il JSON del provider</string>+ <string name="settings_open_source_licenses">Licenze e avvisi open source</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-iw/strings.xml b/feature/settings/src/main/res/values-iw/strings.xmlindex 4d04f9ff..6fe48763 100644--- a/feature/settings/src/main/res/values-iw/strings.xml+++ b/feature/settings/src/main/res/values-iw/strings.xml@@ -937,4 +937,5 @@<string name="settings_sports_provider_beta">בטא · לא נבדק עם חשבון פעיל של הספק.</string><string name="settings_sports_custom_definition_example_action">הוספת דוגמה</string><string name="settings_sports_custom_definition_placeholder">הדביקו JSON של ספק</string>+ <string name="settings_open_source_licenses">רישיונות והודעות של קוד פתוח</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-ja/strings.xml b/feature/settings/src/main/res/values-ja/strings.xmlindex 4c01aac5..3bb57214 100644--- a/feature/settings/src/main/res/values-ja/strings.xml+++ b/feature/settings/src/main/res/values-ja/strings.xml@@ -932,4 +932,5 @@<string name="settings_sports_provider_beta">ベータ版・プロバイダーの有効なアカウントでは未テストです。</string><string name="settings_sports_custom_definition_example_action">例を挿入</string><string name="settings_sports_custom_definition_placeholder">プロバイダーのJSONを貼り付け</string>+ <string name="settings_open_source_licenses">オープンソースライセンスと通知</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-ko/strings.xml b/feature/settings/src/main/res/values-ko/strings.xmlindex e98e1c3b..dd0a5302 100644--- a/feature/settings/src/main/res/values-ko/strings.xml+++ b/feature/settings/src/main/res/values-ko/strings.xml@@ -930,4 +930,5 @@<string name="settings_sports_provider_beta">베타 · 실제 제공업체 계정으로 테스트되지 않았습니다.</string><string name="settings_sports_custom_definition_example_action">예시 삽입</string><string name="settings_sports_custom_definition_placeholder">제공업체 JSON 붙여넣기</string>+ <string name="settings_open_source_licenses">오픈 소스 라이선스 및 고지</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-mk/strings.xml b/feature/settings/src/main/res/values-mk/strings.xmlindex 04367c1c..96dee423 100644--- a/feature/settings/src/main/res/values-mk/strings.xml+++ b/feature/settings/src/main/res/values-mk/strings.xml@@ -932,4 +932,5 @@<string name="settings_sports_provider_beta">Бета · не е тестирано со активна сметка на провајдерот.</string><string name="settings_sports_custom_definition_example_action">Вметни пример</string><string name="settings_sports_custom_definition_placeholder">Залепете JSON од провајдерот</string>+ <string name="settings_open_source_licenses">Лиценци и известувања за софтвер со отворен код</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-ms/strings.xml b/feature/settings/src/main/res/values-ms/strings.xmlindex e0f39469..cf7ba36c 100644--- a/feature/settings/src/main/res/values-ms/strings.xml+++ b/feature/settings/src/main/res/values-ms/strings.xml@@ -929,4 +929,5 @@<string name="settings_sports_provider_beta">Beta · belum diuji dengan akaun penyedia yang aktif.</string><string name="settings_sports_custom_definition_example_action">Sisipkan contoh</string><string name="settings_sports_custom_definition_placeholder">Tampal JSON penyedia</string>+ <string name="settings_open_source_licenses">Lesen dan notis sumber terbuka</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-nb/strings.xml b/feature/settings/src/main/res/values-nb/strings.xmlindex 0aa65a6d..76f743a4 100644--- a/feature/settings/src/main/res/values-nb/strings.xml+++ b/feature/settings/src/main/res/values-nb/strings.xml@@ -934,4 +934,5 @@<string name="settings_sports_provider_beta">Beta · ikke testet med en aktiv leverandørkonto.</string><string name="settings_sports_custom_definition_example_action">Sett inn eksempel</string><string name="settings_sports_custom_definition_placeholder">Lim inn leverandørens JSON</string>+ <string name="settings_open_source_licenses">Lisenser og merknader for åpen kildekode</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-nl/strings.xml b/feature/settings/src/main/res/values-nl/strings.xmlindex 9c17f4ce..4901e25c 100644--- a/feature/settings/src/main/res/values-nl/strings.xml+++ b/feature/settings/src/main/res/values-nl/strings.xml@@ -934,4 +934,5 @@<string name="settings_sports_provider_beta">Bèta · niet getest met een actief account van de provider.</string><string name="settings_sports_custom_definition_example_action">Voorbeeld invoegen</string><string name="settings_sports_custom_definition_placeholder">Plak de JSON van de provider</string>+ <string name="settings_open_source_licenses">Open-sourcelicenties en kennisgevingen</string></resources>diff --git a/feature/settings/src/main/res/values-pl/strings.xml b/feature/settings/src/main/res/values-pl/strings.xmlindex c4844fa0..8f128f54 100644--- a/feature/settings/src/main/res/values-pl/strings.xml+++ b/feature/settings/src/main/res/values-pl/strings.xml@@ -940,4 +940,5 @@<string name="settings_sports_provider_beta">Beta · nie testowano z aktywnym kontem dostawcy.</string><string name="settings_sports_custom_definition_example_action">Wstaw przykład</string><string name="settings_sports_custom_definition_placeholder">Wklej JSON dostawcy</string>+ <string name="settings_open_source_licenses">Licencje i informacje o oprogramowaniu open source</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-pt/strings.xml b/feature/settings/src/main/res/values-pt/strings.xmlindex bb00c460..68d32016 100644--- a/feature/settings/src/main/res/values-pt/strings.xml+++ b/feature/settings/src/main/res/values-pt/strings.xml@@ -930,4 +930,5 @@<string name="settings_sports_provider_beta">Beta · não testado com uma conta ativa do provedor.</string><string name="settings_sports_custom_definition_example_action">Inserir exemplo</string><string name="settings_sports_custom_definition_placeholder">Cole o JSON do provedor</string>+ <string name="settings_open_source_licenses">Licenças e avisos de código aberto</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-ro/strings.xml b/feature/settings/src/main/res/values-ro/strings.xmlindex 9e8e965d..ae823e84 100644--- a/feature/settings/src/main/res/values-ro/strings.xml+++ b/feature/settings/src/main/res/values-ro/strings.xml@@ -937,4 +937,5 @@<string name="settings_sports_provider_beta">Beta · netestat cu un cont activ al furnizorului.</string><string name="settings_sports_custom_definition_example_action">Inserează exemplu</string><string name="settings_sports_custom_definition_placeholder">Lipește JSON-ul furnizorului</string>+ <string name="settings_open_source_licenses">Licențe și notificări pentru software open-source</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-ru/strings.xml b/feature/settings/src/main/res/values-ru/strings.xmlindex 70795803..d0f70296 100644--- a/feature/settings/src/main/res/values-ru/strings.xml+++ b/feature/settings/src/main/res/values-ru/strings.xml@@ -940,4 +940,5 @@<string name="settings_sports_provider_beta">Бета · не проверено с активной учетной записью провайдера.</string><string name="settings_sports_custom_definition_example_action">Вставить пример</string><string name="settings_sports_custom_definition_placeholder">Вставьте JSON провайдера</string>+ <string name="settings_open_source_licenses">Лицензии и уведомления об открытом исходном коде</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-sk/strings.xml b/feature/settings/src/main/res/values-sk/strings.xmlindex b6080b7b..cc174841 100644--- a/feature/settings/src/main/res/values-sk/strings.xml+++ b/feature/settings/src/main/res/values-sk/strings.xml@@ -938,4 +938,5 @@<string name="settings_sports_provider_beta">Beta · nebolo testované s aktívnym účtom poskytovateľa.</string><string name="settings_sports_custom_definition_example_action">Vložiť príklad</string><string name="settings_sports_custom_definition_placeholder">Vložte JSON poskytovateľa</string>+ <string name="settings_open_source_licenses">Licencie a oznámenia o otvorenom kóde</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-sq/strings.xml b/feature/settings/src/main/res/values-sq/strings.xmlindex 02b73c98..7be57cde 100644--- a/feature/settings/src/main/res/values-sq/strings.xml+++ b/feature/settings/src/main/res/values-sq/strings.xml@@ -932,4 +932,5 @@<string name="settings_sports_provider_beta">Beta · nuk është testuar me një llogari aktive të ofruesit.</string><string name="settings_sports_custom_definition_example_action">Fut shembullin</string><string name="settings_sports_custom_definition_placeholder">Ngjitni JSON-in e ofruesit</string>+ <string name="settings_open_source_licenses">Licencat dhe njoftimet e burimit të hapur</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-sr/strings.xml b/feature/settings/src/main/res/values-sr/strings.xmlindex e2c9a3a6..ca45647d 100644--- a/feature/settings/src/main/res/values-sr/strings.xml+++ b/feature/settings/src/main/res/values-sr/strings.xml@@ -935,4 +935,5 @@<string name="settings_sports_provider_beta">Бета · није тестирано са активним налогом добављача.</string><string name="settings_sports_custom_definition_example_action">Уметни пример</string><string name="settings_sports_custom_definition_placeholder">Налепите JSON добављача</string>+ <string name="settings_open_source_licenses">Лиценце и обавештења о софтверу отвореног кода</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-sv/strings.xml b/feature/settings/src/main/res/values-sv/strings.xmlindex 7302631a..61109041 100644--- a/feature/settings/src/main/res/values-sv/strings.xml+++ b/feature/settings/src/main/res/values-sv/strings.xml@@ -934,4 +934,5 @@<string name="settings_sports_provider_beta">Beta · inte testad med ett aktivt leverantörskonto.</string><string name="settings_sports_custom_definition_example_action">Infoga exempel</string><string name="settings_sports_custom_definition_placeholder">Klistra in leverantörens JSON</string>+ <string name="settings_open_source_licenses">Licenser och meddelanden för öppen källkod</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-th/strings.xml b/feature/settings/src/main/res/values-th/strings.xmlindex 98899fd7..ffa5fd03 100644--- a/feature/settings/src/main/res/values-th/strings.xml+++ b/feature/settings/src/main/res/values-th/strings.xml@@ -929,4 +929,5 @@<string name="settings_sports_provider_beta">เบต้า · ยังไม่ได้ทดสอบด้วยบัญชีผู้ให้บริการที่ใช้งานจริง</string><string name="settings_sports_custom_definition_example_action">แทรกตัวอย่าง</string><string name="settings_sports_custom_definition_placeholder">วาง JSON ของผู้ให้บริการ</string>+ <string name="settings_open_source_licenses">ใบอนุญาตและประกาศเกี่ยวกับซอฟต์แวร์โอเพนซอร์ส</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-tr/strings.xml b/feature/settings/src/main/res/values-tr/strings.xmlindex 36e4f122..0d25119e 100644--- a/feature/settings/src/main/res/values-tr/strings.xml+++ b/feature/settings/src/main/res/values-tr/strings.xml@@ -934,4 +934,5 @@<string name="settings_sports_provider_beta">Beta · sağlayıcının etkin bir hesabıyla test edilmedi.</string><string name="settings_sports_custom_definition_example_action">Örneği ekle</string><string name="settings_sports_custom_definition_placeholder">Sağlayıcı JSON verisini yapıştırın</string>+ <string name="settings_open_source_licenses">Açık kaynak lisansları ve bildirimleri</string></resources>diff --git a/feature/settings/src/main/res/values-uk/strings.xml b/feature/settings/src/main/res/values-uk/strings.xmlindex f2514cdf..d7b0368e 100644--- a/feature/settings/src/main/res/values-uk/strings.xml+++ b/feature/settings/src/main/res/values-uk/strings.xml@@ -940,4 +940,5 @@<string name="settings_sports_provider_beta">Бета · не перевірено з активним обліковим записом провайдера.</string><string name="settings_sports_custom_definition_example_action">Вставити приклад</string><string name="settings_sports_custom_definition_placeholder">Вставте JSON провайдера</string>+ <string name="settings_open_source_licenses">Ліцензії та повідомлення про відкрите програмне забезпечення</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-vi/strings.xml b/feature/settings/src/main/res/values-vi/strings.xmlindex c08ca6b0..33de77f5 100644--- a/feature/settings/src/main/res/values-vi/strings.xml+++ b/feature/settings/src/main/res/values-vi/strings.xml@@ -931,4 +931,5 @@<string name="settings_sports_provider_beta">Beta · chưa được kiểm thử bằng tài khoản nhà cung cấp đang hoạt động.</string><string name="settings_sports_custom_definition_example_action">Chèn ví dụ</string><string name="settings_sports_custom_definition_placeholder">Dán JSON của nhà cung cấp</string>+ <string name="settings_open_source_licenses">Giấy phép và thông báo mã nguồn mở</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-zh-rTW/strings.xml b/feature/settings/src/main/res/values-zh-rTW/strings.xmlindex d4f6f2c3..f973b476 100644--- a/feature/settings/src/main/res/values-zh-rTW/strings.xml+++ b/feature/settings/src/main/res/values-zh-rTW/strings.xml@@ -929,4 +929,5 @@<string name="settings_sports_provider_beta">Beta(測試版)· 尚未使用有效的提供者帳戶進行測試。</string><string name="settings_sports_custom_definition_example_action">插入範例</string><string name="settings_sports_custom_definition_placeholder">貼上提供者 JSON</string>+ <string name="settings_open_source_licenses">開放原始碼授權與聲明</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values-zh/strings.xml b/feature/settings/src/main/res/values-zh/strings.xmlindex 1f2eb024..933d38e3 100644--- a/feature/settings/src/main/res/values-zh/strings.xml+++ b/feature/settings/src/main/res/values-zh/strings.xml@@ -930,4 +930,5 @@<string name="settings_sports_provider_beta">测试版 · 尚未使用有效的提供商账户进行测试。</string><string name="settings_sports_custom_definition_example_action">插入示例</string><string name="settings_sports_custom_definition_placeholder">粘贴提供商 JSON</string>+ <string name="settings_open_source_licenses">开源许可证和声明</string></resources>\ No newline at end of filediff --git a/feature/settings/src/main/res/values/strings.xml b/feature/settings/src/main/res/values/strings.xmlindex 0074506d..2d923973 100644--- a/feature/settings/src/main/res/values/strings.xml+++ b/feature/settings/src/main/res/values/strings.xml@@ -994,7 +994,7 @@<string name="settings_sports_metadata_source">Team and league metadata source</string><string name="settings_sports_provider_custom_json">Custom JSON provider</string><string name="settings_sports_custom_definition">Configuration (JSON)</string>- <string name="settings_sports_custom_definition_hint">Enter the API's HTTPS base URL above. Insert the example, then replace the endpoint paths and JSON fields to match your API documentation. Put its key or token in the credential field.</string>+ <string name="settings_sports_custom_definition_hint">Enter the API\'s HTTPS base URL above. Insert the example, then replace the endpoint paths and JSON fields to match your API documentation. Put its key or token in the credential field.</string><string name="settings_sports_provider_attribution">Data from %1$s</string><string name="settings_sports_provider_football_data_name">Football-Data.org</string><string name="settings_sports_provider_football_data_attribution">Football data provided by %1$s</string>@@ -1009,4 +1009,5 @@<string name="settings_sports_provider_beta">Beta · not tested with a live provider account.</string><string name="settings_sports_custom_definition_example_action">Insert example</string><string name="settings_sports_custom_definition_placeholder">Paste provider JSON</string>-</resources>\ No newline at end of file+ <string name="settings_open_source_licenses">Open-source licenses and notices</string>+</resources>diff --git a/local.properties.example b/local.properties.exampleindex 059ff168..7ddf310d 100644--- a/local.properties.example+++ b/local.properties.example@@ -8,18 +8,19 @@# $ cp local.properties.example local.properties## Values declared here are read at build time by `app/build.gradle.kts` and-# injected into `BuildConfig.*` fields, but ONLY for the `debug` build type.-# Release builds inherit empty defaults from `defaultConfig`, so a release-# APK can never ship a contributor's credentials regardless of what your-# `local.properties` contains.+# injected into `BuildConfig.*` fields for the `debug` build type only. The+# OpenSubtitles key can also be provided through the `OPENSUBTITLES_API_KEY`+# environment variable for beta/release CI builds. Release builds do not read+# values from this local file.## See `docs/DEV_SEEDING.md` for the full opt-in onboarding flow.# ------------------------------------------------------------------------------# --- OpenSubtitles API application key (debug builds only) --------------------+# --- OpenSubtitles API application key (local debug builds) -------------------# Get a key from OpenSubtitles, then add it to your ignored `local.properties`:# opensubtitles.api.key=your-opensubtitles-api-key-# Rebuild the app after changing this value.+# Rebuild the app after changing this value. CI beta/release builds receive the+# same app key from the GitHub Actions secret OPENSUBTITLES_API_KEY.# === Trakt app configuration (public client settings) =========================# Environment TRAKT_CLIENT_ID / TRAKT_REDIRECT_URI take precedence.