Repository: jonathanklee/Sapio Branch: main Commit: fde6ba30e24f Files: 202 Total size: 463.2 KB Directory structure: gitextract_rftqr9mc/ ├── .github/ │ ├── FUNDING.yml │ └── workflows/ │ ├── android.yml │ └── jekyll-gh-pages.yml ├── .gitignore ├── LICENSE ├── README.md ├── app/ │ ├── .gitignore │ ├── build.gradle │ ├── detekt-baseline.xml │ ├── proguard-rules.pro │ └── src/ │ ├── androidTest/ │ │ └── java/ │ │ └── com/ │ │ └── klee/ │ │ └── sapio/ │ │ └── ExampleInstrumentedTest.kt │ ├── main/ │ │ ├── AndroidManifest.xml │ │ ├── java/ │ │ │ └── com/ │ │ │ └── klee/ │ │ │ └── sapio/ │ │ │ ├── SapioApplication.kt │ │ │ ├── ui/ │ │ │ │ ├── model/ │ │ │ │ │ ├── InstalledAppWithRating.kt │ │ │ │ │ ├── Label.kt │ │ │ │ │ ├── Rating.kt │ │ │ │ │ └── SharedEvaluation.kt │ │ │ │ ├── state/ │ │ │ │ │ ├── AppEvaluationsUiState.kt │ │ │ │ │ ├── ChooseAppUiState.kt │ │ │ │ │ ├── EvaluateUiState.kt │ │ │ │ │ ├── FeedUiState.kt │ │ │ │ │ ├── MyAppsUiState.kt │ │ │ │ │ └── SearchUiState.kt │ │ │ │ ├── view/ │ │ │ │ │ ├── AboutFragment.kt │ │ │ │ │ ├── ChooseAppAdapter.kt │ │ │ │ │ ├── ChooseAppDialog.kt │ │ │ │ │ ├── ChooseAppFragment.kt │ │ │ │ │ ├── Color.kt │ │ │ │ │ ├── ContributeFragment.kt │ │ │ │ │ ├── EvaluateFragment.kt │ │ │ │ │ ├── EvaluationsFragment.kt │ │ │ │ │ ├── FeedAppAdapter.kt │ │ │ │ │ ├── FeedFragment.kt │ │ │ │ │ ├── FragmentAdapter.kt │ │ │ │ │ ├── LoadingFragment.kt │ │ │ │ │ ├── MainActivity.kt │ │ │ │ │ ├── MyAppsAdapter.kt │ │ │ │ │ ├── MyAppsFragment.kt │ │ │ │ │ ├── PreferencesFragment.kt │ │ │ │ │ ├── SearchAppAdapter.kt │ │ │ │ │ ├── SearchFragment.kt │ │ │ │ │ ├── ShareComposable.kt │ │ │ │ │ ├── SplashActivity.kt │ │ │ │ │ ├── SuccessFragment.kt │ │ │ │ │ ├── ToastMessage.kt │ │ │ │ │ └── WarningFragment.kt │ │ │ │ └── viewmodel/ │ │ │ │ ├── AppEvaluationsViewModel.kt │ │ │ │ ├── ChooseAppViewModel.kt │ │ │ │ ├── EvaluateViewModel.kt │ │ │ │ ├── FeedViewModel.kt │ │ │ │ ├── LoadingViewModel.kt │ │ │ │ ├── MyAppsViewModel.kt │ │ │ │ └── SearchViewModel.kt │ │ │ └── work/ │ │ │ ├── CompatibilityCheckScheduler.kt │ │ │ ├── CompatibilityCheckWorker.kt │ │ │ └── CompatibilityNotificationManager.kt │ │ └── res/ │ │ ├── drawable/ │ │ │ ├── bg_label_rounded.xml │ │ │ ├── ic_close.xml │ │ │ ├── ic_info_background.xml │ │ │ ├── ic_launcher_foreground.xml │ │ │ ├── ic_notification_info.xml │ │ │ ├── ic_phone.xml │ │ │ ├── ic_settings.xml │ │ │ ├── ic_status_green.xml │ │ │ ├── ic_status_red.xml │ │ │ └── ic_status_yellow.xml │ │ ├── drawable-anydpi/ │ │ │ ├── ic_add.xml │ │ │ ├── ic_search.xml │ │ │ └── ic_settings.xml │ │ ├── drawable-v33/ │ │ │ └── ic_launcher_monochrome.xml │ │ ├── layout/ │ │ │ ├── activity_main.xml │ │ │ ├── activity_splash.xml │ │ │ ├── choose_app_card.xml │ │ │ ├── dialog_choose_app.xml │ │ │ ├── feed_app_card.xml │ │ │ ├── fragment_about.xml │ │ │ ├── fragment_choose_app.xml │ │ │ ├── fragment_contribute.xml │ │ │ ├── fragment_evaluate.xml │ │ │ ├── fragment_evaluations.xml │ │ │ ├── fragment_loading.xml │ │ │ ├── fragment_main.xml │ │ │ ├── fragment_my_apps.xml │ │ │ ├── fragment_search.xml │ │ │ ├── fragment_success.xml │ │ │ ├── fragment_warning.xml │ │ │ ├── my_app_card.xml │ │ │ └── search_app_card.xml │ │ ├── menu/ │ │ │ ├── bottom_menu.xml │ │ │ └── menu.xml │ │ ├── mipmap-anydpi-v26/ │ │ │ ├── ic_info.xml │ │ │ ├── ic_info_round.xml │ │ │ ├── ic_launcher.xml │ │ │ ├── ic_launcher_round.xml │ │ │ ├── search_icon.xml │ │ │ └── search_icon_round.xml │ │ ├── navigation/ │ │ │ └── nav_graph.xml │ │ ├── raw/ │ │ │ └── loading.json │ │ ├── values/ │ │ │ ├── colors.xml │ │ │ ├── dimens.xml │ │ │ ├── strings.xml │ │ │ └── themes.xml │ │ ├── values-de/ │ │ │ └── strings.xml │ │ ├── values-es/ │ │ │ └── strings.xml │ │ ├── values-fr/ │ │ │ └── strings.xml │ │ ├── values-it/ │ │ │ └── strings.xml │ │ ├── values-land/ │ │ │ └── dimens.xml │ │ ├── values-night/ │ │ │ └── colors.xml │ │ ├── values-night-v31/ │ │ │ └── themes.xml │ │ ├── values-v31/ │ │ │ └── themes.xml │ │ ├── values-w1240dp/ │ │ │ └── dimens.xml │ │ ├── values-w600dp/ │ │ │ └── dimens.xml │ │ └── xml/ │ │ └── preferences.xml │ └── test/ │ └── java/ │ └── com/ │ └── klee/ │ └── sapio/ │ ├── AppEvaluationsViewModelTest.kt │ ├── DeviceConfigurationTest.kt │ ├── DomainUseCasesTest.kt │ ├── EvaluateAppUseCaseBehaviourTest.kt │ ├── EvaluateAppUseCaseTest.kt │ ├── EvaluateViewModelTest.kt │ ├── EvaluationServiceTest.kt │ ├── FeedViewModelTest.kt │ ├── InstalledApplicationsRepositoryTest.kt │ ├── LoadingViewModelTest.kt │ ├── RatingTest.kt │ ├── SapioApplicationTest.kt │ ├── SearchViewModelTest.kt │ ├── SettingsTest.kt │ ├── SystemPropertyReaderTest.kt │ └── data/ │ ├── local/ │ │ └── EvaluationDaoTest.kt │ └── repository/ │ └── EvaluationRepositoryImplTest.kt ├── build.gradle ├── data/ │ ├── build.gradle │ └── src/ │ ├── main/ │ │ └── java/ │ │ └── com/ │ │ └── klee/ │ │ └── sapio/ │ │ └── data/ │ │ ├── api/ │ │ │ └── RetrofitClient.kt │ │ ├── di/ │ │ │ └── DataModule.kt │ │ ├── dto/ │ │ │ ├── Evaluation.kt │ │ │ ├── IconDtos.kt │ │ │ ├── StrapiDtos.kt │ │ │ └── UploadDtos.kt │ │ ├── fdroid/ │ │ │ ├── CachedFdroidAvailabilityChecker.kt │ │ │ └── OkHttpFdroidAvailabilityChecker.kt │ │ ├── local/ │ │ │ ├── AppDatabase.kt │ │ │ ├── Converters.kt │ │ │ ├── DatabaseModule.kt │ │ │ ├── DeviceAppDao.kt │ │ │ ├── DeviceAppEntity.kt │ │ │ ├── EvaluationDao.kt │ │ │ └── EvaluationEntity.kt │ │ ├── repository/ │ │ │ ├── DeviceAppCacheRepositoryImpl.kt │ │ │ ├── EvaluationRepositoryImpl.kt │ │ │ └── InstalledApplicationsRepository.kt │ │ └── system/ │ │ ├── DeviceConfiguration.kt │ │ ├── Settings.kt │ │ └── SystemPropertyReader.kt │ └── test/ │ └── java/ │ └── com/ │ └── klee/ │ └── sapio/ │ └── data/ │ ├── CachedFdroidAvailabilityCheckerTest.kt │ ├── ConvertersTest.kt │ ├── EvaluationRepositoryImplTest.kt │ └── InstalledApplicationsRepositoryTest.kt ├── detekt.yml ├── domain/ │ ├── build.gradle │ └── src/ │ ├── main/ │ │ └── java/ │ │ └── com/ │ │ └── klee/ │ │ └── sapio/ │ │ └── domain/ │ │ ├── AppSettings.kt │ │ ├── CheckFdroidAvailabilityUseCase.kt │ │ ├── DeviceAppCacheRepository.kt │ │ ├── DeviceInfo.kt │ │ ├── EvaluateAppUseCase.kt │ │ ├── EvaluationRepository.kt │ │ ├── FdroidAvailabilityChecker.kt │ │ ├── FetchAppEvaluationUseCase.kt │ │ ├── FetchIconUrlUseCase.kt │ │ ├── InstalledApplicationsDataSource.kt │ │ ├── ListLatestEvaluationsUseCase.kt │ │ ├── SearchEvaluationUseCase.kt │ │ └── model/ │ │ ├── CachedDeviceApp.kt │ │ ├── DeviceProfile.kt │ │ └── Models.kt │ └── test/ │ └── java/ │ └── com/ │ └── klee/ │ └── sapio/ │ └── domain/ │ ├── CheckFdroidAvailabilityUseCaseTest.kt │ ├── EvaluateAppUseCaseTest.kt │ ├── FetchAppEvaluationUseCaseTest.kt │ ├── FetchIconUrlUseCaseTest.kt │ ├── ListLatestEvaluationsUseCaseTest.kt │ └── SearchEvaluationUseCaseTest.kt ├── fastlane/ │ └── metadata/ │ └── android/ │ ├── de-DE/ │ │ ├── full_description.txt │ │ ├── short_description.txt │ │ └── title.txt │ ├── en-US/ │ │ ├── changelogs/ │ │ │ └── 4.txt │ │ ├── full_description.txt │ │ ├── short_description.txt │ │ └── title.txt │ ├── es-ES/ │ │ ├── full_description.txt │ │ ├── short_description.txt │ │ └── title.txt │ ├── fr-FR/ │ │ ├── full_description.txt │ │ └── short_description.txt │ └── it-IT/ │ ├── full_description.txt │ ├── short_description.txt │ └── title.txt ├── gradle/ │ ├── libs.versions.toml │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat └── settings.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ ko_fi: jnthnkl ================================================ FILE: .github/workflows/android.yml ================================================ name: Android CI on: push: branches: [ "main" ] pull_request: branches: [ "main" ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: set up JDK 17 uses: actions/setup-java@v3 with: java-version: '17' distribution: 'temurin' cache: gradle - name: Grant execute permission for gradlew run: chmod +x gradlew - name: Build and checks with Gradle run: ./gradlew detekt assembleRelease testRelease --parallel ================================================ FILE: .github/workflows/jekyll-gh-pages.yml ================================================ # Sample workflow for building and deploying a Jekyll site to GitHub Pages name: Deploy Jekyll with GitHub Pages dependencies preinstalled on: # Runs on pushes targeting the default branch push: branches: ["main"] # Allows you to run this workflow manually from the Actions tab workflow_dispatch: # Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages permissions: contents: read pages: write id-token: write # Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued. # However, do NOT cancel in-progress runs as we want to allow these production deployments to complete. concurrency: group: "pages" cancel-in-progress: false jobs: # Build job build: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v4 - name: Setup Pages uses: actions/configure-pages@v5 - name: Build with Jekyll uses: actions/jekyll-build-pages@v1 with: source: ./ destination: ./_site - name: Upload artifact uses: actions/upload-pages-artifact@v3 # Deployment job deploy: environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} runs-on: ubuntu-latest needs: build steps: - name: Deploy to GitHub Pages id: deployment uses: actions/deploy-pages@v4 ================================================ FILE: .gitignore ================================================ *.iml .gradle /local.properties /.idea/* .DS_Store **/build /captures .externalNativeBuild .cxx local.properties ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================

# Sapio Sapio is the anagram of Open Source API. Sapio provides the compatibility of an Android application running on a device without Google Play Services (i.e. deGoogled bare Android Open Source Project (AOSP) devices, coupled or not with microG). Sapio can serve as a lobbying tool by sharing compatibility on social media to raise awareness among app developers about respecting users' personal data. Evaluations in Sapio are given to the community by the community. [Get it on F-Droid](https://f-droid.org/packages/com.klee.sapio/) [Get it on GitHub](https://github.com/jonathanklee/Sapio/releases)

    

# Rating 🟢 The app works perfectly without Google Play Services 🟡 The app works partially: at least one feature (notifications, in-app purchases, login methods etc) does not work without Google Play Services 🔴 The app does not work at all or crashes without Google Play Services **bareAOSP** The device is a bare AOSP device **microG** The device has microG installed **secure** The device is considered secured **unsafe** The device is considered unsafe # 🔨 Build ## Get the sources ``` git clone git@github.com:jonathanklee/Sapio.git ``` ## Build Sapio ``` cd Sapio ./gradlew assembleDebug ```` # 📱 Install ``` adb install ./app/build/outputs/apk/debug/app-debug.apk ``` # 🌍 Public API ## Base url ``` https://server.sapio.ovh/api ``` ## Endpoints ### List evaluations - Endpoint: /sapio-applications - Method: GET - Description: List evaluations - Parameters: https://docs.strapi.io/dev-docs/api/rest/parameters - Result: - https://docs.strapi.io/dev-docs/api/rest#requests - attributes: - microg: 1 for microG, 2 for bareAOSP - secure: 3 for secure, 4 for unsafe - rating: 1 for green, 2 for yellow, 3 for red - Example: Get the latest 100 evaluations ``` curl -X GET "https://server.sapio.ovh/api/sapio-applications?pagination\[pageSize\]=100&sort=updatedAt:Desc" ``` ### Search evaluations - Endpoint: /sapio-applications - Method: GET - Description: Search evaluations - Parameters: https://docs.strapi.io/dev-docs/api/rest/filters-locale-publication#filtering - Result: - https://docs.strapi.io/dev-docs/api/rest#requests - attributes: - microg: 1 for microG, 2 for bareAOSP - secure: 3 for secure, 4 for unsafe - rating: 1 for green, 2 for yellow, 3 for red - Example: Search evaluations for an app called ChatGPT ``` curl -X GET "https://server.sapio.ovh/api/sapio-applications?filters\[name\]\[\$eq\]=ChatGPT" ``` ### Get icons - Endpoint: /upload/files - Method: GET - Description: Get icons - Parameters: https://docs.strapi.io/dev-docs/api/rest/parameters - Example: Get ChatGPT icon ``` curl -X GET "https://server.sapio.ovh/api/upload/files?filters\[name\]\[\$eq\]=com.openai.chatgpt.png" ``` # ⚠️ Disclaimer Evaluations are community-contributed and may be inaccurate, incomplete, or device-specific. Sapio and its maintainers are not responsible for any issues arising from relying on these evaluations. # ☕ Coffee If you want to offer me a coffee for the maintenance of the server part: Buy Me a Coffee at ko-fi.com # 👏 Credits Brain icons created by Freepik - Flaticon Search icons created by Smashicons - Flaticon ================================================ FILE: app/.gitignore ================================================ /build ================================================ FILE: app/build.gradle ================================================ plugins { id 'com.android.application' id 'org.jetbrains.kotlin.android' id 'kotlin-parcelize' id 'kotlin-kapt' id 'dagger.hilt.android.plugin' alias libs.plugins.compose.compiler id 'jacoco' } android { compileSdk 36 defaultConfig { applicationId "com.klee.sapio" minSdk 21 targetSdk 35 versionCode 85 versionName "2.2.3" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_17 targetCompatibility JavaVersion.VERSION_17 } kotlinOptions { jvmTarget = '17' } testOptions { unitTests.returnDefaultValues = true } buildFeatures { viewBinding = true compose = true } namespace 'com.klee.sapio' } jacoco { toolVersion = "0.8.13" reportsDirectory = layout.buildDirectory.dir("jacocoReports") } // Ensure jacoco agent instruments all JVM unit tests (including Robolectric). tasks.withType(Test).configureEach { jacoco.includeNoLocationClasses = true jacoco.excludes += ['jdk.internal.*'] } tasks.register("jacocoTestReport", JacocoReport) { dependsOn tasks.test reports { xml.required = true html.required = true } def fileFilter = [ '**/R.class', '**/R$*.class', '**/BuildConfig.*', '**/Manifest*.*', '**/*Test*.*', '**/android/**/*.*', '**/androidTest/**/*.*', '**/test/**/*.*', '**/*$ViewInjector*.*', '**/*$ViewBinder*.*', '**/databinding/**/*.*' ] // Kotlin and Java classes live in different intermediate folders with AGP 8+. def kotlinDebugTree = fileTree( dir: "${project.buildDir}/tmp/kotlin-classes/debug", excludes: fileFilter ) def javaDebugTree = fileTree( dir: "${project.buildDir}/intermediates/javac/debug/compileDebugJavaWithJavac/classes", excludes: fileFilter ) def mainSrc = [ "${project.projectDir}/src/main/java", "${project.projectDir}/src/main/kotlin" ] sourceDirectories.from = files(mainSrc) classDirectories.from = files([kotlinDebugTree, javaDebugTree]) executionData.from = fileTree(dir: "${project.buildDir}", includes: ["**/*.exec", "**/*.ec"]) } tasks.register("jacocoTestCoverageVerification", JacocoCoverageVerification) { dependsOn tasks.jacocoTestReport violationRules { rule { limit { minimum = 0.5 // 50% coverage minimum } } } } dependencies { implementation project(':domain') implementation project(':data') implementation libs.androidx.core.ktx implementation libs.androidx.appcompat implementation libs.material implementation libs.androidx.constraintlayout implementation libs.glide implementation libs.coil.compose implementation libs.coil.network.okhttp implementation libs.kotlinx.coroutines.android implementation libs.androidx.navigation.fragment.ktx implementation libs.androidx.navigation.ui.ktx implementation libs.androidx.recyclerview implementation libs.room.runtime implementation libs.room.ktx kapt libs.room.compiler // hilt implementation libs.hilt.android implementation libs.androidx.runner implementation libs.androidx.material3.android kapt libs.hilt.compiler testImplementation libs.hilt.android.testing implementation libs.androidx.emoji2 implementation libs.androidx.emoji2.views implementation libs.androidx.emoji2.views.helper implementation libs.rootbeer.lib testImplementation libs.junit testImplementation libs.mockito.core testImplementation libs.mockito.inline testImplementation libs.robolectric testImplementation libs.kotlinx.coroutines.test testImplementation libs.androidx.arch.core.testing androidTestImplementation libs.mockito.android androidTestImplementation libs.androidx.junit androidTestImplementation libs.androidx.espresso.core // retrofit implementation libs.retrofit implementation libs.converter.jackson implementation libs.logging.interceptor implementation libs.retrofit2.kotlin.coroutines.adapter implementation libs.circleimageview implementation libs.androidx.swiperefreshlayout // splashscreen implementation libs.androidx.core.splashscreen // preferences implementation libs.androidx.preference.ktx // workmanager implementation libs.androidx.work.runtime.ktx // lottie implementation libs.lottie // compose implementation platform(libs.androidx.compose.bom) implementation(libs.androidx.foundation) implementation libs.androidx.ui implementation libs.androidx.ui.tooling.preview implementation libs.androidx.activity.compose debugImplementation libs.androidx.ui.tooling } ================================================ FILE: app/detekt-baseline.xml ================================================ LoopWithTooManyJumpStatements:DeviceConfiguration.kt$DeviceConfiguration$for TooManyFunctions:EvaluationRepository.kt$EvaluationRepository TooManyFunctions:EvaluationRepositoryImpl.kt$EvaluationRepositoryImpl : EvaluationRepository ================================================ FILE: app/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # You can control the set of applied configuration files using the # proguardFiles setting in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} # Uncomment this to preserve the line number information for # debugging stack traces. #-keepattributes SourceFile,LineNumberTable # If you keep the line number information, uncomment this to # hide the original source file name. #-renamesourcefileattribute SourceFile ================================================ FILE: app/src/androidTest/java/com/klee/sapio/ExampleInstrumentedTest.kt ================================================ package com.klee.sapio import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import junit.framework.TestCase.assertEquals import org.junit.runner.RunWith import org.junit.Test /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.klee.sapio", appContext.packageName) } } ================================================ FILE: app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: app/src/main/java/com/klee/sapio/SapioApplication.kt ================================================ package com.klee.sapio import android.app.Application import com.google.android.material.color.DynamicColors import com.klee.sapio.work.CompatibilityCheckScheduler import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class SapioApplication : Application() { override fun onCreate() { super.onCreate() DynamicColors.applyToActivitiesIfAvailable(this) CompatibilityCheckScheduler.schedule(this) } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/model/InstalledAppWithRating.kt ================================================ package com.klee.sapio.ui.model import com.klee.sapio.domain.model.Evaluation import com.klee.sapio.domain.model.InstalledApplication data class InstalledAppWithRating( val installedApp: InstalledApplication, val evaluation: Evaluation? ) ================================================ FILE: app/src/main/java/com/klee/sapio/ui/model/Label.kt ================================================ package com.klee.sapio.ui.model import android.content.Context import android.os.Build import androidx.annotation.RequiresApi import com.klee.sapio.R import com.klee.sapio.domain.model.GmsType import com.klee.sapio.domain.model.UserType data class Label(val text: String, val color: Int) { companion object { const val MICROG = GmsType.MICROG const val BARE_AOSP = GmsType.BARE_AOSP const val SECURE = UserType.SECURE const val UNSAFE = UserType.UNSAFE @RequiresApi(Build.VERSION_CODES.M) fun create(context: Context, label: Int): Label { return when (label) { MICROG -> Label( context.getString(R.string.microg_label), context.getColor(R.color.blue_200) ) BARE_AOSP -> Label( context.getString(R.string.bare_aosp_label), context.getColor(R.color.blue_700) ) SECURE -> Label( context.getString(R.string.secure_label), context.getColor(R.color.purple_200) ) UNSAFE -> Label( context.getString(R.string.unsafe_label), context.getColor(R.color.purple_700) ) else -> Label(" Empty label ", context.getColor(R.color.black)) } } } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/model/Rating.kt ================================================ package com.klee.sapio.ui.model import com.klee.sapio.R data class Rating(val value: Int, val drawable: Int, val text: String) { companion object { const val GOOD = 1 const val AVERAGE = 2 const val BAD = 3 const val GREEN_CIRCLE_EMOJI = 0x1F7E2 const val YELLOW_CIRCLE_EMOJI = 0x1F7E1 const val RED_CIRCLE_EMOJI = 0x1F534 fun create(rating: Int): Rating { return when (rating) { GOOD -> Rating(GOOD, R.drawable.ic_status_green, String(Character.toChars(GREEN_CIRCLE_EMOJI))) AVERAGE -> Rating(AVERAGE, R.drawable.ic_status_yellow, String(Character.toChars(YELLOW_CIRCLE_EMOJI))) BAD -> Rating(BAD, R.drawable.ic_status_red, String(Character.toChars(RED_CIRCLE_EMOJI))) else -> Rating(BAD, R.drawable.ic_status_red, String(Character.toChars(RED_CIRCLE_EMOJI))) } } } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/model/SharedEvaluation.kt ================================================ package com.klee.sapio.ui.model import android.graphics.Bitmap data class SharedEvaluation( val name: String, val packageName: String, val icon: Bitmap, val ratingMicrog: Int, val ratingBareAOSP: Int ) ================================================ FILE: app/src/main/java/com/klee/sapio/ui/state/AppEvaluationsUiState.kt ================================================ package com.klee.sapio.ui.state import com.klee.sapio.domain.model.Evaluation data class AppEvaluationsUiState( val microgUser: Evaluation? = null, val microgRoot: Evaluation? = null, val bareAospUser: Evaluation? = null, val bareAospRoot: Evaluation? = null, val iconUrl: String? = null, val pendingCount: Int = 0, val hasError: Boolean = false ) { val isFullyLoaded: Boolean get() = pendingCount == 0 } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/state/ChooseAppUiState.kt ================================================ package com.klee.sapio.ui.state import com.klee.sapio.domain.model.InstalledApplication data class ChooseAppUiState( val apps: List = emptyList(), val isLoading: Boolean = true ) ================================================ FILE: app/src/main/java/com/klee/sapio/ui/state/EvaluateUiState.kt ================================================ package com.klee.sapio.ui.state data class EvaluateUiState( val gmsType: Int, val userType: Int ) sealed class EvaluateEvent { data class NavigateToSuccess(val packageName: String, val appName: String) : EvaluateEvent() object ShowError : EvaluateEvent() } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/state/FeedUiState.kt ================================================ package com.klee.sapio.ui.state import com.klee.sapio.domain.model.Evaluation data class FeedUiState( val items: List = emptyList(), val isLoading: Boolean = false, val isLoadingMore: Boolean = false, val hasError: Boolean = false ) ================================================ FILE: app/src/main/java/com/klee/sapio/ui/state/MyAppsUiState.kt ================================================ package com.klee.sapio.ui.state import com.klee.sapio.ui.model.InstalledAppWithRating data class MyAppsUiState( val items: List = emptyList(), val isLoading: Boolean = false, val isRefreshing: Boolean = false, val progress: Int = 0 ) ================================================ FILE: app/src/main/java/com/klee/sapio/ui/state/SearchUiState.kt ================================================ package com.klee.sapio.ui.state import com.klee.sapio.domain.model.Evaluation data class SearchUiState( val query: String = "", val items: List = emptyList(), val isLoading: Boolean = false, val hasError: Boolean = false ) ================================================ FILE: app/src/main/java/com/klee/sapio/ui/view/AboutFragment.kt ================================================ package com.klee.sapio.ui.view import android.os.Build import android.os.Bundle import android.text.Html import android.text.method.LinkMovementMethod import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.klee.sapio.BuildConfig import com.klee.sapio.R import com.klee.sapio.databinding.FragmentAboutBinding class AboutFragment : Fragment() { companion object { const val RATING_RULES = "https://github.com/jonathanklee/Sapio?tab=readme-ov-file#rating" const val GITHUB_URL = "https://github.com/jonathanklee/Sapio" } private var _binding: FragmentAboutBinding? = null private val mBinding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentAboutBinding.inflate(inflater, container, false) return mBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mBinding.version.text = "v${BuildConfig.VERSION_NAME}" mBinding.ratingRules.text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Html.fromHtml(getString(R.string.rating_rules, RATING_RULES), Html.FROM_HTML_MODE_COMPACT) } else { @Suppress("DEPRECATION") Html.fromHtml(getString(R.string.rating_rules, RATING_RULES)) } mBinding.ratingRules.movementMethod = LinkMovementMethod.getInstance() } override fun onDestroyView() { super.onDestroyView() _binding = null } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/view/ChooseAppAdapter.kt ================================================ package com.klee.sapio.ui.view import android.content.pm.PackageManager import android.os.Build import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.klee.sapio.databinding.ChooseAppCardBinding import com.klee.sapio.domain.model.InstalledApplication class ChooseAppAdapter( private val onAppClicked: (InstalledApplication) -> Unit ) : ListAdapter(DIFF_CALLBACK) { inner class ViewHolder(val binding: ChooseAppCardBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(app: InstalledApplication) { binding.appName.text = app.name try { val pm = binding.root.context.packageManager val appInfo = pm.getApplicationInfo(app.packageName, 0) val icon = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { appInfo.loadUnbadgedIcon(pm) } else { appInfo.loadIcon(pm) } binding.appIcon.setImageDrawable(icon) } catch (e: PackageManager.NameNotFoundException) { // leave default icon } binding.root.setOnClickListener { onAppClicked(app) } binding.appIcon.setOnClickListener { onAppClicked(app) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = ChooseAppCardBinding.inflate(LayoutInflater.from(parent.context), parent, false) return ViewHolder(binding) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(getItem(position)) } companion object { private val DIFF_CALLBACK = object : DiffUtil.ItemCallback() { override fun areItemsTheSame(old: InstalledApplication, new: InstalledApplication) = old.packageName == new.packageName override fun areContentsTheSame(old: InstalledApplication, new: InstalledApplication) = old == new } } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/view/ChooseAppDialog.kt ================================================ package com.klee.sapio.ui.view import android.content.DialogInterface import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.DialogFragment import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.klee.sapio.databinding.DialogChooseAppBinding import com.klee.sapio.domain.model.InstalledApplication import com.klee.sapio.ui.state.ChooseAppUiState import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch class ChooseAppDialog( private val uiState: StateFlow, private val onAppSelected: (InstalledApplication) -> Unit, private val onDismissed: (() -> Unit)? = null ) : DialogFragment() { private lateinit var mBinding: DialogChooseAppBinding private var hasSelection = false override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { mBinding = DialogChooseAppBinding.inflate(layoutInflater) return mBinding.root } override fun onStart() { super.onStart() val width = (resources.displayMetrics.widthPixels * DIALOG_WIDTH_RATIO).toInt() dialog?.window?.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) val recyclerView = mBinding.recyclerView recyclerView.layoutManager = LinearLayoutManager(requireActivity(), RecyclerView.VERTICAL, false) val adapter = ChooseAppAdapter { app -> hasSelection = true dismiss() onAppSelected(app) } recyclerView.adapter = adapter viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { uiState.collect { state -> if (state.apps.isNotEmpty()) { mBinding.progressBar.visibility = View.GONE recyclerView.visibility = View.VISIBLE } adapter.submitList(state.apps) } } } } override fun onCancel(dialog: DialogInterface) { super.onCancel(dialog) if (!hasSelection) { onDismissed?.invoke() } } override fun onDismiss(dialog: DialogInterface) { super.onDismiss(dialog) if (!hasSelection) { onDismissed?.invoke() } } companion object { private const val DIALOG_WIDTH_RATIO = 0.75 } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/view/ChooseAppFragment.kt ================================================ package com.klee.sapio.ui.view import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.navigation.fragment.findNavController import com.klee.sapio.R import com.klee.sapio.databinding.FragmentChooseAppBinding import com.klee.sapio.domain.model.InstalledApplication import com.klee.sapio.ui.viewmodel.ChooseAppViewModel import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class ChooseAppFragment : Fragment() { private lateinit var mBinding: FragmentChooseAppBinding private var mApp: InstalledApplication? = null val viewModel: ChooseAppViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { mBinding = FragmentChooseAppBinding.inflate(inflater, container, false) mBinding.chooseAppButton.setOnClickListener { onChooseButtonClicked() } mBinding.nextButton.isEnabled = false mBinding.nextButton.setOnClickListener { onNextButtonClicked() } mBinding.backButton.setOnClickListener { findNavController().navigate(R.id.action_chooseAppFragment_to_warningFragment) } return mBinding.root } private fun onChooseButtonClicked() { mBinding.chooseAppButton.isEnabled = false mBinding.nextButton.isEnabled = false val dialog = ChooseAppDialog( uiState = viewModel.uiState, onAppSelected = { chosenApp -> mBinding.appName.text = chosenApp.name mApp = chosenApp mBinding.nextButton.isEnabled = true mBinding.chooseAppButton.isEnabled = true }, onDismissed = { mBinding.chooseAppButton.isEnabled = true } ) dialog.show(parentFragmentManager, "") } private fun onNextButtonClicked() { val bundle = bundleOf( "package" to mApp?.packageName, "name" to mApp?.name ) findNavController().navigate(R.id.action_chooseAppFragment_to_evaluateFragment, bundle) } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/view/Color.kt ================================================ package com.klee.sapio.ui.view import androidx.compose.ui.graphics.Color val Blue200 = Color(0xFF90CAF9) val Blue700 = Color(0xFF1976D2) val Gray = Color(0xFF212121) ================================================ FILE: app/src/main/java/com/klee/sapio/ui/view/ContributeFragment.kt ================================================ package com.klee.sapio.ui.view import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.klee.sapio.databinding.FragmentContributeBinding class ContributeFragment : Fragment() { private lateinit var mBinding: FragmentContributeBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { mBinding = FragmentContributeBinding.inflate(inflater, container, false) return mBinding.root } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/view/EvaluateFragment.kt ================================================ package com.klee.sapio.ui.view import android.content.res.ColorStateList import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.RadioButton import androidx.annotation.RequiresApi import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import com.klee.sapio.R import com.klee.sapio.databinding.FragmentEvaluateBinding import com.klee.sapio.ui.model.Label import com.klee.sapio.ui.model.Rating import com.klee.sapio.ui.viewmodel.EvaluateViewModel import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class EvaluateFragment : Fragment() { companion object { const val NOT_EXISTING = -1 } private val mViewModel by viewModels() private lateinit var mBinding: FragmentEvaluateBinding @RequiresApi(Build.VERSION_CODES.M) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { mBinding = FragmentEvaluateBinding.inflate(inflater, container, false) val packageName = arguments?.getString("package").orEmpty() val appName = arguments?.getString("name").orEmpty() val state = mViewModel.uiState.value val microgLabel = Label.create(requireContext(), state.gmsType) mBinding.microgConfiguration.text = microgLabel.text mBinding.microgConfiguration.backgroundTintList = ColorStateList.valueOf(microgLabel.color) val isRootedLabel = Label.create(requireContext(), state.userType) mBinding.secureConfiguration.text = isRootedLabel.text mBinding.secureConfiguration.backgroundTintList = ColorStateList.valueOf(isRootedLabel.color) mBinding.validateButton.isEnabled = false mBinding.note.setOnCheckedChangeListener { _, _ -> updateButtonState() } mBinding.validateButton.setOnClickListener { val rating = getRatingFromRadioId(mBinding.note.checkedRadioButtonId, requireView()) val bundle = bundleOf("package" to packageName, "name" to appName, "rating" to rating) findNavController().navigate(R.id.action_evaluateFragment_to_loadingFragment, bundle) } mBinding.backButton.setOnClickListener { findNavController().navigate(R.id.action_evaluateFragment_to_chooseAppFragment) } return mBinding.root } private fun updateButtonState() { val radioSelected = mBinding.note.checkedRadioButtonId != -1 mBinding.validateButton.isEnabled = radioSelected } private fun getRatingFromRadioId(id: Int, view: View): Int { val radioButton: RadioButton = view.findViewById(id) return when (radioButton.text) { getString(R.string.works_perfectly) -> Rating.GOOD getString(R.string.works_partially) -> Rating.AVERAGE getString(R.string.dont_work) -> Rating.BAD else -> 0 } } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/view/EvaluationsFragment.kt ================================================ package com.klee.sapio.ui.view import android.app.NotificationManager import android.content.ContentValues import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.drawable.Drawable import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Environment import android.provider.MediaStore.Images.Media import android.util.Log import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.annotation.RequiresApi import androidx.compose.runtime.Composable import androidx.compose.ui.platform.ComposeView import androidx.core.graphics.createBitmap import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.lifecycleScope import com.bumptech.glide.Glide import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.target.CustomTarget import com.bumptech.glide.request.target.Target import com.bumptech.glide.request.transition.Transition import com.klee.sapio.R import com.klee.sapio.databinding.FragmentEvaluationsBinding import com.klee.sapio.domain.AppSettings import com.klee.sapio.ui.model.Rating import com.klee.sapio.ui.model.SharedEvaluation import com.klee.sapio.ui.viewmodel.AppEvaluationsViewModel import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import kotlinx.coroutines.suspendCancellableCoroutine import java.io.IOException import java.text.DateFormat import javax.inject.Inject import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException @AndroidEntryPoint class EvaluationsFragment : Fragment() { @Inject lateinit var settings: AppSettings private var _binding: FragmentEvaluationsBinding? = null private val mBinding get() = _binding!! private val mViewModel by activityViewModels() private lateinit var shareLauncher: ActivityResultLauncher private var shareImage: Uri? = null private var iconReady = false companion object { const val TAG = "EvaluationsFragment" const val COMPRESSION_QUALITY = 100 const val SCREENSHOT_WIDTH_DP = 200 const val SCREENSHOT_HEIGHT_DP = 115 private const val ARG_PACKAGE_NAME = "packageName" private const val ARG_APP_NAME = "appName" private const val ARG_SHARE_IMMEDIATELY = "shareImmediately" private const val ARG_NOTIFICATION_ID = "notificationId" fun newInstance( packageName: String, appName: String, shareImmediately: Boolean = false, notificationId: Int = -1 ) = EvaluationsFragment().apply { arguments = Bundle().apply { putString(ARG_PACKAGE_NAME, packageName) putString(ARG_APP_NAME, appName) putBoolean(ARG_SHARE_IMMEDIATELY, shareImmediately) putInt(ARG_NOTIFICATION_ID, notificationId) } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) shareLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { shareImage?.let { requireContext().contentResolver.delete(it, null, null) } shareImage = null } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentEvaluationsBinding.inflate(inflater, container, false) return mBinding.root } @RequiresApi(Build.VERSION_CODES.O) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val packageName = arguments?.getString(ARG_PACKAGE_NAME).orEmpty() val appName = arguments?.getString(ARG_APP_NAME).orEmpty() val shareImmediately = arguments?.getBoolean(ARG_SHARE_IMMEDIATELY) ?: false val notificationId = arguments?.getInt(ARG_NOTIFICATION_ID) ?: -1 mBinding.packageName.text = packageName mBinding.applicationName.text = appName mBinding.shareButton.setOnClickListener { startTakingScreenshot(appName, packageName) } mBinding.infoIcon.setOnClickListener { (requireActivity() as MainActivity).navigateToAbout() } hideCard() if (shareImmediately) { if (notificationId != -1) { val notificationManager = requireContext().getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.cancel(notificationId) } onElementsLoaded { startTakingScreenshot(appName, packageName) } } onElementsLoaded { showCard() } handleUnsafeConfigurationSetting() observeEvaluations() } private fun hideCard() { mBinding.card.visibility = View.INVISIBLE mBinding.progressBar.visibility = View.VISIBLE } private fun showCard() { mBinding.progressBar.visibility = View.GONE mBinding.card.visibility = View.VISIBLE } private fun onElementsLoaded(callback: () -> Unit) { mViewModel.uiState .filter { it.isFullyLoaded } .onEach { callback.invoke() } .launchIn(viewLifecycleOwner.lifecycleScope) } private fun handleUnsafeConfigurationSetting() { val shouldShow = settings.isUnsafeConfigurationEnabled() with(mBinding) { secure.isVisible = shouldShow microgRoot.isVisible = shouldShow bareAospRoot.isVisible = shouldShow empty.isVisible = shouldShow unsafe.isVisible = shouldShow if (shouldShow) { val extraPadding = resources.getDimensionPixelSize(R.dimen.card_unsafe_extra_padding) cardContent.setPadding(extraPadding, 0, extraPadding, 0) } } } private fun observeEvaluations() { viewLifecycleOwner.lifecycleScope.launch { mViewModel.uiState.collect { state -> renderEvaluation(mBinding.microgUser, state.microgUser) renderEvaluation(mBinding.bareAospUser, state.bareAospUser) if (settings.isUnsafeConfigurationEnabled()) { renderEvaluation(mBinding.bareAospRoot, state.bareAospRoot) renderEvaluation(mBinding.microgRoot, state.microgRoot) } if (state.isFullyLoaded) { val unsafeEnabled = settings.isUnsafeConfigurationEnabled() val microgHasData = state.microgUser != null || (unsafeEnabled && state.microgRoot != null) val bareAospHasData = state.bareAospUser != null || (unsafeEnabled && state.bareAospRoot != null) mBinding.microgRow.isVisible = microgHasData mBinding.bareAospRow.isVisible = bareAospHasData mBinding.shareButton.isEnabled = state.microgUser != null || state.bareAospUser != null } if (state.iconUrl != null && !iconReady) { iconReady = true val needsCount = !state.isFullyLoaded if (state.iconUrl.isNotEmpty()) { Glide.with(requireContext().applicationContext) .load(state.iconUrl) .listener(object : RequestListener { override fun onResourceReady( resource: Drawable, model: Any, target: Target?, dataSource: DataSource, isFirstResource: Boolean ): Boolean { if (needsCount) mViewModel.onIconDisplayed() return false } override fun onLoadFailed( e: GlideException?, model: Any?, target: Target, isFirstResource: Boolean ): Boolean { if (needsCount) mViewModel.onIconDisplayed() return false } }) .into(mBinding.image) } else { if (needsCount) mViewModel.onIconDisplayed() } } } } } private fun renderEvaluation( imageView: android.widget.ImageView, evaluation: com.klee.sapio.domain.model.Evaluation? ) { if (evaluation != null) { imageView.setImageResource(Rating.create(evaluation.rating).drawable) imageView.visibility = View.VISIBLE } else { imageView.setImageDrawable(null) imageView.visibility = View.INVISIBLE } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { imageView.tooltipText = evaluation?.let { computeTooltip(it) } } } private fun computeTooltip(evaluation: com.klee.sapio.domain.model.Evaluation): String { val ratingText = when (evaluation.rating) { Rating.GOOD -> getString(R.string.good) Rating.AVERAGE -> getString(R.string.average) Rating.BAD -> getString(R.string.bad) else -> getString(R.string.unknown) } val date = evaluation.updatedAt?.let { DateFormat.getDateInstance().format(it) } return if (date == null) ratingText else "$date - $ratingText" } private fun startTakingScreenshot(appName: String, packageName: String) { viewLifecycleOwner.lifecycleScope.launch { val state = mViewModel.uiState.value val icon = saveImageToFile( requireContext(), state.iconUrl.orEmpty() ) val sharedEvaluation = SharedEvaluation( appName, packageName, icon, state.microgUser?.rating ?: 0, state.bareAospUser?.rating ?: 0, ) share(takeScreenshot(sharedEvaluation), appName) } } private fun takeScreenshot(sharedEvaluation: SharedEvaluation): Bitmap { return composeToBitmap(requireContext(), SCREENSHOT_WIDTH_DP, SCREENSHOT_HEIGHT_DP) { ShareScreenshot(sharedEvaluation) } } private suspend fun saveImageToFile( context: Context, url: String ): Bitmap = suspendCancellableCoroutine { continuation -> val target = object : CustomTarget() { override fun onResourceReady( resource: Bitmap, transition: Transition? ) { continuation.resume(resource) } override fun onLoadCleared(placeholder: Drawable?) { continuation.resumeWithException(Exception("Failed to load image")) } } Glide.with(requireContext().applicationContext) .asBitmap() .load(url) .into(target) continuation.invokeOnCancellation { Glide.with(context).clear(target) } } private fun composeToBitmap( context: Context, widthDp: Int, heightDp: Int, scaleFactor: Float = 2f, composable: @Composable () -> Unit, ): Bitmap { val displayMetrics = context.resources.displayMetrics val widthPx = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, widthDp.toFloat(), displayMetrics ).toInt() val heightPx = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, heightDp.toFloat(), displayMetrics ).toInt() val composeView = ComposeView(context).apply { setLayerType(View.LAYER_TYPE_SOFTWARE, null) setContent { composable() } layoutParams = ViewGroup.LayoutParams(widthPx, heightPx) } mBinding.bitmapContainer.addView(composeView) composeView.measure( View.MeasureSpec.makeMeasureSpec(widthPx, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(heightPx, View.MeasureSpec.EXACTLY) ) composeView.layout(0, 0, composeView.measuredWidth, composeView.measuredHeight) val bitmap = createBitmap( (composeView.width * scaleFactor).toInt(), (composeView.height * scaleFactor).toInt() ) val canvas = Canvas(bitmap) canvas.scale(scaleFactor, scaleFactor) composeView.draw(canvas) mBinding.bitmapContainer.removeView(composeView) return bitmap } private fun share(bitmap: Bitmap, appName: String) { val contentValues = ContentValues().apply { put(Media.DISPLAY_NAME, "screenshot_${System.currentTimeMillis()}") put(Media.DESCRIPTION, getString(R.string.share_android_compatibility, appName)) put(Media.MIME_TYPE, "image/jpeg") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { put( Media.RELATIVE_PATH, "${Environment.DIRECTORY_PICTURES}/${Environment.DIRECTORY_SCREENSHOTS}" ) } } shareImage = requireContext().contentResolver.insert(Media.EXTERNAL_CONTENT_URI, contentValues) ?: return try { requireContext().contentResolver.openOutputStream(shareImage!!)?.use { outputStream -> bitmap.compress(Bitmap.CompressFormat.JPEG, COMPRESSION_QUALITY, outputStream) } } catch (exception: IOException) { Log.e(TAG, "Failed to share matrix", exception) } val shareIntent = Intent(Intent.ACTION_SEND).apply { type = "image/*" putExtra(Intent.EXTRA_STREAM, shareImage) putExtra( Intent.EXTRA_TEXT, getString(R.string.share_android_compatibility_text, appName) ) } shareLauncher.launch(Intent.createChooser(shareIntent, "Share")) } override fun onDestroyView() { super.onDestroyView() iconReady = false shareImage?.let { requireContext().contentResolver.delete(it, null, null) shareImage = null } _binding = null } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/view/FeedAppAdapter.kt ================================================ package com.klee.sapio.ui.view import android.content.Context import android.content.res.ColorStateList import android.os.Build import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import com.klee.sapio.R import com.klee.sapio.databinding.FeedAppCardBinding import com.klee.sapio.domain.AppSettings import com.klee.sapio.domain.model.Evaluation import com.klee.sapio.domain.model.UserType import com.klee.sapio.ui.model.Label import com.klee.sapio.ui.model.Rating import java.text.SimpleDateFormat import java.util.Locale class FeedAppAdapter( private val mContext: Context, private var mSettings: AppSettings, private val onAppSelected: (packageName: String, appName: String) -> Unit ) : ListAdapter(DiffCallback) { companion object { const val DATE_FORMAT = "dd/MM/yyyy" private val DiffCallback = object : DiffUtil.ItemCallback() { override fun areItemsTheSame(oldItem: Evaluation, newItem: Evaluation): Boolean { return oldItem.packageName == newItem.packageName && oldItem.microg == newItem.microg && oldItem.secure == newItem.secure } override fun areContentsTheSame(oldItem: Evaluation, newItem: Evaluation): Boolean { return oldItem == newItem } } } inner class ViewHolder(val binding: FeedAppCardBinding) : RecyclerView.ViewHolder(binding.root) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = FeedAppCardBinding.inflate(LayoutInflater.from(parent.context), parent, false) return ViewHolder(binding) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val app = getItem(position) val element = holder.binding element.appName.text = app.name element.packageName.text = app.packageName val dateFormat = SimpleDateFormat(DATE_FORMAT, Locale.getDefault()) element.updatedDate.text = mContext.getString( R.string.updated_on, app.updatedAt?.let { dateFormat.format(it) } ) element.emoji.setImageResource(Rating.create(app.rating).drawable) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val microgLabel = Label.create(mContext, app.microg) val secureLabel = Label.create(mContext, app.secure) element.microG.text = microgLabel.text element.microG.backgroundTintList = ColorStateList.valueOf(microgLabel.color) element.secure.text = secureLabel.text element.secure.backgroundTintList = ColorStateList.valueOf(secureLabel.color) if (mSettings.getUnsafeConfigurationLevel() == UserType.UNSAFE) { element.secure.visibility = View.VISIBLE } else { element.secure.visibility = View.GONE } } Glide.with(mContext.applicationContext).clear(holder.binding.image) val iconUrl = app.iconUrl if (!iconUrl.isNullOrEmpty()) { Glide.with(mContext.applicationContext) .load(iconUrl) .diskCacheStrategy(DiskCacheStrategy.ALL) .into(holder.binding.image) } holder.itemView.setOnClickListener { onAppSelected(app.packageName, app.name) } } override fun onViewRecycled(holder: ViewHolder) { super.onViewRecycled(holder) Glide.with(mContext.applicationContext).clear(holder.binding.image) } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/view/FeedFragment.kt ================================================ package com.klee.sapio.ui.view import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.klee.sapio.databinding.FragmentMainBinding import com.klee.sapio.domain.AppSettings import com.klee.sapio.ui.viewmodel.FeedViewModel import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.Job import kotlinx.coroutines.launch import javax.inject.Inject @AndroidEntryPoint class FeedFragment : Fragment() { companion object { private const val LOAD_MORE_THRESHOLD = 3 } @Inject lateinit var mSettings: AppSettings private lateinit var mBinding: FragmentMainBinding private lateinit var mFeedAppAdapter: FeedAppAdapter private val mViewModel by activityViewModels() private var fetchJob: Job? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { mBinding = FragmentMainBinding.inflate(inflater, container, false) mBinding.recyclerView.layoutManager = LinearLayoutManager(context) setupAdapter() collectFeed() mBinding.refreshView.setOnRefreshListener { mViewModel.refresh() } setupScrollListener() return mBinding.root } override fun onResume() { super.onResume() mViewModel.syncUnsafeConfiguration(mSettings.getUnsafeConfigurationLevel()) } private fun setupAdapter() { mFeedAppAdapter = FeedAppAdapter(requireContext(), mSettings) { packageName, appName -> (requireActivity() as MainActivity).navigateToEvaluations(packageName, appName) } mBinding.recyclerView.adapter = mFeedAppAdapter } private fun setupScrollListener() { mBinding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { if (dy <= 0) return val layoutManager = recyclerView.layoutManager as? LinearLayoutManager ?: return val lastVisible = layoutManager.findLastVisibleItemPosition() val total = layoutManager.itemCount if (total > 0 && lastVisible >= total - LOAD_MORE_THRESHOLD) { mViewModel.loadNextPage() } } }) } private fun collectFeed() { fetchJob?.cancel() fetchJob = viewLifecycleOwner.lifecycleScope.launch { mViewModel.uiState.collect { state -> mFeedAppAdapter.submitList(state.items) { if (!state.isLoading && !state.isLoadingMore) { loadMoreIfNeeded() } } val isInitialLoad = state.isLoading && state.items.isEmpty() mBinding.progressBar.visibility = if (isInitialLoad) View.VISIBLE else View.GONE mBinding.refreshView.isRefreshing = false } } } private fun loadMoreIfNeeded() { mBinding.recyclerView.post { val layoutManager = mBinding.recyclerView.layoutManager as? LinearLayoutManager ?: return@post val lastVisible = layoutManager.findLastVisibleItemPosition() val total = layoutManager.itemCount if (total > 0 && lastVisible >= total - LOAD_MORE_THRESHOLD) { mViewModel.loadNextPage() } } } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/view/FragmentAdapter.kt ================================================ package com.klee.sapio.ui.view import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.lifecycle.Lifecycle import androidx.viewpager2.adapter.FragmentStateAdapter class FragmentAdapter(fragmentManager: FragmentManager, lifecycle: Lifecycle) : FragmentStateAdapter(fragmentManager, lifecycle) { private val fragments: HashMap = hashMapOf( 0 to FeedFragment(), 1 to SearchFragment(), 2 to ContributeFragment() ) override fun getItemCount(): Int { return fragments.size } override fun createFragment(position: Int): Fragment { return fragments[position]!! } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/view/LoadingFragment.kt ================================================ package com.klee.sapio.ui.view import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import com.klee.sapio.R import com.klee.sapio.databinding.FragmentLoadingBinding import com.klee.sapio.ui.state.EvaluateEvent import com.klee.sapio.ui.viewmodel.LoadingViewModel import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch @AndroidEntryPoint class LoadingFragment : Fragment() { private val mViewModel by viewModels() private lateinit var mBinding: FragmentLoadingBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { mBinding = FragmentLoadingBinding.inflate(inflater, container, false) val packageName = arguments?.getString("package").orEmpty() val appName = arguments?.getString("name").orEmpty() val rating = arguments?.getInt("rating") ?: 0 mViewModel.submit(packageName, appName, rating) viewLifecycleOwner.lifecycleScope.launch { mViewModel.events.collect { event -> when (event) { is EvaluateEvent.NavigateToSuccess -> { val bundle = Bundle().apply { putString("package", event.packageName) putString("name", event.appName) } findNavController().navigate(R.id.action_loadingFragment_to_successFragment, bundle) } is EvaluateEvent.ShowError -> { Toast.makeText(context, getString(R.string.upload_error), Toast.LENGTH_LONG).show() findNavController().popBackStack() } } } } return mBinding.root } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/view/MainActivity.kt ================================================ package com.klee.sapio.ui.view import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import android.view.ViewGroup import androidx.activity.OnBackPressedCallback import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import androidx.core.view.updateLayoutParams import androidx.activity.viewModels import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import com.klee.sapio.R import com.klee.sapio.databinding.ActivityMainBinding import com.klee.sapio.ui.viewmodel.AppEvaluationsViewModel import com.klee.sapio.ui.viewmodel.ChooseAppViewModel import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : AppCompatActivity() { private lateinit var mBinding: ActivityMainBinding private val mEvaluationsViewModel by viewModels() private val mChooseAppViewModel by viewModels() private val notificationPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { } companion object { const val DONATE_URL = "https://ko-fi.com/jnthnkl" const val EXTRA_PACKAGE_NAME = "packageName" const val EXTRA_APP_NAME = "appName" const val EXTRA_SHARE_IMMEDIATELY = "shareImmediately" const val EXTRA_NOTIFICATION_ID = "notificationId" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mBinding = ActivityMainBinding.inflate(layoutInflater) setContentView(mBinding.root) requestNotificationPermissionIfNeeded() mChooseAppViewModel.uiState if (savedInstanceState == null) { displayFragment(FeedFragment()) handleDeepLinkIntent(intent) } handleEdgeToEdgeInsets() onBackPressedDispatcher.addCallback( this, object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { if (supportFragmentManager.backStackEntryCount > 0) { supportFragmentManager.popBackStack() } else if (mBinding.bottomNavigation.selectedItemId != R.id.feed) { mBinding.bottomNavigation.selectedItemId = R.id.feed } else { finish() } } } ) mBinding.bottomNavigation.setOnItemSelectedListener { item -> when (item.itemId) { R.id.feed -> displayFragment(FeedFragment()) R.id.search -> displayFragment(SearchFragment()) R.id.my_apps -> displayFragment(MyAppsFragment()) R.id.contribute -> displayFragment(ContributeFragment()) R.id.options -> displayFragment(PreferencesFragment()) } return@setOnItemSelectedListener true } } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) handleDeepLinkIntent(intent) } private fun handleDeepLinkIntent(intent: Intent) { val packageName = intent.getStringExtra(EXTRA_PACKAGE_NAME) ?: return val appName = intent.getStringExtra(EXTRA_APP_NAME).orEmpty() val shareImmediately = intent.getBooleanExtra(EXTRA_SHARE_IMMEDIATELY, false) val notificationId = intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1) navigateToEvaluations(packageName, appName, shareImmediately, notificationId) } fun navigateToAbout() { supportFragmentManager.beginTransaction() .replace(R.id.fragment_container, AboutFragment()) .addToBackStack(null) .commit() } fun navigateToContribute() { mBinding.bottomNavigation.selectedItemId = R.id.contribute } fun navigateToEvaluations( packageName: String, appName: String, shareImmediately: Boolean = false, notificationId: Int = -1 ) { mEvaluationsViewModel.listEvaluations(packageName) val fragment = EvaluationsFragment.newInstance(packageName, appName, shareImmediately, notificationId) supportFragmentManager.beginTransaction() .replace(R.id.fragment_container, fragment) .addToBackStack(null) .commit() } private fun displayFragment(fragment: Fragment) { supportFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE) supportFragmentManager.beginTransaction().replace(R.id.fragment_container, fragment).commit() } private fun handleEdgeToEdgeInsets() { ViewCompat.setOnApplyWindowInsetsListener(mBinding.root) { v, windowInsets -> val bars = windowInsets.getInsets( WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.displayCutout() ) val ime = windowInsets.getInsets(WindowInsetsCompat.Type.ime()) v.updateLayoutParams { bottomMargin = maxOf(bars.bottom, ime.bottom) leftMargin = bars.left rightMargin = bars.right topMargin = bars.top } WindowInsetsCompat.CONSUMED } } private fun requestNotificationPermissionIfNeeded() { if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) { return } val permission = Manifest.permission.POST_NOTIFICATIONS val isGranted = ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED if (!isGranted) { notificationPermissionLauncher.launch(permission) } } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/view/MyAppsAdapter.kt ================================================ package com.klee.sapio.ui.view import android.content.Context import android.content.pm.PackageManager import android.os.Build import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.klee.sapio.databinding.MyAppCardBinding import com.klee.sapio.ui.model.InstalledAppWithRating import com.klee.sapio.ui.model.Rating class MyAppsAdapter( private val mContext: Context, private val onAppSelected: (packageName: String, appName: String) -> Unit, private val onContribute: () -> Unit ) : ListAdapter(DiffCallback) { companion object { private val DiffCallback = object : DiffUtil.ItemCallback() { override fun areItemsTheSame( oldItem: InstalledAppWithRating, newItem: InstalledAppWithRating ): Boolean { return oldItem.installedApp.packageName == newItem.installedApp.packageName } override fun areContentsTheSame( oldItem: InstalledAppWithRating, newItem: InstalledAppWithRating ): Boolean { return oldItem == newItem } } } inner class ViewHolder(val binding: MyAppCardBinding) : RecyclerView.ViewHolder(binding.root) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = MyAppCardBinding.inflate( LayoutInflater.from(parent.context), parent, false ) return ViewHolder(binding) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = getItem(position) val element = holder.binding element.appName.text = item.installedApp.name element.packageName.text = item.installedApp.packageName try { val pm = holder.itemView.context.packageManager val appInfo = pm.getApplicationInfo(item.installedApp.packageName, 0) val icon = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { appInfo.loadUnbadgedIcon(pm) } else { appInfo.loadIcon(pm) } element.image.setImageDrawable(icon) } catch (e: PackageManager.NameNotFoundException) { // leave default } val rating = item.evaluation?.rating element.infoIcon.visibility = View.VISIBLE if (rating != null) { element.emoji.setImageResource(Rating.create(rating).drawable) element.emoji.visibility = View.VISIBLE element.noRatingIcon.visibility = View.GONE } else { element.emoji.visibility = View.GONE element.noRatingIcon.visibility = View.VISIBLE } holder.itemView.setOnClickListener { if (item.evaluation != null) { onAppSelected(item.installedApp.packageName, item.installedApp.name) } else { onContribute() } } } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/view/MyAppsFragment.kt ================================================ package com.klee.sapio.ui.view import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import com.klee.sapio.databinding.FragmentMyAppsBinding import com.klee.sapio.ui.viewmodel.MyAppsViewModel import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch @AndroidEntryPoint class MyAppsFragment : Fragment() { private lateinit var mBinding: FragmentMyAppsBinding private lateinit var mAdapter: MyAppsAdapter private val mViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { mBinding = FragmentMyAppsBinding.inflate(inflater, container, false) mBinding.recyclerView.layoutManager = LinearLayoutManager(context) mAdapter = MyAppsAdapter( requireContext(), onAppSelected = { packageName, appName -> (requireActivity() as MainActivity).navigateToEvaluations(packageName, appName) }, onContribute = { (requireActivity() as MainActivity).navigateToContribute() } ) mBinding.recyclerView.adapter = mAdapter mBinding.swipeRefreshLayout.setOnRefreshListener { mViewModel.loadApps(forceRefresh = true) } collectState() mViewModel.loadApps() return mBinding.root } private fun collectState() { viewLifecycleOwner.lifecycleScope.launch { mViewModel.uiState.collect { state -> if (state.isLoading) { mAdapter.submitList(emptyList()) mBinding.progressBar.visibility = View.VISIBLE } else { mAdapter.submitList(state.items) mBinding.progressBar.visibility = View.GONE } mBinding.recyclerView.visibility = if (state.isLoading) View.GONE else View.VISIBLE mBinding.swipeRefreshLayout.isRefreshing = false } } } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/view/PreferencesFragment.kt ================================================ package com.klee.sapio.ui.view import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.View import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import androidx.core.view.updatePadding import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import com.klee.sapio.R class PreferencesFragment : PreferenceFragmentCompat() { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.preferences, rootKey) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) ViewCompat.setOnApplyWindowInsetsListener(view) { v, windowInsets -> val bars = windowInsets.getInsets( WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.displayCutout() ) v.updatePadding( left = bars.left, right = bars.right, top = bars.top, bottom = bars.bottom ) WindowInsetsCompat.CONSUMED } setupPreferenceClickListeners() } private fun setupPreferenceClickListeners() { findPreference("github_star_preference")?.setOnPreferenceClickListener { val githubUrl = getString(R.string.github_url) val intent = Intent(Intent.ACTION_VIEW, Uri.parse(githubUrl)) startActivity(intent) true } findPreference("about_preference")?.setOnPreferenceClickListener { (requireActivity() as MainActivity).navigateToAbout() true } findPreference("donate_preference")?.setOnPreferenceClickListener { val donateUrl = "https://ko-fi.com/jnthnkl" val intent = Intent(Intent.ACTION_VIEW, Uri.parse(donateUrl)) startActivity(intent) true } } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/view/SearchAppAdapter.kt ================================================ package com.klee.sapio.ui.view import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import com.klee.sapio.databinding.SearchAppCardBinding import com.klee.sapio.domain.model.Evaluation class SearchAppAdapter( private val mContext: Context, private val onAppSelected: (packageName: String, appName: String) -> Unit ) : ListAdapter(DiffCallback) { companion object { private val DiffCallback = object : DiffUtil.ItemCallback() { override fun areItemsTheSame(oldItem: Evaluation, newItem: Evaluation): Boolean { return oldItem.packageName == newItem.packageName && oldItem.microg == newItem.microg && oldItem.secure == newItem.secure } override fun areContentsTheSame(oldItem: Evaluation, newItem: Evaluation): Boolean { return oldItem == newItem } } } inner class ViewHolder(val binding: SearchAppCardBinding) : RecyclerView.ViewHolder(binding.root) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = SearchAppCardBinding.inflate( LayoutInflater.from(parent.context), parent, false ) return ViewHolder(binding) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val app = getItem(position) val element = holder.binding element.appName.text = app.name element.packageName.text = app.packageName Glide.with(mContext.applicationContext).clear(holder.binding.image) val iconUrl = app.iconUrl if (!iconUrl.isNullOrEmpty()) { Glide.with(mContext.applicationContext) .load(iconUrl) .diskCacheStrategy(DiskCacheStrategy.ALL) .into(holder.binding.image) } holder.itemView.setOnClickListener { onAppSelected(app.packageName, app.name) } } override fun onViewRecycled(holder: ViewHolder) { super.onViewRecycled(holder) Glide.with(mContext.applicationContext).clear(holder.binding.image) } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/view/SearchFragment.kt ================================================ package com.klee.sapio.ui.view import android.content.Context import android.graphics.PorterDuff import android.os.Build import android.os.Bundle import android.os.Handler import android.os.Looper import android.text.Editable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import androidx.core.content.ContextCompat import androidx.core.widget.addTextChangedListener import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import com.google.android.material.R import com.klee.sapio.databinding.FragmentSearchBinding import com.klee.sapio.ui.state.SearchUiState import com.klee.sapio.ui.viewmodel.SearchViewModel import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.Job import kotlinx.coroutines.launch @AndroidEntryPoint class SearchFragment : Fragment() { private lateinit var mBinding: FragmentSearchBinding private lateinit var mSearchAppAdapter: SearchAppAdapter private val mViewModel by viewModels() private var searchJob: Job? = null private lateinit var mHandler: Handler override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { mBinding = FragmentSearchBinding.inflate(inflater, container, false) mBinding.recyclerView.layoutManager = LinearLayoutManager(context) mBinding.recyclerView.visibility = View.INVISIBLE mHandler = Handler(Looper.getMainLooper()) mSearchAppAdapter = SearchAppAdapter(requireContext()) { packageName, appName -> (requireActivity() as MainActivity).navigateToEvaluations(packageName, appName) } mBinding.recyclerView.adapter = mSearchAppAdapter mBinding.editTextSearch.addTextChangedListener { editable -> onTextChanged(editable) } setupClearButton() setSearchIconsColor() collectSearch() return mBinding.root } private fun onTextChanged(editable: Editable?) { val text = editable?.trim().toString() searchJob?.cancel() searchJob = viewLifecycleOwner.lifecycleScope.launch { mViewModel.searchApplication(text, this@SearchFragment::onNetworkError) } } private fun collectSearch() { viewLifecycleOwner.lifecycleScope.launch { mViewModel.uiState.collect { state -> renderState(state) } } } private fun renderState(state: SearchUiState) { mSearchAppAdapter.submitList(state.items) showResults(state.query.isNotEmpty() && state.items.isNotEmpty()) } private fun setupClearButton() { mBinding.editTextSearch.addTextChangedListener { text -> mBinding.clearSearch.visibility = if (text?.isNotEmpty() == true) View.VISIBLE else View.GONE } mBinding.clearSearch.setOnClickListener { mBinding.editTextSearch.text?.clear() } } private fun setSearchIconsColor() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { mBinding.searchIcon.setColorFilter( ContextCompat.getColor( requireContext(), R.color.material_dynamic_primary80 ), PorterDuff.Mode.SRC_IN ) mBinding.searchIconBig.setColorFilter( ContextCompat.getColor( requireContext(), R.color.material_dynamic_primary80 ), PorterDuff.Mode.SRC_IN ) } } override fun onResume() { super.onResume() showKeyboard() } private fun onNetworkError() { // Nothing for now } private fun showResults(visible: Boolean) { if (visible) { mBinding.recyclerView.visibility = View.VISIBLE mBinding.emptyState.visibility = View.GONE } else { mBinding.recyclerView.visibility = View.INVISIBLE mBinding.emptyState.visibility = View.VISIBLE } } private fun showKeyboard() { mBinding.editTextSearch.post { if (!isAdded) return@post mBinding.editTextSearch.requestFocus() val inputMethodManager = requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager inputMethodManager.showSoftInput( mBinding.editTextSearch, InputMethodManager.SHOW_IMPLICIT ) } } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/view/ShareComposable.kt ================================================ package com.klee.sapio.ui.view import android.annotation.SuppressLint import android.graphics.Bitmap import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredHeight import androidx.compose.foundation.layout.requiredWidth import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.klee.sapio.R import com.klee.sapio.ui.model.Rating import com.klee.sapio.ui.model.SharedEvaluation import java.time.LocalDate import java.time.format.DateTimeFormatter @SuppressLint("NewApi") @Composable fun ShareScreenshot( sharedEvaluation: SharedEvaluation, ) { Box( modifier = Modifier .requiredWidth(200.dp) .requiredHeight(115.dp) .background(color = Gray) ) { Column( modifier = Modifier .fillMaxSize() .padding(start = 12.dp, end = 12.dp, top = 8.dp, bottom = 4.dp) ) { Box( modifier = Modifier.fillMaxWidth() ) { Column( modifier = Modifier.align(Alignment.TopCenter), horizontalAlignment = Alignment.CenterHorizontally ) { Text( stringResource(R.string.android_compatibility_matrix), style = TextStyle( color = Color.White, fontSize = 8.5.sp ) ) Text( stringResource(R.string.android_compatibility_subtitle), style = TextStyle( color = Color.White.copy(alpha = 0.7f), fontSize = 5.sp ) ) } Image( painter = painterResource(R.drawable.ic_launcher_foreground), modifier = Modifier .size(18.dp) .align(Alignment.TopEnd), contentDescription = "Sapio icon", ) } Spacer(modifier = Modifier.height(8.dp)) Box( modifier = Modifier.fillMaxWidth() ) { Box( modifier = Modifier .size(44.dp) .background( color = Blue200.copy(alpha = 0.18f), shape = CircleShape ) .align(Alignment.CenterStart), contentAlignment = Alignment.Center ) { Image( bitmap = sharedEvaluation.icon.asImageBitmap(), contentDescription = null, modifier = Modifier .clip(CircleShape) .size(36.dp), ) } Column( modifier = Modifier .align(Alignment.Center) .padding(horizontal = 48.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Text( sharedEvaluation.name, style = TextStyle( color = Color.White.copy(alpha = 0.9f), fontSize = 9.sp ) ) Text( sharedEvaluation.packageName, style = TextStyle( color = Color.White.copy(alpha = 0.65f), fontSize = 5.sp ), maxLines = 1, overflow = TextOverflow.Ellipsis ) Spacer(modifier = Modifier.height(6.dp)) val availableRatings = buildList { if (hasRating(sharedEvaluation.ratingMicrog)) { add("microG" to sharedEvaluation.ratingMicrog) } if (hasRating(sharedEvaluation.ratingBareAOSP)) { add("bareAOSP" to sharedEvaluation.ratingBareAOSP) } } val pillHeight = 14.dp val pillSpacing = 3.dp val pillStackHeight = (pillHeight * 2) + pillSpacing val pillAreaHeight = if (availableRatings.isEmpty()) 0.dp else pillStackHeight Box( modifier = Modifier .height(pillAreaHeight), contentAlignment = Alignment.CenterStart ) { when (availableRatings.size) { 1 -> { val (label, rating) = availableRatings[0] RatingPill( label = label, rating = rating, modifier = Modifier.height(pillHeight) ) } 2 -> { Column { availableRatings.forEachIndexed { index, (label, rating) -> RatingPill( label = label, rating = rating, modifier = Modifier.height(pillHeight) ) if (index == 0) { Spacer(modifier = Modifier.height(pillSpacing)) } } } } } } } } Spacer(modifier = Modifier.weight(1f)) Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally ) { Row( verticalAlignment = Alignment.CenterVertically, ) { Text( stringResource(R.string.app_name), style = TextStyle( color = Color.White, fontSize = 5.5.sp ) ) } } Box( modifier = Modifier .fillMaxWidth() .padding(top = 2.dp) ) { Text( stringResource(R.string.support_privacy_focused_apps), style = TextStyle( color = Color.White.copy(alpha = 0.8f), fontSize = 4.sp ), modifier = Modifier.align(Alignment.Center) ) Text( LocalDate.now().format( DateTimeFormatter.ofPattern("dd/MM/yyyy") ), style = TextStyle( color = Color.White.copy(alpha = 0.8f), fontSize = 5.sp ), modifier = Modifier.align(Alignment.CenterEnd) ) } } } } @Composable private fun RatingPill( label: String, rating: Int, modifier: Modifier = Modifier, ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = modifier .background(Color.White.copy(alpha = 0.08f), shape = RoundedCornerShape(10.dp)) .padding(start = 7.dp, end = 7.dp, top = 3.dp, bottom = 3.dp) ) { Text( text = label, style = TextStyle( color = Color.White.copy(alpha = 0.9f), fontSize = 6.sp ), modifier = Modifier.width(40.dp), textAlign = TextAlign.Start ) Spacer(modifier = Modifier.width(4.dp)) val circleColor = when (rating) { Rating.GOOD -> Color(0xFF4CAF50) Rating.AVERAGE -> Color(0xFFFFC107) Rating.BAD -> Color(0xFFF44336) else -> Color.Transparent } Box( modifier = Modifier .size(7.dp) .background(circleColor, shape = CircleShape) ) } } private fun hasRating(rating: Int): Boolean { return rating == Rating.GOOD || rating == Rating.AVERAGE || rating == Rating.BAD } const val WIDTH = 5 const val HEIGHT = 5 @Preview @Composable fun ShareScreenshotPreview() { val sharedEvaluation = SharedEvaluation( "My great app", "my.great.app", Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.ARGB_8888), 1, 2 ) ShareScreenshot(sharedEvaluation) } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/view/SplashActivity.kt ================================================ package com.klee.sapio.ui.view import android.content.Intent import android.os.Build import android.os.Bundle import android.os.Handler import android.view.WindowManager import androidx.appcompat.app.AppCompatActivity import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import com.klee.sapio.databinding.ActivitySplashBinding class SplashActivity : AppCompatActivity() { companion object { const val SPLASH_DELAY_MS = 2000 } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val splashScreen = installSplashScreen() splashScreen.setKeepOnScreenCondition { Build.VERSION.SDK_INT >= Build.VERSION_CODES.S } window.setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN ) val binding = ActivitySplashBinding.inflate(layoutInflater) setContentView(binding.root) val delay = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) 0 else SPLASH_DELAY_MS Handler().postDelayed({ val intent = Intent(this@SplashActivity, MainActivity::class.java) startActivity(intent) finish() }, delay.toLong()) } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/view/SuccessFragment.kt ================================================ package com.klee.sapio.ui.view import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.lifecycleScope import com.klee.sapio.databinding.FragmentSuccessBinding import com.klee.sapio.ui.viewmodel.AppEvaluationsViewModel import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach @AndroidEntryPoint class SuccessFragment : Fragment() { private lateinit var mBinding: FragmentSuccessBinding private val mViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val packageName = arguments?.getString("package").orEmpty() val appName = arguments?.getString("name").orEmpty() mBinding = FragmentSuccessBinding.inflate(inflater, container, false) mBinding.emoji.text = "\uD83C\uDF89 \uD83E\uDD73" mViewModel.listEvaluations(packageName) mBinding.shareEvaluation.setOnClickListener { (requireActivity() as MainActivity).navigateToEvaluations( packageName, appName, shareImmediately = true ) } mViewModel.uiState.onEach { state -> mBinding.shareEvaluation.isEnabled = state.microgUser != null || state.bareAospUser != null }.launchIn(viewLifecycleOwner.lifecycleScope) return mBinding.root } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/view/ToastMessage.kt ================================================ package com.klee.sapio.ui.view import android.content.Context import android.widget.Toast object ToastMessage { fun showNetworkIssue(context: Context) { Toast.makeText( context, "Sapio's server cannot be reached.", Toast.LENGTH_LONG ).show() } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/view/WarningFragment.kt ================================================ package com.klee.sapio.ui.view import android.os.Build import android.os.Bundle import android.text.Html import android.text.method.LinkMovementMethod import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import com.klee.sapio.R import com.klee.sapio.databinding.FragmentWarningBinding import com.klee.sapio.domain.DeviceInfo import com.klee.sapio.domain.model.GmsType import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class WarningFragment : Fragment() { @Inject lateinit var mDeviceInfo: DeviceInfo private lateinit var mBinding: FragmentWarningBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { mBinding = FragmentWarningBinding.inflate(inflater, container, false) mBinding.reportAppDescription.text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Html.fromHtml(getString(R.string.warning_desc, AboutFragment.RATING_RULES), Html.FROM_HTML_MODE_LEGACY) } else { @Suppress("DEPRECATION") Html.fromHtml(getString(R.string.warning_desc, AboutFragment.RATING_RULES)) } mBinding.reportAppDescription.movementMethod = LinkMovementMethod.getInstance() mBinding.proceedButton.setOnClickListener { findNavController().navigate(R.id.action_warningFragment_to_chooseAppFragment) } mBinding.checkbox.setOnClickListener { updateProceedButton() } updateProceedButton() return mBinding.root } private fun updateProceedButton() { mBinding.proceedButton.isEnabled = mDeviceInfo.getGmsType() != GmsType.GOOGLE_PLAY_SERVICES && mBinding.checkbox.isChecked } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/viewmodel/AppEvaluationsViewModel.kt ================================================ package com.klee.sapio.ui.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.klee.sapio.domain.AppSettings import com.klee.sapio.domain.FetchAppEvaluationUseCase import com.klee.sapio.domain.FetchIconUrlUseCase import com.klee.sapio.domain.model.GmsType import com.klee.sapio.domain.model.UserType import com.klee.sapio.ui.state.AppEvaluationsUiState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class AppEvaluationsViewModel @Inject constructor( private val fetchAppEvaluationUseCase: FetchAppEvaluationUseCase, private val fetchIconUrlUseCase: FetchIconUrlUseCase, private val settings: AppSettings ) : ViewModel() { internal var ioDispatcher: CoroutineDispatcher = Dispatchers.IO private val _uiState = MutableStateFlow(AppEvaluationsUiState()) val uiState = _uiState.asStateFlow() private var loadingJob: Job? = null companion object { private const val FETCHES_WITH_UNSAFE = 5 private const val FETCHES_WITHOUT_UNSAFE = 3 } fun listEvaluations(packageName: String) { loadingJob?.cancel() _uiState.value = AppEvaluationsUiState() val expectedFetches = if (settings.isUnsafeConfigurationEnabled()) FETCHES_WITH_UNSAFE else FETCHES_WITHOUT_UNSAFE _uiState.update { it.copy(pendingCount = expectedFetches) } loadingJob = viewModelScope.launch { launch(ioDispatcher) { _uiState.update { it.copy( microgUser = fetchAppEvaluationUseCase( packageName, GmsType.MICROG, UserType.SECURE ).getOrNull(), pendingCount = it.pendingCount - 1 ) } } launch(ioDispatcher) { _uiState.update { it.copy( bareAospUser = fetchAppEvaluationUseCase( packageName, GmsType.BARE_AOSP, UserType.SECURE ).getOrNull(), pendingCount = it.pendingCount - 1 ) } } if (settings.isUnsafeConfigurationEnabled()) { launch(ioDispatcher) { _uiState.update { it.copy( microgRoot = fetchAppEvaluationUseCase( packageName, GmsType.MICROG, UserType.UNSAFE ).getOrNull(), pendingCount = it.pendingCount - 1 ) } } launch(ioDispatcher) { _uiState.update { it.copy( bareAospRoot = fetchAppEvaluationUseCase( packageName, GmsType.BARE_AOSP, UserType.UNSAFE ).getOrNull(), pendingCount = it.pendingCount - 1 ) } } } launch(ioDispatcher) { _uiState.update { it.copy(iconUrl = fetchIconUrlUseCase(packageName).getOrDefault("")) } } } } fun onIconDisplayed() { _uiState.update { it.copy(pendingCount = it.pendingCount - 1) } } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/viewmodel/ChooseAppViewModel.kt ================================================ package com.klee.sapio.ui.viewmodel import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import androidx.core.content.ContextCompat import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.klee.sapio.domain.CheckFdroidAvailabilityUseCase import com.klee.sapio.domain.InstalledApplicationsDataSource import com.klee.sapio.domain.model.InstalledApplication import com.klee.sapio.ui.state.ChooseAppUiState import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Semaphore import kotlinx.coroutines.sync.withPermit import kotlinx.coroutines.withContext import javax.inject.Inject @HiltViewModel class ChooseAppViewModel @Inject constructor( private val installedApplicationsDataSource: InstalledApplicationsDataSource, private val checkFdroidAvailabilityUseCase: CheckFdroidAvailabilityUseCase, @ApplicationContext private val context: Context ) : ViewModel() { private val _uiState = MutableStateFlow(ChooseAppUiState()) val uiState = _uiState.asStateFlow() private val packageReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (intent.action == Intent.ACTION_PACKAGE_ADDED || intent.action == Intent.ACTION_PACKAGE_REMOVED) { loadApps() } } } init { loadApps() val filter = IntentFilter().apply { addAction(Intent.ACTION_PACKAGE_ADDED) addAction(Intent.ACTION_PACKAGE_REMOVED) addDataScheme("package") } ContextCompat.registerReceiver(context, packageReceiver, filter, ContextCompat.RECEIVER_EXPORTED) } override fun onCleared() { super.onCleared() context.unregisterReceiver(packageReceiver) } private fun loadApps() { viewModelScope.launch { val allApps = withContext(Dispatchers.IO) { installedApplicationsDataSource.listInstalledApplications() } val filtered = filterFdroidApps(allApps) _uiState.update { it.copy(apps = filtered, isLoading = false) } } } private suspend fun filterFdroidApps(apps: List): List { val semaphore = Semaphore(PARALLEL_REQUESTS) return coroutineScope { apps.map { app -> async(Dispatchers.IO) { semaphore.withPermit { if (checkFdroidAvailabilityUseCase(app.packageName)) null else app } } }.awaitAll().filterNotNull() } } companion object { private const val PARALLEL_REQUESTS = 10 } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/viewmodel/EvaluateViewModel.kt ================================================ package com.klee.sapio.ui.viewmodel import androidx.lifecycle.ViewModel import com.klee.sapio.domain.DeviceInfo import com.klee.sapio.ui.state.EvaluateUiState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import javax.inject.Inject @HiltViewModel class EvaluateViewModel @Inject constructor( deviceInfo: DeviceInfo ) : ViewModel() { private val _uiState = MutableStateFlow( EvaluateUiState( gmsType = deviceInfo.getGmsType(), userType = deviceInfo.isUnsafe() ) ) val uiState = _uiState.asStateFlow() } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/viewmodel/FeedViewModel.kt ================================================ package com.klee.sapio.ui.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.klee.sapio.domain.ListLatestEvaluationsUseCase import com.klee.sapio.ui.state.FeedUiState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class FeedViewModel @Inject constructor( private val listLatestEvaluationsUseCase: ListLatestEvaluationsUseCase ) : ViewModel() { private var currentPage = 0 private var hasMorePages = true private var lastLoadedUnsafeLevel: Int? = null private val _uiState = MutableStateFlow(FeedUiState(isLoading = true)) val uiState = _uiState.asStateFlow() init { refresh() } fun syncUnsafeConfiguration(currentLevel: Int) { val last = lastLoadedUnsafeLevel if (last == null) { lastLoadedUnsafeLevel = currentLevel } else if (last != currentLevel) { lastLoadedUnsafeLevel = currentLevel refresh() } } fun refresh() { viewModelScope.launch { currentPage = 0 hasMorePages = true _uiState.update { it.copy(items = emptyList(), isLoading = true, isLoadingMore = false, hasError = false) } loadPage() } } fun loadNextPage() { val state = _uiState.value if (state.isLoading || state.isLoadingMore || !hasMorePages) return viewModelScope.launch { _uiState.update { it.copy(isLoadingMore = true) } loadPage() } } private suspend fun loadPage() { currentPage++ val result = listLatestEvaluationsUseCase(currentPage) if (result.isFailure) { _uiState.update { it.copy(isLoading = false, isLoadingMore = false, hasError = true) } return } val newItems = result.getOrDefault(emptyList()) _uiState.update { val combined = (it.items + newItems).distinctBy { item -> Triple(item.packageName, item.microg, item.secure) } hasMorePages = combined.size > it.items.size it.copy( items = combined, isLoading = false, isLoadingMore = false ) } } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/viewmodel/LoadingViewModel.kt ================================================ package com.klee.sapio.ui.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.klee.sapio.domain.EvaluateAppUseCase import com.klee.sapio.domain.InstalledApplicationsDataSource import com.klee.sapio.ui.state.EvaluateEvent import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class LoadingViewModel @Inject constructor( private val installedApplicationsDataSource: InstalledApplicationsDataSource, private val evaluateAppUseCase: EvaluateAppUseCase ) : ViewModel() { private val _events = MutableSharedFlow() val events = _events.asSharedFlow() fun submit(packageName: String, appName: String, rating: Int) { viewModelScope.launch { val app = installedApplicationsDataSource.getInstalledApplication(packageName) if (app == null) { _events.emit(EvaluateEvent.ShowError) return@launch } val result = evaluateAppUseCase(app, rating) if (result.isSuccess) { _events.emit(EvaluateEvent.NavigateToSuccess(packageName, appName)) } else { _events.emit(EvaluateEvent.ShowError) } } } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/viewmodel/MyAppsViewModel.kt ================================================ package com.klee.sapio.ui.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.klee.sapio.domain.CheckFdroidAvailabilityUseCase import com.klee.sapio.domain.DeviceAppCacheRepository import com.klee.sapio.domain.DeviceInfo import com.klee.sapio.domain.FetchAppEvaluationUseCase import com.klee.sapio.domain.InstalledApplicationsDataSource import com.klee.sapio.domain.model.CachedDeviceApp import com.klee.sapio.domain.model.Evaluation import com.klee.sapio.ui.model.InstalledAppWithRating import com.klee.sapio.ui.state.MyAppsUiState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Semaphore import kotlinx.coroutines.sync.withPermit import kotlinx.coroutines.withContext import java.util.concurrent.atomic.AtomicInteger import javax.inject.Inject @HiltViewModel class MyAppsViewModel @Inject constructor( private val installedApplicationsDataSource: InstalledApplicationsDataSource, private val fetchAppEvaluationUseCase: FetchAppEvaluationUseCase, private val checkFdroidAvailabilityUseCase: CheckFdroidAvailabilityUseCase, private val deviceInfo: DeviceInfo, private val deviceAppCacheRepository: DeviceAppCacheRepository ) : ViewModel() { private val _uiState = MutableStateFlow(MyAppsUiState()) val uiState = _uiState.asStateFlow() private var lastLoadTime: Long? = null private fun isCacheValid(timestamp: Long?): Boolean { val last = timestamp ?: return false return System.currentTimeMillis() - last < CACHE_VALIDITY_MS } fun loadApps(forceRefresh: Boolean = false) { if (_uiState.value.isLoading || _uiState.value.isRefreshing) return if (!forceRefresh && _uiState.value.items.isNotEmpty() && isCacheValid(lastLoadTime)) return viewModelScope.launch { if (forceRefresh) { _uiState.update { it.copy(isLoading = true, isRefreshing = true, progress = 0) } fetchFromWebAndSave() } else { _uiState.update { it.copy(isLoading = true, progress = 0) } val entities = withContext(Dispatchers.IO) { deviceAppCacheRepository.getAll() } val lastCachedAt = entities.maxOfOrNull { it.cachedAt } if (entities.isNotEmpty() && isCacheValid(lastCachedAt)) { val result = buildListFromEntities(entities) lastLoadTime = lastCachedAt _uiState.update { it.copy(items = result, isLoading = false) } } else { fetchFromWebAndSave() } } } } private suspend fun buildListFromEntities( entities: List ): List { val installedMap = withContext(Dispatchers.IO) { installedApplicationsDataSource.listInstalledApplications().associateBy { it.packageName } } val total = entities.size val result = mutableListOf() entities.forEachIndexed { index, entity -> val installedApp = installedMap[entity.packageName] ?: return@forEachIndexed val evaluation = entity.rating?.let { rating -> Evaluation( name = installedApp.name, packageName = entity.packageName, iconUrl = null, rating = rating, microg = 0, secure = 0, updatedAt = null, createdAt = null, publishedAt = null, versionName = null ) } result.add(InstalledAppWithRating(installedApp, evaluation)) _uiState.update { it.copy(progress = ((index + 1) * 100) / total) } } return result } private suspend fun fetchFromWebAndSave() { val gmsType = deviceInfo.getGmsType() val userType = deviceInfo.isUnsafe() val installedApps = withContext(Dispatchers.IO) { installedApplicationsDataSource.listInstalledApplications() } val total = installedApps.size val semaphore = Semaphore(PARALLEL_REQUESTS) val completed = AtomicInteger(0) val result = coroutineScope { installedApps.map { app -> async(Dispatchers.IO) { semaphore.withPermit { val isFdroid = checkFdroidAvailabilityUseCase(app.packageName) val item = if (!isFdroid) { val evaluation = fetchAppEvaluationUseCase( app.packageName, gmsType, userType ).getOrNull() InstalledAppWithRating(app, evaluation) } else { null } _uiState.update { state -> state.copy(progress = (completed.incrementAndGet() * 100) / total) } item } } }.awaitAll().filterNotNull() } val now = System.currentTimeMillis() val entities = result.map { item -> CachedDeviceApp( packageName = item.installedApp.packageName, rating = item.evaluation?.rating, cachedAt = now ) } withContext(Dispatchers.IO) { deviceAppCacheRepository.replaceAll(entities) } lastLoadTime = now _uiState.update { it.copy(items = result, isLoading = false, isRefreshing = false) } } companion object { private const val CACHE_VALIDITY_MS = 86_400_000L private const val PARALLEL_REQUESTS = 10 } } ================================================ FILE: app/src/main/java/com/klee/sapio/ui/viewmodel/SearchViewModel.kt ================================================ package com.klee.sapio.ui.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.klee.sapio.domain.SearchEvaluationUseCase import com.klee.sapio.ui.state.SearchUiState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class SearchViewModel @Inject constructor( private val searchEvaluationUseCase: SearchEvaluationUseCase ) : ViewModel() { private val _uiState = MutableStateFlow(SearchUiState()) val uiState = _uiState.asStateFlow() fun searchApplication(pattern: String, onError: () -> Unit) { _uiState.update { it.copy(query = pattern, isLoading = true, hasError = false) } viewModelScope.launch { val result = searchEvaluationUseCase(pattern) val list = result.getOrDefault(emptyList()) val hasError = result.isFailure if (list.isEmpty() || hasError) { onError.invoke() } _uiState.update { it.copy( items = list, isLoading = false, hasError = hasError ) } } } } ================================================ FILE: app/src/main/java/com/klee/sapio/work/CompatibilityCheckScheduler.kt ================================================ package com.klee.sapio.work import android.content.Context import androidx.work.Constraints import androidx.work.ExistingPeriodicWorkPolicy import androidx.work.NetworkType import androidx.work.PeriodicWorkRequestBuilder import androidx.work.WorkManager import java.util.concurrent.TimeUnit object CompatibilityCheckScheduler { private const val UNIQUE_WORK_NAME = "compatibility_check" private const val UNIQUE_WORK_NOW_NAME = "compatibility_check_now" private const val REPEAT_INTERVAL_DAYS = 7L private const val FLEX_INTERVAL_DAYS = 1L fun schedule(context: Context) { if (!WorkManager.isInitialized()) { return } val constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build() val request = PeriodicWorkRequestBuilder( REPEAT_INTERVAL_DAYS, TimeUnit.DAYS, FLEX_INTERVAL_DAYS, TimeUnit.DAYS ) .setConstraints(constraints) .build() WorkManager.getInstance(context) .enqueueUniquePeriodicWork( UNIQUE_WORK_NAME, ExistingPeriodicWorkPolicy.UPDATE, request ) } fun runNow(context: Context) { if (!WorkManager.isInitialized()) { return } val constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build() val request = androidx.work.OneTimeWorkRequestBuilder() .setConstraints(constraints) .build() WorkManager.getInstance(context) .enqueueUniqueWork( UNIQUE_WORK_NOW_NAME, androidx.work.ExistingWorkPolicy.REPLACE, request ) } } ================================================ FILE: app/src/main/java/com/klee/sapio/work/CompatibilityCheckWorker.kt ================================================ package com.klee.sapio.work import android.content.Context import androidx.work.CoroutineWorker import androidx.work.WorkerParameters import com.klee.sapio.domain.EvaluationRepository import com.klee.sapio.domain.DeviceInfo import com.klee.sapio.domain.InstalledApplicationsDataSource import com.klee.sapio.domain.model.InstalledApplication import com.klee.sapio.domain.model.GmsType import com.klee.sapio.domain.model.UserType import com.klee.sapio.ui.model.Rating import dagger.hilt.EntryPoint import dagger.hilt.InstallIn import dagger.hilt.android.EntryPointAccessors import dagger.hilt.components.SingletonComponent import kotlin.random.Random class CompatibilityCheckWorker( appContext: Context, params: WorkerParameters ) : CoroutineWorker(appContext, params) { override suspend fun doWork(): Result { val entryPoint = EntryPointAccessors.fromApplication( applicationContext, CompatibilityWorkerEntryPoint::class.java ) val deviceConfiguration = entryPoint.deviceConfiguration() val gmsType = deviceConfiguration.getGmsType() if (gmsType == GmsType.GOOGLE_PLAY_SERVICES) { return Result.success() } val installedApps = entryPoint.installedApplicationsRepository() .listInstalledApplications() val evaluationRepository = entryPoint.evaluationRepository() val userType = UserType.SECURE val badApps = mutableListOf() val averageApps = mutableListOf() for (app in installedApps) { when { isBadCompatibility(evaluationRepository, app, gmsType, userType) -> { badApps.add(app) } isAverageCompatibility(evaluationRepository, app, gmsType, userType) -> { averageApps.add(app) } } } if (badApps.isNotEmpty()) { val badApp = badApps[Random.nextInt(badApps.size)] CompatibilityNotificationManager(applicationContext).show(badApp) } else if (averageApps.isNotEmpty()) { val averageApp = averageApps[Random.nextInt(averageApps.size)] CompatibilityNotificationManager(applicationContext).show(averageApp) } return Result.success() } private suspend fun isBadCompatibility( evaluationRepository: EvaluationRepository, app: InstalledApplication, gmsType: Int, userType: Int ): Boolean { val evaluation = evaluationRepository.fetchEvaluation(app.packageName, gmsType, userType).getOrNull() return evaluation?.rating == Rating.BAD } private suspend fun isAverageCompatibility( evaluationRepository: EvaluationRepository, app: InstalledApplication, gmsType: Int, userType: Int ): Boolean { val evaluation = evaluationRepository.fetchEvaluation(app.packageName, gmsType, userType).getOrNull() return evaluation?.rating == Rating.AVERAGE } } @EntryPoint @InstallIn(SingletonComponent::class) interface CompatibilityWorkerEntryPoint { fun installedApplicationsRepository(): InstalledApplicationsDataSource fun evaluationRepository(): EvaluationRepository fun deviceConfiguration(): DeviceInfo } ================================================ FILE: app/src/main/java/com/klee/sapio/work/CompatibilityNotificationManager.kt ================================================ package com.klee.sapio.work import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.graphics.Bitmap import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.graphics.drawable.toBitmap import com.klee.sapio.R import com.klee.sapio.domain.model.InstalledApplication import com.klee.sapio.ui.view.MainActivity class CompatibilityNotificationManager( private val context: Context ) { fun show(app: InstalledApplication) { notify(app) } private fun notify(app: InstalledApplication) { val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager ensureChannel(notificationManager) val pendingIntent = createEvaluationPendingIntent(app, shareImmediately = false) val sharePendingIntent = createEvaluationPendingIntent(app, shareImmediately = true) val notification = buildNotification(app, pendingIntent, sharePendingIntent) notificationManager.notify(NOTIFICATION_ID, notification) } private fun ensureChannel(notificationManager: NotificationManager) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { return } val channel = NotificationChannel( CHANNEL_ID, context.getString(R.string.compatibility_check_channel_name), NotificationManager.IMPORTANCE_DEFAULT ).apply { description = context.getString(R.string.compatibility_check_channel_description) } notificationManager.createNotificationChannel(channel) } private fun createEvaluationPendingIntent( app: InstalledApplication, shareImmediately: Boolean ): PendingIntent { val intent = Intent(context, MainActivity::class.java).apply { putExtra(MainActivity.EXTRA_PACKAGE_NAME, app.packageName) putExtra(MainActivity.EXTRA_APP_NAME, app.name) if (shareImmediately) { putExtra(MainActivity.EXTRA_SHARE_IMMEDIATELY, true) putExtra(MainActivity.EXTRA_NOTIFICATION_ID, NOTIFICATION_ID) } flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP } val requestCode = if (shareImmediately) { app.packageName.hashCode() + 1 } else { app.packageName.hashCode() } return PendingIntent.getActivity( context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) } private fun getAppIcon(packageName: String): Bitmap? { return try { context.packageManager.getApplicationIcon(packageName).toBitmap() } catch (e: PackageManager.NameNotFoundException) { null } } private fun buildNotification( app: InstalledApplication, pendingIntent: PendingIntent, sharePendingIntent: PendingIntent ) = NotificationCompat.Builder(context, CHANNEL_ID) .setSmallIcon(R.drawable.ic_notification_info) .apply { val icon = getAppIcon(app.packageName) if (icon != null) { setLargeIcon(icon) } } .setContentTitle(context.getString(R.string.compatibility_check_notification_title)) .setContentText( context.getString( R.string.compatibility_check_notification_body, app.name ) ) .setStyle( NotificationCompat.BigTextStyle().bigText( context.getString( R.string.compatibility_check_notification_body, app.name ) ) ) .setAutoCancel(false) .setContentIntent(pendingIntent) .addAction( android.R.drawable.ic_menu_share, context.getString(R.string.compatibility_check_notification_share_action), sharePendingIntent ) .build() private companion object { const val CHANNEL_ID = "compatibility_check" const val NOTIFICATION_ID = 2201 } } ================================================ FILE: app/src/main/res/drawable/bg_label_rounded.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_close.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_info_background.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_launcher_foreground.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_notification_info.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_phone.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_settings.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_status_green.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_status_red.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_status_yellow.xml ================================================ ================================================ FILE: app/src/main/res/drawable-anydpi/ic_add.xml ================================================ ================================================ FILE: app/src/main/res/drawable-anydpi/ic_search.xml ================================================ ================================================ FILE: app/src/main/res/drawable-anydpi/ic_settings.xml ================================================ ================================================ FILE: app/src/main/res/drawable-v33/ic_launcher_monochrome.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_main.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_splash.xml ================================================ ================================================ FILE: app/src/main/res/layout/choose_app_card.xml ================================================ ================================================ FILE: app/src/main/res/layout/dialog_choose_app.xml ================================================ ================================================ FILE: app/src/main/res/layout/feed_app_card.xml ================================================ ================================================ FILE: app/src/main/res/layout/fragment_about.xml ================================================ ================================================ FILE: app/src/main/res/layout/fragment_choose_app.xml ================================================